jQuery(function ($) {
	var mediaUploader;
	var hiddenField = "";
	var imageField = "";

	$('a.chama-external-url').attr('target', '_blank');
	//Color picker
	$('.color-picker').wpColorPicker();

	//single image uploader
	$('.chama-image-uploader').on('click', function (e) {
		e.preventDefault();
		hiddenField = $(this).data('hidden');
		imageField = $(this).data('image');
		if (mediaUploader) {
			mediaUploader.open();
			return;
		}

		mediaUploader = wp.media.frames.file_frame = wp.media({
			title: 'Select an Image For Your Button',
			button: {
				text: 'Choose this image'
			},
			multiple: false
		});

		mediaUploader.on('select', function () {

		});

		mediaUploader.on('close', function () {
			attachment = mediaUploader.state().get('selection').first().toJSON();
			$('#' + hiddenField).val(attachment.url);
			$('#' + imageField).attr("src", attachment.url);
			hiddenField = "";
			imageField = "";
		});

		mediaUploader.open();

	});
	$('.chama-delete-image').on('click', function (e) {
		e.preventDefault();
		hiddenField = $(this).data('hidden');
		imageField = $(this).data('image');
		noImageUrl = $(this).data('noimage');
		$('#' + hiddenField).val('');
		$('#' + imageField).attr("src", noImageUrl);
		hiddenField = "";
		imageField = "";
	});


	//gallery image uploader
	$(document.body).on('click', '.chama-gallery-upload-button', function (event) {
		// prevent default link click event
		event.preventDefault();

		const button = $(this);
		// we are going to use <input type="hidden"> to store image IDs, comma separated
		const hiddenField = button.prev();
		const hiddenFieldValue = hiddenField.val();
		const hiddenFieldValueArray = hiddenFieldValue ? hiddenFieldValue.split(',') : [];

		const customUploader = wp.media({
			title: 'Insert images',
			library: {
				type: 'image'
			},
			button: {
				text: 'Use these images'
			},
			multiple: true
		}).on('select', function () {

			// get selected images and rearrange the array
			let selectedImages = customUploader.state().get('selection').map(item => {
				item.toJSON();
				return item;
			})

			selectedImages.map(image => {
				// add every selected image to the <ul> list
				$('.chama-commission-gallery').append('<li data-id="' + image.id + '"><span class="chama-preview-image" style="background-image:url(' + image.attributes.url + ')"></span><a class="button chama-commission-gallery-remove" data-hidden="commission_preview_images" data-id="' + image.id + '" href="#">Remove</a></li>');
				// and to hidden field
				hiddenFieldValueArray.push(image.id)
			});

			// refresh sortable
			$('.chama-commission-gallery').sortable('refresh');
			// add the IDs to the hidden field value
			hiddenField.val(hiddenFieldValueArray.join());

		}).open();
	});

	// remove image event
	$(document.body).on('click', '.chama-commission-gallery-remove', function (event) {

		event.preventDefault();

		const button = $(this);
		const imageId = button.data('id');
		const container = button.parent().parent();
		//const hiddenField = $('#' + button.data('hidden') );
		const hiddenField = $('input:hidden[name=' + button.data('hidden') + ']');
		const hiddenFieldValue = hiddenField.val();
		const hiddenFieldValueArray = hiddenFieldValue ? hiddenFieldValue.split(',') : [];
		for (var j = 0; j < hiddenFieldValueArray.length; j++) { hiddenFieldValueArray[j] = parseInt(hiddenFieldValueArray[j]); }
		const i = hiddenFieldValueArray.indexOf(imageId);

		//alert($('input:hidden[name=commission_preview_images]').val());
		//console.log(hiddenFieldValueArray );
		//console.log(imageId );
		button.parent().remove();

		// remove certain array element
		if (i != -1) {
			hiddenFieldValueArray.splice(i, 1);

		}

		// add the IDs to the hidden field value 
		hiddenField.val(hiddenFieldValueArray.join());

		// refresh sortable
		container.sortable('refresh');

	});

	// reordering the images with drag and drop
	$('.chama-commission-gallery').sortable({
		items: 'li',
		cursor: '-webkit-grabbing', // mouse cursor
		scrollSensitivity: 40,
		/*
		You can set your custom CSS styles while this element is dragging
		start:function(event,ui){
			ui.item.css({'background-color':'grey'});
		},
		*/
		stop: function (event, ui) {
			ui.item.removeAttr('style');

			let sort = new Array() // array of image IDs
			const container = $(this) // .chama-commission-gallery

			// each time after dragging we resort our array
			container.find('li').each(function (index) {
				sort.push($(this).attr('data-id'));
			});
			// add the array value to the hidden input field
			container.parent().next().val(sort.join());
			// console.log(sort);
		}
	});

	$(document.body).on('click', '.chama-sync-subscription-renewals', function (event) {
		event.preventDefault();
		$("#chama-sync-renewals-spinner").show();
		$(this).attr('disabled', true);
		$(this).addClass('disabled');
		post_id = $(this).data('id');
		stripe_subscription_id = $(this).data('stripe-subscription-id');
		nonce = $(this).data('nonce');
		data = {
			action: 'chama_synchronize_subscription_renewals',
			chama_nonce: nonce,   // pass the nonce here
			id: post_id,
			stripe_subscription_id: stripe_subscription_id,
		};
		$.post(ajaxurl, data, function (response) {
			$(".chama-renewal-response").addClass('chama-response-success');
			$(".chama-renewal-response").html(response);
			$(".chama-renewal-response").fadeIn();
			$("#chama-sync-renewals-spinner").hide();
			$('.chama-sync-subscription-renewals').attr('disabled', false);
			$('.chama-sync-subscription-renewals').removeClass('disabled');
		})
			.fail(function (response) {
				$(".chama-renewal-response").addClass('chama-response-error');
				$(".chama-renewal-response").html('Error: ' + response.responseText);
			});
	});
	$(document.body).on('click', '.chama-close-admin-modal', function (event) {
		self.parent.tb_remove();
		event.preventDefault();
	});
	$(document.body).on('click', '.chama-admin-process-cancelation', function (event) {
		event.preventDefault();
		$(".chama-admin-processing").show();
		$(this).attr('disabled', true);
		$(this).addClass('disabled');
		post_id = $(this).data('id');
		stripe_subscription_id = $(this).data('stripe-subscription-id');
		nonce = $(this).data('nonce');
		data = {
			action: 'chama_cancel_subscription',
			chama_nonce: nonce,   // pass the nonce here
			id: post_id,
			stripe_subscription_id: stripe_subscription_id,
		};
		$.post(ajaxurl, data, function (response) {
			$("#chama_subscription_status").val('canceled');
			$("#chama-subscription-status").removeClass('active');
			$("#chama-subscription-status").addClass('canceled');
			$(".chama-cancelation-response").addClass('chama-response-success');
			$(".chama-cancelation-response").html(response);
			$(".chama-cancelation-response").fadeIn();
			$(".chama-admin-processing").hide();
		})
			.fail(function (response) {
				$(".chama-admin-processing").hide();
				$(".chama-cancelation-response").addClass('chama-response-error');
				$(".chama-cancelation-response").html('Error: ' + response.responseText);
			});
	});
	/*  Campaign CPT */
	//FAQ repeater
	$('#add-faq-row').on('click', function () {
		var row = $('.faq-empty-row.screen-reader-text').clone(true);
		row.removeClass('faq-empty-row screen-reader-text');
		row.insertBefore('#campaign-faqs-repeater tbody>tr:last');
		return false;
	});

	$('.remove-faq-row').on('click', function () {
		$(this).parents('tr').remove();
		return false;
	});
	//Updates repeater
	$('#add-update-row').on('click', function () {
		var row = $('.update-empty-row.screen-reader-text').clone(true);
		row.removeClass('update-empty-row screen-reader-text');
		row.insertBefore('#campaign-updates-repeater tbody>tr:last');
		return false;
	});

	$('.remove-update-row').on('click', function () {
		$(this).parents('tr').remove();
		return false;
	});
	/*  Commissions CPT */
	//Add-ons repeater
	$('#add-add-on-row').on('click', function () {
		var row = $('.add-on-empty-row.screen-reader-text').clone(true);
		row.removeClass('add-on-empty-row screen-reader-text');
		row.insertBefore('#commission-add-ons-repeater tbody>tr:last');
		return false;
	});

	$('.remove-add-on-row').on('click', function () {
		$(this).parents('tr').remove();
		return false;
	});

	//Shipping options repeater
	$('#add-shipping-price-row').on('click', function () {
		var row = $('.shipping-empty-row.screen-reader-text').clone(true);
		row.removeClass('shipping-empty-row screen-reader-text');
		row.insertBefore('#commission-shipping-prices-repeater tbody>tr:last');
		return false;
	});

	$('.remove-shipping-price-row').on('click', function () {
		$(this).parents('tr').remove();
		return false;
	});
});