/* global STD_Engine */
(function($) {
	'use strict';

	var $wrapper = $('.std-layout, #std-layout-conditions');
	var $template = $wrapper.find('.std-layout-condition-template');
	var $form = $wrapper.find('form');

	var $popup = $wrapper.find('.std-popup');
	var allowSubmit = true;

	// Change status.
	$(document).on('click', '.column-std_layout_status .std-switcher-btn', function() {
		var $switcher = $(this);

		$switcher.addClass('std-loading');

		$.ajax({
			url     : STD_Engine.ajaxUrl,
			method  : 'POST',
			data    : {
				action  : 'std_layout_change_status',
				id      : $switcher.data('id'),
				status  : 'publish' === $switcher.data('status') ? 'draft' : 'publish',
				security: STD_Engine.get_new_template_nonce
			},
			dataType: 'json',
			success : function(response) {
				$switcher.replaceWith(response.new_html);
			},
			error   : function() {
				$popup.find('.std-layout-popup-notices').text('');
				$popup.find('.std-layout-popup-notices').append('<div class="std-notice std-warning">مشکلی در ایجاد طراحی رخ داده است !</div>');
				$popup.removeClass('std-loading');
			}
		});
	});

	// Form.
	$form.on('submit', function(e) {
		e.preventDefault();

		if (allowSubmit) {
			allowSubmit = false;
		} else {
			return false;
		}

		var data = [];
		var layoutType = $form.find('.std-layout-type').val();
		var layoutName = $form.find('.std-layout-name').val();

		$form.find('.std-layout-condition').each(function() {
			var $condition = $(this);
			data.push({
				condition_comparison: $condition.find('.std-layout-condition-comparison').val(),
				condition_type      : $condition.find('.std-layout-condition-type').val(),
				condition_query     : $condition.find('.std-layout-condition-query').val()
			});
		});

		$popup.addClass('std-loading');

		$.ajax({
			url     : STD_Engine.ajaxUrl,
			method  : 'POST',
			data    : {
				action         : 'std_layout_create',
				data           : data,
				type           : layoutType,
				name           : layoutName,
				predefined_name: $form.find('.std-layout-predefined-layout.std-active').data('name'),
				security       : STD_Engine.get_new_template_nonce
			},
			dataType: 'json',
			success : function(response) {
				window.location.href = response.redirect_url;
			},
			error   : function() {
				$popup.find('.std-layout-popup-notices').text('');
				$popup.find('.std-layout-popup-notices').append('<div class="std-notice std-warning">مشکلی در ایجاد طراحی رخ داده است !</div>');
				$popup.removeClass('std-loading');
			}
		});
	});

	// Change layout type.
	$form.find('.std-layout-type').on('change', function() {
		var layoutType = $(this).val();

		$form.find('.std-layout-condition').remove();

		$('.std-layout-predefined-layouts').addClass('std-hidden');
		$('.std-layout-predefined-layout').removeClass('std-active');

		if (!layoutType) {
			$wrapper.find('.std-layout-condition-add').addClass('std-hidden');
			$wrapper.find('.std-layout-submit').addClass('std-disabled');
			$wrapper.find('.std-layout-conditions-title').addClass('std-hidden');
		} else {
			$wrapper.find('.std-layout-condition-add').removeClass('std-hidden');
			$wrapper.find('.std-layout-conditions-title').removeClass('std-hidden');
			$wrapper.find('.std-layout-submit').removeClass('std-disabled');
			$wrapper.find('.std-layout-condition-add').trigger('click');

			$('.std-layout-predefined-layouts[data-type="' + layoutType + '"]').removeClass('std-hidden');
		}

		if ('cart' === layoutType || 'checkout_form' === layoutType || 'checkout_content' === layoutType) {
			$wrapper.find('.std-layout-condition-add').addClass('std-hidden');
			$wrapper.find('.std-layout-conditions-title').addClass('std-hidden');
			$form.find('.std-layout-condition').addClass('std-hidden');
		}
	});

	// Change condition type.
	$(document).on('change', '.std-layout-condition-type', function() {
		var $this = $(this);
		var conditionType = $this.val();
		var $querySelect = $this.siblings('.std-layout-condition-query');

		if ($querySelect.data('select2')) {
			$querySelect.val('');
			$querySelect.select2('destroy');
		}

		if ('all' === conditionType || 'shop_page' === conditionType || 'product_search' === conditionType || 'product_cats' === conditionType || 'product_tags' === conditionType || 'checkout_form' === conditionType || 'checkout_content' === conditionType || 'cart' === conditionType || 'filtered_product_term_any' === conditionType) {
			$querySelect.addClass('std-hidden');
			$querySelect.removeAttr('data-query-type');
		} else {
			$querySelect.removeClass('std-hidden');
			$querySelect.attr('data-query-type', conditionType);
			conditionQuerySelect2($querySelect);
		}
	});

	// Condition query select2.
	function conditionQuerySelect2($field) {
		$field.select2({
			ajax             : {
				url     : STD_Engine.ajaxUrl,
				data    : function(params) {
					return {
						action    : 'std_layout_conditions_query',
						security  : STD_Engine.get_new_template_nonce,
						query_type: $field.attr('data-query-type'),
						search    : params.term
					};
				},
				method  : 'POST',
				dataType: 'json'
			},
			theme            : 'std',
			dropdownAutoWidth: false,
			width            : 'resolve'
		});
	}

	// Condition add.
	$wrapper.find('.std-layout-condition-add').on('click', function() {
		var layoutType = $form.find('.std-layout-type').val();
		var $templateClone = $template.clone();

		$templateClone.find('.std-layout-condition-type[data-type="' + layoutType + '"]').siblings('.std-layout-condition-type').remove();

		$wrapper.find('.std-layout-conditions .std-layout-conditions-title').after($templateClone.html());
	});

	// Conditions edit add.
	$(document).on('click', '.std-layout-conditions-edit-add', function() {
		var $this = $(this);
		var $wrapper = $this.parent();
		var layoutType = $wrapper.data('type');
		var $templateClone = $template.clone();

		$templateClone.find('.std-layout-condition-type[data-type="' + layoutType + '"]').siblings('.std-layout-condition-type').remove();

		$this.before($templateClone.html());
	});

	// Conditions edit.
	$(document).on('click', '.std-layout-conditions-edit', function() {
		var $this = $(this);
		var $wrapper = $this.parents('.std-popup-holder').find('.std-layout-conditions');

		$this.parents('.std-popup-holder').find('.std-layout-popup-notices').text('');

		if ($wrapper.hasClass('std-inited')) {
			return;
		}

		var conditions = $wrapper.data('conditions');
		var layoutType = $wrapper.data('type');

		if (conditions) {
			conditions.forEach(function(condition) {
				var $templateClone = $template.clone();

				$templateClone.find('.std-layout-condition-type[data-type="' + layoutType + '"]').siblings('.std-layout-condition-type').remove();

				$templateClone.find('.std-layout-condition').attr('data-condition', JSON.stringify(condition));

				$wrapper.find('.std-layout-conditions-edit-add').before($templateClone.html());
			});
		}

		$wrapper.find('.std-layout-condition').each(function() {
			var $this = $(this);
			var condition = $this.data('condition');

			if (condition) {
				$this.find('.std-layout-condition-comparison').val(condition.condition_comparison).trigger('change');
				$this.find('.std-layout-condition-type').val(condition.condition_type).trigger('change');

				if (condition.condition_query_text) {
					$this.find('.std-layout-condition-query').append('<option value="' + condition.condition_query + '">' + condition.condition_query_text + '</option>').val(condition.condition_query).trigger('change');
				}
			}
		});

		$wrapper.find('.std-layout-conditions-edit-save').removeClass('std-hidden');
		$wrapper.find('.std-layout-conditions-edit-add').removeClass('std-hidden');
		$wrapper.addClass('std-inited');
	});

	// Conditions save.
	$(document).on('click', '.std-layout-conditions-edit-save', function() {
		var $this = $(this);
		var $wrapper = $this.parents('.std_layout_conditions, #std-layout-conditions');
		var $popup = $wrapper.find('.std-popup');
		var $conditionsWrapper = $wrapper.find('.std-layout-conditions');

		var data = [];

		$wrapper.find('.std-popup-holder .std-layout-condition').each(function() {
			var $condition = $(this);
			data.push({
				condition_comparison: $condition.find('.std-layout-condition-comparison').val(),
				condition_type      : $condition.find('.std-layout-condition-type').val(),
				condition_query     : $condition.find('.std-layout-condition-query').val()
			});
		});

		$popup.addClass('std-loading');

		$.ajax({
			url     : STD_Engine.ajaxUrl,
			method  : 'POST',
			data    : {
				action  : 'std_layout_edit',
				data    : data,
				id      : $conditionsWrapper.data('id'),
				security: STD_Engine.get_new_template_nonce
			},
			dataType: 'json',
			success : function() {
				$popup.find('.std-layout-popup-notices').text('');
				$popup.find('.std-layout-popup-notices').append('<div class="std-notice std-success">ویرایش انجام شد :)</div>');
				$popup.removeClass('std-loading');
			},
			error   : function() {
				$popup.find('.std-layout-popup-notices').text('');
				$popup.find('.std-layout-popup-notices').append('<div class="std-notice std-warning">هنگام ویرایش مشکلی پیش آمده است !</div>');
				$popup.removeClass('std-loading');
			}
		});
	});

	// Condition remove.
	$(document).on('click', '.std-layout-condition-remove', function() {
		$(this).parent().remove();
	});

	// Predefined.
	$('.std-layout-predefined-layout').on('click', function() {
		var $this = $(this);
		$this.siblings().removeClass('std-active');
		$this.toggleClass('std-active');
	});

	// Popup.
	$('.page-title-action, .menu-icon-woodmart_layout li:not(.current) a').on('click', function(event) {
		event.preventDefault();
		$wrapper.find('.std-popup-holder').addClass('std-opened');
		$form.find('.std-layout-type').trigger('change');

		setTimeout(function() {
			var $input = $form.find('.std-layout-name');
			var strLength = $input.val().length;
			$input.trigger('focus');
			$input[0].setSelectionRange(strLength, strLength);
		}, 100);
	});
	$(document).on('click', '.std-popup-opener', function() {
		$(this).parent().addClass('std-opened');
	});
	$(document).on('click', '.std-popup-close, .std-popup-overlay', function() {
		$('.std-popup-holder').removeClass('std-opened');
	});
})(jQuery);