"use strict";

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

	function initiateImport( progressItem, all ) {

		all = typeof all !== 'undefined' ? all : false;

		var funcName = 'meridian-one-ajax-' + progressItem.data('meridian-one-func-name');

		jQuery('.meridian-one-importer-row').show();
		progressItem.show();
		progressItem.find('span').show();

		jQuery.post(

			MeridianOneImporterAjax.ajaxurl,
			{
				action : funcName,
			},
			function( response ) {

				if ( response.status == 'success' ) {
					progressItem.find('strong').show();
				} else {
					alert( 'Something went wrong, please try again.' );
				}

				if ( progressItem.next('.meridian-one-importer-progress-item').length ) {
					initiateImport( progressItem.next('.meridian-one-importer-progress-item'), all );
				} else {
					progressItem.after('<hr><strong>All Finished</strong>');
					progressItem.closest('.meridian-one-importer-row').find('.meridian-one-importer-hook').text('Installed');
					if ( all ) {
						if ( progressItem.closest('.meridian-one-importer-row').next('.meridian-one-importer-row').length ) {
							initiateImport( progressItem.closest('.meridian-one-importer-row').next('.meridian-one-importer-row').find('.meridian-one-importer-progress-item:first-child'), all );
						}
					}
				}

			}

		);

	}

	function initiateImportAll() {

		initiateImport( jQuery('.meridian-one-importer-row .meridian-one-importer-progress-item:first-child'), true );

	}

	jQuery(document).on( 'click', '.meridian-one-importer-hook:not(.button-disabled)', function(e){

		e.preventDefault();

		var _this = jQuery(this),
		progress = _this.closest('.meridian-one-importer-row').find('.meridian-one-importer-progress'),
		funcName,
		progressItem;

		// Disable button
		_this.hide();

		// Initiate Import
		initiateImport( progress.find('.meridian-one-importer-progress-item:first-child'), false );

	});

	jQuery(document).on( 'click', '.meridian-one-importer-all-hook:not(.button-disabled)', function(e){

		e.preventDefault();

		var _this = jQuery(this);

		// Disable button
		_this.hide()

		// Initiate Import
		initiateImportAll();

	});

});