(function ($) {
	var progressTemplate = _.template($('#tm-import-progress').html()),
		$result = $('#tm-import-result'),
		importing = false;

	function get_progressbar_element(data) {
		return $result.find('#tm-import-progress-' + data + ' .tm-import-progressbar');
	}

	function tm_import(demo, type, data, step) {
		importing = true;

		// Do AJAX
		$.ajax({
			url: ajaxurl,
			type: 'POST',
			dataType: 'json',
			data: {
				action: 'tm_import',
				demo: demo,
				type: type,
				data: data,
				step: step
			},
			success: function (response) {
				if (typeof response.step != 'undefined') {
					// Display progressbar when the step equals to 1
					if (1 == response.step) {
						var title = 'Import ' + tm_import_data.types[data];

						$result.append(progressTemplate({title: title, data: data}));
						get_progressbar_element(data).progressbar({
							value: 0
						});
					}

					var $bar = get_progressbar_element(response.data),
						percent = response.step / response.length * 100;

					$bar.progressbar('option', 'value', percent);

					if ( percent >= 100 ) {
						$bar.find('.ui-progressbar-value').addClass('done');
					}
				}

				if (typeof response.next_data == 'undefined') {
					tm_import(response.demo, response.type, response.data, response.step);
				} else if ('none' != response.next_data) {
					tm_import(response.demo, response.type, response.next_data, 0);
				} else if ('none' == response.next_data) {
					$('body').trigger('tm_import_done');
				}
			},
			error: function(xhr, ajaxOptions, thrownError) {
				alert("There is a error. Please contact our support staff.\r\n" + thrownError + "\r\n" + xhr.responseText);
			}
		});
	}

	window.onbeforeunload = function(evt){
		if ( true == importing ) {
			if (!evt) {
				evt = window.event;
			}

			evt.cancelBubble = true;
			evt.returnValue = 'The importer is running. Please don\'t navigate away from this page.';

			if (evt.stopPropagation) {
				evt.stopPropagation();
				evt.preventDefault();
			}
		}
	};

	$(document).ready(function () {
		var $trigger = $('.tm-demo-source-install');

		$trigger.on('click', function (evt) {
			evt.preventDefault();

			if (!confirm('Do you want to import this demo?')) {
				return false;
			}

			var $this = $(this);

			$this.addClass('installing').html('Installing...');

			$trigger.prop('disabled', true);

			tm_import($this.data('demo'), 'all', 'all', 0);
		});

		$('body').on('tm_import_done', function () {
			importing = false;

			$trigger
				.prop('disabled', false)
				.filter('.installing')
				.html('Install');

			alert('Import is successful!');
		});
	});
})(jQuery);