# cartflows/1.0.4/assets/js/import.js

CartFlows – Funnel Builder &amp; Checkout Plugin for WooCommerce, version 1.0.4. 1,171 lines.

- Page: https://pluginprobe.com/plugins/cartflows/1.0.4/code/assets/js/import.js
- Raw: https://pluginprobe.com/plugins/cartflows/1.0.4/raw/assets/js/import.js
- Modified: 2018-11-30T13:26:54+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/cartflows/1.0.4/code/assets/js/import.js#L10-L20`.

```javascript
/**
 * AJAX Request Queue
 *
 * - add()
 * - remove()
 * - run()
 * - stop()
 *
 * @since 1.0.0
 */

var CartFlowsAjaxQueue = (function() {

	var requests = [];

	return {

		/**
		 * Add AJAX request
		 *
		 * @since 1.0.0
		 */
		add:  function(opt) {
		    requests.push(opt);
		},

		/**
		 * Remove AJAX request
		 *
		 * @since 1.0.0
		 */
		remove:  function(opt) {
		    if( jQuery.inArray(opt, requests) > -1 )
		        requests.splice($.inArray(opt, requests), 1);
		},

		/**
		 * Run / Process AJAX request
		 *
		 * @since 1.0.0
		 */
		run: function() {
		    var self = this,
		        oriSuc;

		    if( requests.length ) {
		        oriSuc = requests[0].complete;

		        requests[0].complete = function() {
		             if( typeof(oriSuc) === 'function' ) oriSuc();
		             requests.shift();
		             self.run.apply(self, []);
		        };

		        jQuery.ajax(requests[0]);

		    } else {

		      self.tid = setTimeout(function() {
		         self.run.apply(self, []);
		      }, 1000);
		    }
		},

		/**
		 * Stop AJAX request
		 *
		 * @since 1.0.0
		 */
		stop:  function() {

		    requests = [];
		    clearTimeout(this.tid);
		}
	};

}());


(function($){

	CartFlowsImport = {

		doc     : $( document ),
		wrap    : $( '.wcf-flow-steps-data-wrap' ),
		inner   : $( '.wcf-flow-steps-data-wrap-importer' ),
		post_id : $( '#post_ID' ).val(),

		_ref			: null,

		_api_step_type : {},
		_api_params		: {},

		all_steps       : 0,
		remaining_steps : 0,

		/**
		 * Init
		 */
		init: function()
		{
			this._bind();

			if( $('.wcf-step-wrap').length ) {
				this._set_category_slugs();
			}

			if( $('.post-type-cartflows_flow').hasClass('edit-php') ) {
				this._cache_remote_flows();
			}
			if( $('.post-type-cartflows_flow').hasClass('post-php') ) {
				this._cache_remote_steps();
			}

			if( $('.post-type-cartflows_flow').hasClass('edit-php') && null !== this._getParamFromURL('add-new-flow') ) {
				this._render_remote_flows();
			}

			if( $('.post-type-cartflows_flow').hasClass('post-php') && null !== this._getParamFromURL('add-new-step') ) {
				this._render_remote_steps();
			}

	        if( this._getParamFromURL('highlight-step-id') ) {
	        	var selector = $('.wcf-step-wrap[data-id="'+this._getParamFromURL('highlight-step-id')+'"]');
	        	if( selector.length ) {
        		    $('html, body').animate({
				        scrollTop: selector.offset().top
				    }, 1500);
	        	}
	        }
		},

		/**
		 * Get URL param.
		 */
		_getParamFromURL: function(name, url)
		{
		    if (!url) url = window.location.href;
		    name = name.replace(/[\[\]]/g, "\\$&");
		    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
		        results = regex.exec(url);
		    if (!results) return null;
		    if (!results[2]) return '';
		    return decodeURIComponent(results[2].replace(/\+/g, " "));
		},

		_set_category_slugs: function() {

			// API Request.
			var api_params = {
				_fields : CartFlowsImportVars.step_type_fields.toString(),
			};

			var api_post = {
				slug    : CartFlowsImportVars.step_type + '?' + decodeURIComponent( $.param( api_params ) ),
			};

			CartFlowsAPI._api_request( api_post, function( data ) {
				if( parseInt( data.items_count ) && $.isEmptyObject( CartFlowsImport._api_step_type ) ) {
					CartFlowsImport._api_step_type = data.items;
				}
			} );
		},

		/**
		 * Binds events
		 */
		_bind: function()
		{
			var self = CartFlowsImport;

			self.doc.on('click', '.cartflows-flow-import-blank',	self._create_default_flow);
			self.doc.on('click', '#wcf-remote-flow-importer .wcf-page-builder-links a',	self._show_page_bulider_for_flow);
			// self.doc.on('click', '#wcf-remote-flow-importer .filter-links a', self._filterFlowClick );
			self.doc.on('click', '#wcf-remote-step-importer .wcf-page-builder-links a',	self._show_page_bulider_for_step);
			self.doc.on('click', '#wcf-remote-step-importer .step-type-filter-links a', self._filterStepClick );

			self.doc.on('click'                 , '.cartflows-step-import-blank:not(.get-pro)',	self._create_blank_step);
			self.doc.on('click'                 , '#wcf-remote-step-importer .cartflows-step-import',	self._import_step);
			self.doc.on('click'                 , '#wcf-remote-flow-importer .cartflows-step-import',	self._import_flow);

			self.doc.on('click'                 , '.cartflows-preview-flow-step',	self._preview_individual);

			self.doc.on( 'add_template_to_page-fail', self._add_template_to_page_fail);

			// self.doc.on( 'trigger-on-templates-load', self._on_templates_load );

			$( 'body' ).on('thickbox:iframe:loaded', 					self._previewLoaded );

			// Event's for API request.
			// $( document ).on('keyup input', '#wcf-remote-flow-importer .wcf-flow-search-input', 	self._remote_flow_search );
			$( document ).on('keyup input', '#wcf-remote-step-importer .wcf-flow-search-input', 	self._remote_step_search );

			$( document ).on('click', '.actions a', 					self._previewResponsive );

			$( document ).on( 'click', '.page-title-action', self._render_remote_flows );
			$( document ).on( 'click', '.wcf-trigger-popup', self._render_remote_steps );

			$( document ).on( 'click', '.wcf-templates-popup-overlay', self._close_template_popup );
			$( document ).on( 'click', '.wcf-popup-close-wrap .close-icon', self._close_template_popup );

			// $( document ).on( 'click', '.wcf-tab > li > a', self._switch_step_tab );
		},

		_switch_step_tab: function( event ) {

			event.preventDefault();//stop browser to take action for clicked anchor
						
			//get displaying tab content jQuery selector
			var active_tab_selector = $('.wcf-tab > li.active > a').attr('href');					
						
			//find actived navigation and remove 'active' css
			var actived_nav = $('.wcf-tab > li.active');
			actived_nav.removeClass('active');
						
			//add 'active' css into clicked navigation
			$(this).parents('li').addClass('active');
						
			//hide displaying tab content
			$(active_tab_selector).removeClass('active');
			$(active_tab_selector).addClass('hide');
						
			//show target tab content
			var target_tab_selector = $(this).attr('href');
			$(target_tab_selector).removeClass('hide');
			$(target_tab_selector).addClass('active');
	    },

		/**
		 * Search Site.
		 *
		 * Prepare Before API Request:
		 * - Remove Inline Height
		 * - Added 'hide-me' class to hide the 'No more sites!' string.
		 * - Added 'loading-content' for body.
		 * - Show spinner.
		 */
		_remote_step_search: function( event ) {

			event.preventDefault();//stop browser to take action for clicked anchor

			// Remove all filter classes.
	        $('.step-type-filter-links').find('a').removeClass('current');
	        $('.step-type-filter-links').find('li:first-child a').addClass('current');

			window.clearTimeout(CartFlowsImport._ref);
			CartFlowsImport._ref = window.setTimeout(function () {
				CartFlowsImport._ref = null;
				CartFlowsImport._showSteps();
	        }, 500);

		},

		/**
		 * Responsive On Click.
		 */
		_previewResponsive: function( event ) {

			event.preventDefault();

			var icon = $(this).find('.dashicons');

			var viewClass = icon.attr('data-view') || '';

			$('#TB_window').removeClass( 'desktop tablet mobile' );
			$('#TB_window').addClass( viewClass );

			$('.actions .dashicons').removeClass('active');
			icon.addClass('active');

			$('#TB_iframeContent').removeClass();
			$('#TB_iframeContent').addClass( viewClass );

		},

		/**
		 * On Filter Clicked
		 */
		_filterStepClick: function( event ) {

			event.preventDefault();

			$(this).parents('.step-type-filter-links').find('a').removeClass('current');
			$(this).addClass('current');

			$step_type = $(this).data('slug');

			if ( 'upsell' === $step_type || 'downsell' === $step_type ) {
				$( '.wcf-template-notice' ).show();

			}else{
				$( '.wcf-template-notice' ).hide();
			}

			CartFlowsImport._showSteps();

			if( '' == CartFlowsImportVars._is_pro_active && ( 'upsell' == $step_type || 'downsell' == $step_type ) ) {
				console.log( 'here' );
				$('.cartflows-step-import-blank').text( 'Get Pro' );
				$('.cartflows-step-import-blank').attr( 'href', CartFlowsImportVars.domain_url );
				$('.cartflows-step-import-blank').attr( 'target', '_blank' );
				$('.cartflows-step-import-blank').addClass('get-pro');
				// 	// $('#wcf-remote-step-list').find('.cartflows-step-import-blank').attr( 'class', 'button button-primary' );
			} else {
				$('.cartflows-step-import-blank').text( 'Create' );
				$('.cartflows-step-import-blank').removeClass( 'get-pro' );
				$('.cartflows-step-import-blank').removeAttr( 'target' );
			}

		},

		_showSteps: function() {

			// Add Params for API request.
			var api_params = {
				licence_args : CartFlowsImportVars.licence_args,
				per_page     : 15,
				_fields      : CartFlowsImportVars.step_fields.toString(),
			};

			// Type.
			var type 		= $('#wcf-remote-step-filters .step-type-filter-links').find('.current').data('group') || '';
			var step_type 	= $('#wcf-remote-step-filters .step-type-filter-links').find('.current').data('slug') || '';
			if( '' !== type && 'all' !== type ) {
				api_params[ CartFlowsImportVars.step_type ] = type;
			}

			// API Request.
			var api_post = {
				slug    : CartFlowsImportVars.step + '?' + decodeURIComponent( $.param( api_params ) ),
			};

			CartFlowsAPI._api_request( api_post, function( data ) {

				data.current_step_type = step_type;

				var template = wp.template('cartflows-steps-list');
				// if( parseInt( data.items_count ) ) {
					$('#wcf-remote-step-list').html( template( data ) );
					$('#wcf-remote-step-list').prepend( wp.template('cartflows-create-blank-step') );
				// } else {
					// $('#wcf-remote-step-list').html( wp.template('cartflows-no-steps') );
				// }
			} );
		},

		_apiAddParam_per_page: function() {
			CartFlowsImport._api_params['per_page'] = 15;
		},

		// Add Params for API request.
		_apiAddParam_licence_args: function() {
			CartFlowsImport._api_params['licence_args'] = CartFlowsImportVars.licence_args;
		},

		// Add 'search'
		_apiAddParam_search: function() {
			var search_val = $('.wcf-flow-search-input').val() || '';
			if( '' !== search_val ) {
				CartFlowsImport._api_params['search'] = search_val;
			}
		},

		_close_popup: function() {
			$('#cartflows-steps').fadeOut();
			$('body').removeClass('cartflows-popup-is-open');
		},

		_post_auto_save: function() {
			var post_title       = $( '#title' );
			var post_prompt_text = $( '#title-prompt-text' );
			var self = CartFlowsImport;

			if ( ! post_title.val() ) {
				post_title.val( 'CartFlows #' + self.post_id );
				if( post_prompt_text.length ) {
					post_prompt_text.remove();
				}
			}

			if ( wp.autosave ) {
				wp.autosave.server.triggerSave();
			}
		},

		_cache_remote_flows: function() {

			// Add Params for API request.
			var api_params = {
				licence_args : CartFlowsImportVars.licence_args,
				hide_empty   : true,
				_fields      : CartFlowsImportVars.flow_type_fields.toString(),
			};

			// API Request.
			var api_post = {
				slug          : CartFlowsImportVars.flow_type + '?'+decodeURIComponent( $.param( api_params ) ),
				wrapper_class : 'flow-type-filter-links filter-links',
				show_all      : false,
			};

			CartFlowsAPI._api_request( api_post, function( data ) {
				var template = wp.template('cartflows-term-filters');
				$('#cartflows-flow-funnel-type').html(template( data ));
				$('#cartflows-flow-funnel-type').find('li:first a').addClass('current');
			} );

			// Add Params for API request.
			var api_params = {
				licence_args : CartFlowsImportVars.licence_args,
				_fields      : CartFlowsImportVars.flow_fields.toString(),
			};

			// API Request.
			var api_post = {
				slug    : CartFlowsImportVars.flow + '?' + decodeURIComponent( $.param( api_params ) ),
			};

			CartFlowsAPI._api_request( api_post, function( data ) {
				var template = wp.template('cartflows-flows-list');
				// if( parseInt( data.items_count ) ) {
					$('#wcf-remote-flow-list').html( template( data ) );

					$('#wcf-remote-flow-list').prepend( wp.template('cartflows-create-blank-flow') );
					


				// } else {
					// $('#wcf-remote-flow-list').html( wp.template('cartflows-no-flows') );
				// }
			} );

		},

		_render_remote_flows: function( event ) {

			if( event ) {
				event.preventDefault();
			}

			$("#wcf-remote-flow-importer").addClass('open');

			$("html").addClass('wcf-popup-open');

			$("#wcf-remote-flow-importer .spinner").css( 'visibility', 'hidden' );
		},

		_cache_remote_steps: function() {

			// Disable the button until caching the data.
			$( 'html' ).addClass('wcf-steps-loading');

			// Add Params for API request.
			var api_params = {
				licence_args : CartFlowsImportVars.licence_args,
				_fields      : CartFlowsImportVars.step_type_fields.toString(),
			};

			// API Request.
			var api_post = {
				slug          : CartFlowsImportVars.step_type + '?'+decodeURIComponent( $.param( api_params ) ),
				wrapper_class : 'step-type-filter-links filter-links',
				show_all      : false,
			};

			CartFlowsAPI._api_request( api_post, function( data ) {

				var step_type_response_data = data;
				var step_types_count        = data.items_count;

				// Send other request for JS caching.
				if( data.items ) {
					for ( key in data.items ) {

						// Add Params for API request.
						var api_params = {
							licence_args : CartFlowsImportVars.licence_args,
							per_page     : 15,
							_fields      : CartFlowsImportVars.step_fields.toString(),
						};

						api_params[ CartFlowsImportVars.step_type ] = data.items[ key ].id;

						// API Request.
						var api_post = {
							slug    : CartFlowsImportVars.step + '?' + decodeURIComponent( $.param( api_params ) ),
						};

						CartFlowsAPI._api_request( api_post, function( data ) {
							var template = wp.template('cartflows-steps-list');
							if( parseInt( data.items_count ) ) {
								$('#wcf-remote-step-list').html( template( data ) );
								$('#wcf-remote-step-list').prepend( wp.template('cartflows-create-blank-step') );
							} else {
								$('#wcf-remote-step-list').html( wp.template('cartflows-no-steps') );
							}

							step_types_count--;

							if( 0 == step_types_count ) {

								var template = wp.template('cartflows-term-filters');
								$('#wcf-remote-step-filters').html(template( step_type_response_data ));
								$('#wcf-remote-step-filters').find('li:first a').addClass('current');

								$('#wcf-remote-content').find( '.spinner' ).remove();

								CartFlowsImport._showSteps();

								$( 'html' ).removeClass('wcf-steps-loading');
							}
						});
					}
				}
			} );
		},

		_render_remote_steps: function( event ) {

			if( event ) {
				event.preventDefault();
			}

			$("#wcf-remote-step-importer").addClass('open');

			$("html").addClass('wcf-popup-open');

			if( $( 'html' ).hasClass('wcf-steps-loading') ) {
				$('#wcf-remote-content').append( '<span class="spinner is-active"></span>' );
			} else {
				CartFlowsImport._showSteps();
			}

		},

		_categorize_data: function( items ) {
				
			var categorised_data = [];

			$.each( items, function( index, value ) {

				var step_type = value.step_type.slug;

				if( 'undefined' == typeof categorised_data[step_type] ) {
					categorised_data[step_type] = [];
				}
					
				categorised_data[step_type].push( value );

			});

			return categorised_data;

		},
		
		_close_template_popup: function( event ) {
			if ( $( event.target ).hasClass('wcf-templates-popup-overlay') 
			 || $( event.target ).hasClass('close-icon') ) {

				// New step creation/importing is in process..
			 	if( ! $( '.wcf-templates-popup-overlay' ).hasClass('request-process') ) {
					$("html").removeClass('wcf-popup-open');
					$(".wcf-templates-popup-overlay").removeClass( 'open' );
			 	}
			}
		},

		_ajax: function( data, callback, trigger ) {

			var self = CartFlowsImport;

			$.ajax({
				url  : ajaxurl,
				type : 'POST',
				data : data,
			})
			.done(function( request, status, XHR )
			{
				var data = {
					request : request,
					status  : status,
					XHR     : XHR,
				};

				if( callback && typeof callback == "function"){
					callback( data );
				}

				self.doc.trigger( trigger + '-done', [request, status, XHR] );
			})
			.fail(function( jqXHR, textStatus )
			{
				self.doc.trigger( trigger + '-fail', [jqXHR, textStatus] );
			})
			.always(function()
			{
				self.doc.trigger( trigger + '-always' );
			});

		},

		_load_templates: function( args, trigger_name ) {
			var self = CartFlowsImport;

			if( $('body').hasClass('processing') ) {
				return;
			}

			$('body').addClass('processing');

			$.ajax({
				url  : ajaxurl,
				type : 'POST',
				data : {
					action  : 'cartflows_load_steps',
					security: cartflows_admin.cf_load_steps_nonce,
					args    : args,
				},
			})
			.done(function( items, status, XHR )
			{
				self.doc.trigger( trigger_name, [items] );
				$('body').removeClass('processing');
			})
			.fail(function( jqXHR, textStatus )
			{
			})
			.always(function()
			{
			});
		},

		_empty: function(data)
		{
		  if(typeof(data) == 'number' || typeof(data) == 'boolean')
		  { 
		    return false; 
		  }
		  if(typeof(data) == 'undefined' || data === null)
		  {
		    return true; 
		  }
		  if(typeof(data.length) != 'undefined')
		  {
		    return data.length == 0;
		  }
		  var count = 0;
		  for(var i in data)
		  {
		    if(data.hasOwnProperty(i))
		    {
		      count ++;
		    }
		  }
		  return count == 0;
		},

		_preview_individual: function()
		{
			var id    = $(this).data('id') || '';
			var href  = $(this).data('href') || '';

			// Active.
			$('.cartflows-preview-flow-step').removeClass('active');
			$('.cartflows-preview-flow-step[data-id="'+id+'"]').addClass('active');

			$('#TB_window').addClass('cartflows-thickbox-loading');

			$('#TB_iframeContent').removeAttr('onload');
			$('#TB_iframeContent').removeAttr('src');
			$('#TB_iframeContent').attr('src', href );
			$('#TB_iframeContent').attr('onload', 'CartFlowsImport.showIframe()' )
		},
		showIframe: function() {
			$("#TB_load").remove();
			$("#TB_window").css({'visibility':'visible'});
			// $("#TB_window").css({'visibility':'visible'}).trigger( 'thickbox:iframe:loaded' );
			$('#TB_window').removeClass('cartflows-thickbox-loading');
		},

		/**
		 * Remove thickbox loading class
		 * 
		 * @param  object event Event object.
		 * @return void.
		 */
		_previewLoaded: function( event ) {
			event.preventDefault();
			$('#TB_window').removeClass('cartflows-thickbox-loading');
		},

		_show_page_bulider_for_step: function( event ) {
			event.preventDefault();
			var id    = $(this).data( 'id' ) || '';
			var title = $(this).text() || '';

			$(this).parents('.wcf-page-builder-links').find('a').removeClass('current');
			$(this).addClass('current');

			if( 'elementor' == id ) {
				$('#wcf-upcoming-page-builders').hide().html('');
				$('#wcf-remote-step-list').show();
			} else {
				$('#wcf-upcoming-page-builders').show().html('<p class="description">Templates for '+title+' are coming soon.</p>');
				$('#wcf-upcoming-page-builders').show().prepend( wp.template('cartflows-create-blank-step') );
				$('#wcf-remote-step-list').hide();
			}
		},

		_show_page_bulider_for_flow: function( event ) {
			event.preventDefault();
			var id    = $(this).data( 'id' ) || '';
			var title = $(this).text() || '';

			$(this).parents('.wcf-page-builder-links').find('a').removeClass('current');
			$(this).addClass('current');

			if( 'elementor' == id ) {
				$('#wcf-upcoming-page-builders').hide().html('');
				$('#wcf-remote-flow-list').show();
			} else {
				$('#wcf-upcoming-page-builders').show().html('<p class="description">Templates for '+title+' are coming soon.</p>');
				$('#wcf-upcoming-page-builders').show().prepend( wp.template('cartflows-create-blank-flow') );
				$('#wcf-remote-flow-list').hide();
			}
		},

		_create_default_flow: function( event )
		{
			event.preventDefault();
			var self = CartFlowsImport;
			var btn = $( this );

			if( btn.hasClass('updating-message') ) {
				return;
			}

			$('#wcf-remote-flow-importer').addClass('request-process');

			btn.addClass('updating-message').text( 'Creating Flow..' );
			btn.parents('.template').addClass('importing');

			var data = {
				action : 'cartflows_default_flow',
				security: cartflows_admin.cf_default_flow_nonce
			};

			// Import Template AJAX.
			self._ajax( data, function( data ) {

				if( data.request.success ) {


					var flow_id = data.request.data; // $( 'form#post #post_ID').val();
					// Created.
					setTimeout(function() {
						btn.removeClass('updating-message').text('Flow Created! Redirecting..');
						window.location = CartFlowsImportVars.admin_url + 'post.php?post='+flow_id+'&action=edit';
					}, 3000);

				}
			});

		},

		_activate_plugin: function( plugin_slug ) {

			var self = CartFlowsImport;

			var data = {
				action      : 'cartflows_activate_plugin',
				plugin_slug : plugin_slug
			};

			self._ajax( data, function( data ) {
			});
		},

		_process_import_flow: function( response )
		{

			var self = CartFlowsImport;
			var btn = $( '#wcf-remote-flow-importer .cartflows-step-import.updating-message' );

			var plugin_slug = '';
			plugin = response.slug;

			switch ( plugin ) {
				case 'elementor':
					plugin_slug = 'elementor/elementor.php';
				break;
			}

			self._activate_plugin( plugin_slug );

			btn.text( 'Creating Flow..' );

			var flow_steps_string = btn.data('flow-steps') || '';
			var flow_steps = ( '' !== flow_steps_string ) ? JSON.parse("[" + flow_steps_string + "]") : [];

			var data = {
				action : 'cartflows_create_flow',
				security: cartflows_admin.cf_create_flow_nonce
			};

			// Import Template AJAX.
			self._ajax( data, function( data ) {

				if( data.request.success ) {

					var flow_id = data.request.data; // $( 'form#post #post_ID').val();

					if( flow_steps ) {

						// Activate ALl Plugins.
						CartFlowsAjaxQueue.stop();
						CartFlowsAjaxQueue.run();

						CartFlowsImport.all_steps = flow_steps.length;

						// Importing.
						btn.addClass('updating-message').text('Importing Step 1 of ' + CartFlowsImport.all_steps );

						$.each(flow_steps, function(index, template_id) {

							CartFlowsAjaxQueue.add({
								url: CartFlowsImportVars.ajaxurl,
								type: 'POST',
								data: {
									action      : 'cartflows_import_flow_step',
									flow_id     : flow_id,
									template_id : template_id,
									security    : cartflows_admin.cf_import_flow_step_nonce
								},
								success: function( result ) {
									CartFlowsImport.remaining_steps = CartFlowsImport.remaining_steps + 1;

									if( CartFlowsImport.remaining_steps === CartFlowsImport.all_steps ) {

										// Imported.
										btn.addClass('updating-message').text('Imported Step ' + CartFlowsImport.remaining_steps  + ' of ' + CartFlowsImport.all_steps );

										setTimeout(function() {
											btn.removeClass('updating-message').text('All Imported! Redirecting..');
											window.location = CartFlowsImportVars.admin_url + 'post.php?post='+flow_id+'&action=edit';
										}, 3000);

									} else {
										// Importing.
										btn.addClass('updating-message').text('Importing Step ' + CartFlowsImport.remaining_steps  + ' of ' + CartFlowsImport.all_steps );
									}
								},
								error: function( result ) {
									CartFlowsImport.remaining_steps = CartFlowsImport.remaining_steps + 1;

									template = btn.parents('.template.importing');
									template.find('.preview')
										.addClass('notice notice-warning')
										.removeClass('preview')
										.text( result.statusText );

									if( CartFlowsImport.remaining_steps === CartFlowsImport.all_steps ) {

										// Imported.
										btn.addClass('updating-message').text('Failed ' + CartFlowsImport.remaining_steps  + ' of ' + CartFlowsImport.all_steps );

										setTimeout(function() {
											btn.removeClass('updating-message button-primary').addClass('disabled');
											// location.reload();
										}, 3000);

									} else {
										// Importing.
										btn.addClass('updating-message').text('Failed ' + CartFlowsImport.remaining_steps  + ' of ' + CartFlowsImport.all_steps );
									}
								},
								fail: function( result ) {
									
									CartFlowsImport.remaining_steps = CartFlowsImport.remaining_steps + 1;

									if( CartFlowsImport.remaining_steps === CartFlowsImport.all_steps ) {

										// Imported.
										btn.addClass('updating-message').text('Imported ' + CartFlowsImport.remaining_steps  + ' of ' + CartFlowsImport.all_steps );

										setTimeout(function() {
											btn.removeClass('updating-message').text('All Step Imported! Reloading..');
											location.reload();
										}, 3000);

									} else {
										// Importing.
										btn.addClass('updating-message').text('Importing ' + CartFlowsImport.remaining_steps  + ' of ' + CartFlowsImport.all_steps );
									}
								}
							});
						});
					}
				}
			});
		},

		_import_flow: function() 
		{
			var btn = $( this );
			var plugins = btn.data('required');

			if( btn.hasClass('updating-message') ) {
				return;
			}

			$('#wcf-remote-flow-importer').addClass('request-process');

			if( ! $.isEmptyObject( plugins ) ) {

				btn.addClass('updating-message');
				btn.parents('.template').addClass('importing');
				
				if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) {
					wp.updates.requestFilesystemCredentials( event );
				}

				$.each( plugins, function( plugin_slug, plugin ) {

					var is_installed = plugin.install;
					var is_active = plugin.active;

					if( 'no' == is_installed ) {

						btn.text( 'Installing ' + plugin_slug + '...' );
						
						wp.updates.installPlugin({
							slug: plugin_slug,
							success: CartFlowsImport._process_import_flow,
							error: CartFlowsImport._handle_error
						});

					} else {

						if( 'no' == is_active ) {
							btn.text( 'Activating ' + plugin_slug + '...' );
						}
						
						var data = {
							slug: plugin_slug
						};

						CartFlowsImport._process_import_flow( data );	
					}
				});
			}
		},

		_handle_error: function( response ) 
		{
			var btn = $( '.cartflows-step-import.updating-message' );

			btn.addClass('updating-message').text( response.errorMessage );
		},

		_create_blank_step: function( event )
		{
			event.preventDefault();

			var btn    	   		  = $(this),
				self              = CartFlowsImport,
				flow_id           = $("#post_ID").val(),
				step_slug         = $('.step-type-filter-links .current').data('slug') || '',
				step_title        = $('.step-type-filter-links .current').data('title') || '',
				step_type         = step_slug,
				step_count        = $('.wcf-step-wrap[data-term-slug="'+step_slug+'"]').length || 1;
				step_custom_title = `${step_title} ${step_count+1}`;


			if ( ! CartFlowsImportVars._is_pro_active && ( 'upsell' === step_type || 'downsell' === step_type )) {
				return;
			}
			
			$('#wcf-remote-step-importer').addClass('request-process');

			$('.cartflows-step-import').addClass('disabled');
			btn.addClass('importing updating-message').text('Creating..');
			btn.parents('.template').addClass('importing');

			// Process Import Page.
			if( $( 'body' ).hasClass( 'post-type-cartflows_flow' ) ) {
				var data = {
					action     : 'cartflows_step_create_blank',
					flow_id    : flow_id,
					step_type  : step_type,
					step_title : step_custom_title,
					security   : cartflows_admin.cf_step_create_blank_nonce
				};

				// Import Template AJAX.
				self._ajax( data, function( data ) {
					
					var self     = CartFlowsImport;
					var template = btn.parents('.template.importing');

					if( data.request.success ) {
						btn.text('Created. Reloading..');
						setTimeout(function() {
							window.location.href = window.location.href + '&highlight-step-id=' + data.request.data;
						}, 3000);

					} else {
						btn.removeClass('importing updating-message')
							.text('Creating Failed!');

						template.find('.cartflows-step-preview').append( "<div class='preview'></div>" );

						template.find('.preview')
							.addClass('notice notice-warning')
							.removeClass('preview')
							.text( data.request.data );
					}
				} );
			}
		},

		_process_import_step: function( response ) {

			var step_slug         = $('.step-type-filter-links .current').data('slug') || '',
				step_title        = $('.step-type-filter-links .current').data('title') || '',
				step_count        = $('.wcf-step-wrap[data-term-slug="'+step_slug+'"]').length || 1;
				step_custom_title = `${step_title} ${step_count+1}`,
				btn               = $('#wcf-remote-step-importer .cartflows-step-import.updating-message'),
				self 		      = CartFlowsImport;

			var plugin_slug = '';
			plugin = response.slug;

			switch ( plugin ) {
				case 'elementor':
					plugin_slug = 'elementor/elementor.php';
				break;
			}

			self._activate_plugin( plugin_slug );

			var template_id = btn.data('template-id') || '';
			var flow_id     = $("#post_ID").val();
			var step_type   = step_slug; 
			var self        = CartFlowsImport;

			$('.cartflows-step-import-blank').addClass('disabled');
			$('.cartflows-step-import').addClass('disabled');
			btn.addClass('importing updating-message').text('Importing..');

			// Process Import Page.
			if( $( 'body' ).hasClass( 'post-type-cartflows_flow' ) )
			{
				var data = {
					action      : 'cartflows_step_import',
					flow_id     : flow_id,
					template_id : template_id,
					step_title  : step_custom_title,
					step_type   : step_type,
					security    : cartflows_admin.cf_step_import_nonce   
				};

				// Import Template AJAX.
				self._ajax( data, function( data ) {

					var self     = CartFlowsImport;
					var template = btn.parents('.template.importing');

					if( data.request.success ) {
						btn.text('Imported. Reloading..');
						setTimeout(function() {
							window.location.href = window.location.href + '&highlight-step-id=' + data.request.data;
						}, 3000);

					} else {

						$( '.wcf-templates-popup-overlay' ).removeClass('request-process');

						btn.removeClass('importing updating-message')
							.text('Import Failed!');

						template.find('.preview')
							.addClass('notice notice-warning')
							.removeClass('preview')
							.text( data.request.data );
					}

				}, 'add_template_to_page' );
			}
		},

		_import_step: function( event )
		{
			event.preventDefault();
			var btn = $(this);
			var plugins = btn.data('required');

			if( btn.hasClass('updating-message') ) {
				return;
			}

			btn.addClass('updating-message');

			if( ! $.isEmptyObject( plugins ) ) {

				if ( wp.updates.shouldRequestFilesystemCredentials && ! wp.updates.ajaxLocked ) {
					wp.updates.requestFilesystemCredentials( event );
				}

				$('#wcf-remote-step-importer').addClass('request-process');

				$.each( plugins, function( plugin_slug, plugin ) {

					var is_installed = plugin.install;
					var is_active = plugin.active;

					btn.parents('.template').addClass('importing');

					if( 'no' == is_installed ) {

						btn.addClass('updating-message').text( 'Installing ' + plugin_slug + '...' );
						
						wp.updates.installPlugin({
							slug: plugin_slug,
							success: CartFlowsImport._process_import_step,
							error: CartFlowsImport._handle_error
						});

					} else {

						if( 'no' == is_active ) {
							btn.addClass('updating-message').text( 'Activating ' + plugin_slug + '...' );
						}
						
						var data = {
							slug: plugin_slug
						};

						CartFlowsImport._process_import_step( data );	
					}
				});
			}
		 	
		},

		_add_template_to_page_fail: function( event, jqXHR, textStatus ) {
			event.preventDefault();
			var self = CartFlowsImport,
				template = $('.wcf-flow-steps-data-wrap-importer .template.importing');

			template.find('.cartflows-step-import')
				.removeClass('importing updating-message')
				.text('Import Failed!');


			template.find('.preview')
				.addClass('notice notice-warning')
				.removeClass('preview')
				.text( jqXHR.responseText );
		}

	};

	/**
	 * Initialization
	 */
	$(function(){
		CartFlowsImport.init();
	});

})(jQuery);	
```
