import tlite from 'tlite';
import '../../node_modules/magnific-popup/dist/jquery.magnific-popup.js';

/**
 * Creating the Media Uploader
 *
 * @param $imageContainer
 * @param $imageInput
 */
function giveasap_image_media( $imageContainer, $imageInput ) {
	'use strict';

	var file_frame;

	/**
	 * If an instance of file_frame already exists, then we can open it
	 * rather than creating a new instance.
	 */

	if ( undefined !== file_frame ) {

		file_frame.open();

		return;

	}

	/**
	 * If we're this far, then an instance does not exist, so we need to
	 * create our own.
	 *
	 * Here, use the wp.media library to define the settings of the Media
	 * Uploader. We're opting to use the 'post' frame which is a template
	 * defined in WordPress core and are initializing the file frame
	 * with the 'insert' state.
	 *
	 * We're also not allowing the user to select more than one image.
	 */
	file_frame = wp.media(
		{
			multiple: false,
		}
	);

	file_frame.on(
		'open',
		function() {
			var selection = file_frame.state().get( 'selection' );
			var ids       = $imageInput.val().split( ',' );
			ids.forEach(
				function(id) {
					var attachment = wp.media.attachment( id );
					attachment.fetch();
					selection.add( attachment ? [ attachment ] : [] );
				}
			);
		}
	);

	// When an image is selected in the media frame...
	file_frame.on(
		'select',
		function() {

			// Get media attachment details from the frame state
			var attachments = file_frame.state().get( 'selection' ).toJSON();

			var attachmentIDs = [];
			$imageContainer.empty();
			console.log( $imageContainer );
			var $galleryID = $imageContainer.attr( "id" );
			for ( var i = 0; i < attachments.length; i++ ) {
				if ( attachments[ i ].type == "image" ) {
					attachmentIDs.push( attachments[ i ].id );
					$imageContainer.append( sortable_gallery_image_create( attachments[ i ], $galleryID ) );
				}
			}

			$imageInput.val( attachmentIDs.join() );
			$imageInput.trigger( 'change' );
			// sortable_gallery_image_remove();

			jQuery( document ).trigger( 'giveasap:prize_image_updated', {
				containerId: $imageContainer.attr( 'id' ),
				html: $imageContainer.html(),
				ids: attachmentIDs.join()
			} );
		}
	);

	// Now display the actual file_frame
	file_frame.open();

}

function sortable_image_gallery_media( $imageContainer, $imageInput ) {
	'use strict';

	var file_frame;

	/**
	 * If an instance of file_frame already exists, then we can open it
	 * rather than creating a new instance.
	 */

	if ( undefined !== file_frame ) {

		file_frame.open();

		return;

	}

	/**
	 * If we're this far, then an instance does not exist, so we need to
	 * create our own.
	 *
	 * Here, use the wp.media library to define the settings of the Media
	 * Uploader. We're opting to use the 'post' frame which is a template
	 * defined in WordPress core and are initializing the file frame
	 * with the 'insert' state.
	 *
	 * We're also not allowing the user to select more than one image.
	 */
	file_frame = wp.media(
		{
			multiple: true,
		}
	);

	file_frame.on(
		'open',
		function() {
			var selection = file_frame.state().get( 'selection' );
			var ids       = $imageInput.val().split( ',' );
			ids.forEach(
				function(id) {
					var attachment = wp.media.attachment( id );
					attachment.fetch();
					selection.add( attachment ? [ attachment ] : [] );
				}
			);
		}
	);

	// When an image is selected in the media frame...
	file_frame.on(
		'select',
		function() {

			// Get media attachment details from the frame state
			var attachments = file_frame.state().get( 'selection' ).toJSON();

			var attachmentIDs = [];
			$imageContainer.empty();
			var $galleryID = $imageContainer.attr( "id" );
			for ( var i = 0; i < attachments.length; i++ ) {
				if ( attachments[ i ].type == "image" ) {
					attachmentIDs.push( attachments[ i ].id );
					$imageContainer.append( sortable_gallery_image_create( attachments[ i ], $galleryID ) );
				}
			}

			$imageInput.val( attachmentIDs.join() );
			// sortable_gallery_image_remove();
		}
	);

	// Now display the actual file_frame
	file_frame.open();

}

function sortable_gallery_image_create( $attachment, $galleryID ) {
	var image_url = '';
	if ( $attachment.sizes.thumbnail ) {
		image_url = $attachment.sizes.thumbnail.url;
	} else {
		image_url = $attachment.sizes.full.url;
	}
	var $output = '<li tabindex="0" role="checkbox" aria-label="' + $attachment.title + '" aria-checked="true" data-id="' + $attachment.id + '" class="attachment save-ready selected details">';
	$output    += '<div class="attachment-preview js--select-attachment type-image subtype-jpeg portrait">';
	$output    += '<div class="thumbnail">'

	$output += '<div class="centered">'
	$output += '<img src="' + image_url + '" draggable="false" alt="">'
	$output += '</div>'

	$output += '</div>'

	$output += '</div>'

	$output += '<button type="button" data-gallery="#' + $galleryID + '" class="button-link check remove-sortable-wordpress-gallery-image" tabindex="0"><span class="media-modal-icon"></span><span class="screen-reader-text">Deselect</span></button>'

	$output += '</li>';
	return $output;

}

function sortable_gallery_image_remove( ) {
	jQuery( ".remove-sortable-wordpress-gallery-image" ).on(
		'click',
		function(){
			var $id         = jQuery( this ).parent().attr( "data-id" );
			var $gallery    = jQuery( this ).attr( "data-gallery" );
			var $imageInput = jQuery( $gallery + "_input" );

			jQuery( this ).parent().remove();
			var ids      = $imageInput.val().split( ',' );
			var $idIndex = ids.indexOf( $id );
			if ( $idIndex >= 0 ) {
				ids.splice( $idIndex, 1 );
				$imageInput.val( ids.join() );
			}
		}
	);
}

function giveasap_prepare_format_from_php( format ) {
	format = format.replace( "d", "dd" );
	format = format.replace( "j", "d" );
	format = format.replace( "Y", "yy" );
	format = format.replace( "m", "mm" );

	return format;
}

function giveasap_initialize_code_editor() {
	var $ = jQuery;
	if ( $( '.sg-code-editor' ).length ) {
		$( '.sg-code-editor.initialized' ).each(function(i, el){
			if ( el.CodeMirror ) {
				el.CodeMirror.refresh();
			}
		});

		$( '.sg-code-editor:not(.initialized)' ).each(
			function(){
				var $textarea      = $( this );
				var editorSettings = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
				var mode           = $textarea.attr( 'data-mode' );
				if ( typeof mode === 'undefined' ) {
					mode = false;
				}
				editorSettings.codemirror = _.extend(
					{},
					editorSettings.codemirror,
					{
						indentUnit: 2,
						tabSize: 2
					}
				);

				if ( mode ) {
					editorSettings.codemirror.mode = mode;
				}

				var editor = wp.codeEditor.initialize( $textarea, editorSettings );
				$textarea.addClass('initialized');

				var cm = editor && editor.codemirror ? editor.codemirror : $textarea[0].CodeMirror;
				if ( cm ) {
					$textarea.data( 'sg-codemirror', cm );
					cm.on( 'change', function() {
						cm.save();
						$textarea.trigger( 'codemirror:change' );
					} );
				}
			}
		);
	}
}

(function($){

	$( document ).ready(
		function(){

			$(document.body).on( 'click', '#notify', function (e){
				if ( ! $('#sg_allow_awarding').length ) {
					return;
				}

				if ( ! $('#sg_allow_awarding').prop('checked') ) {
					return;
				}

				if ( ! $('.sg-select-prizes-manual').length ) {
					return;
				}

				if ( ! $('.sg-prizes-field-container ').length ) {
					return;
				}

				if ( ! $('.sg-prizes-field-container ').children().length ) {
					return;
				}

				var prizesDropdown     = $('.sg-select-prizes-manual');
				var havePricesSelected = true;
				prizesDropdown.each(function() {
					var value = $(this).find('select').val();
					if ( ! value.length ) {
						havePricesSelected = false;
					}
				});

				if ( ! havePricesSelected ) {
					e.preventDefault();
					alert('Some users don\'t have their prizes selected! Please make sure all have their prizes selected, save the giveaway and click again to notify.');
				}
			});

			tlite( el => el.classList.contains( 'sg-tooltip' ) );


			$( '#sgToggleAwardPrizes' ).on(
				'click',
				function(e){
					e.preventDefault();
					var $this = $( this ),
					$target   = $this.attr( 'data-target' ),
					$class    = $this.attr( 'data-class' );

					$( $target ).toggleClass( $class );
					if ( $( $target ).hasClass( $class ) ) {
						$( '#sg_awarding_prizes_manually' ).removeAttr( 'checked' );
					} else {
						$( '#sg_awarding_prizes_manually' ).attr( 'checked', 'checked' );
					}
				}
			);

			$( '.sg-toggle' ).on(
				'click',
				function (e) {
					e.preventDefault();
					var $this = $( this ),
					$target   = $this.attr( 'data-target' ),
					$class    = $this.attr( 'data-class' ),
					$text     = $this.attr( 'data-text' );

					$( $target ).toggleClass( $class );
					if ( $text ) {
						var old_text = $this.text();
						$this.attr( 'data-text', old_text );
						$this.html( $text );
					}
				}
			);

			if ( $( '#sg_giveaway_add_subscriber' ).length ) {
				$( '#sg_giveaway_add_subscriber' ).on(
					'change',
					function() {
						$.ajax(
							{
								url: gasap.ajax_url,
								dataType: 'json',
								type: 'GET',
								data: { action: 'sg_get_giveaway_form_fields', giveaway: $( this ).val(), nonce: gasap.nonce },
								success: function(resp) {
									if ( resp.success ) {
										$( '#sgGiveawayFields' ).html( resp.data );
									}
								}
							}
						);
					}
				);
			}

			var imageButton = $( ".add-sortable-wordpress-gallery" );

			$( document ).on(
				'click',
				'.remove-sortable-wordpress-gallery-image',
				function( e ){
					e.preventDefault();
					var $this = $( this ),
					$id       = $this.parent().attr( 'data-id' ),
					$gallery  = $this.attr( 'data-gallery' ),
					$input    = $( $gallery + '_input' );

					var ids  = $input.val().split( ',' ),
					$idIndex = ids.indexOf( $id );
					if ( $idIndex >= 0 ) {
						ids.splice( $idIndex, 1 );
						$input.val( ids.join() );
					}

					$this.parent().remove();

					$( document ).trigger( 'giveasap:prize_image_updated', {
						containerId: $gallery.replace( /^#/, '' ),
						html: $( $gallery ).html(),
						ids: $input.val()
					} );
				}
			);

			// sortable_gallery_image_remove();
			imageButton.each(
				function(){
					var galleryID      = $( this ).attr( "data-gallery" );
					var imageContainer = $( galleryID );
					var imageInput     = $( galleryID + "_input" );
					imageContainer.sortable();
					imageContainer.on(
						"sortupdate",
						function( event, ui ) {
							var $ids    = [];
							var $images = imageContainer.children( "li" );
							$images.each(
								function(){
									$ids.push( $( this ).attr( "data-id" ) );
								}
							);
							imageInput.val( $ids.join() );
						}
					);

					$( this ).on(
						'click',
						function(){
							sortable_image_gallery_media( imageContainer, imageInput );
						}
					);

				}
			);

			$( document ).on(
				'click',
				'.add-single-wordpress-image',
				function(e){
					e.preventDefault();
					var galleryID      = $( this ).attr( "data-gallery" );
					var imageContainer = $( galleryID );
					var imageInput     = $( galleryID + "_input" );
					giveasap_image_media( imageContainer, imageInput );
				}
			);

			$( document ).on(
				'change',
				'#giveasap_end_date, #giveasap_end_time',
				function(){
					var end_time       = $( '#giveasap_end_time' ).val(),
					end_date           = $( '#giveasap_end_date' ).val().split( '-' ).reverse().join( '-' ),
					winner_time        = $( '#giveasap_winner_time' ).val(),
					winner_date        = $( '#giveasap_winner_date' ).val().split( '-' ).reverse().join( '-' ),
					end_date_object    = Date.parse( end_date + 'T' + end_time ),
					winner_date_object = Date.parse( winner_date + 'T' + winner_time );

					if ( end_date_object > winner_date_object ) {
						$( '#giveasap_winner_date' ).val( $( '#giveasap_end_date' ).val() );
						$( '#giveasap_winner_time' ).val( $( '#giveasap_end_time' ).val() );
					}
				}
			);

			$( document ).on(
				'change',
				'#giveasap_winner_time, #giveasap_winner_date',
				function(){
					var end_time       = $( '#giveasap_end_time' ).val(),
					end_date           = $( '#giveasap_end_date' ).val().split( '-' ).reverse().join( '-' ),
					winner_time        = $( '#giveasap_winner_time' ).val(),
					winner_date        = $( '#giveasap_winner_date' ).val().split( '-' ).reverse().join( '-' ),
					end_date_object    = Date.parse( end_date + 'T' + end_time ),
					winner_date_object = Date.parse( winner_date + 'T' + winner_time );

					if ( end_date_object > winner_date_object ) {
						alert( gasap.text.winner_before_end );
					}
				}
			);

			var $expand_users = $( "#giveasap_expand_users" );
			$expand_users.on(
				'click',
				function(){
					var $users_container = $( "#giveasap_users_container" );
					$users_container.toggleClass( "hidden" );
				}
			);

			var $date_format = $( "#date_format" );
			$date_format.on(
				'change',
				function(){

					var $format = giveasap_prepare_format_from_php( $( this ).val() );
					$( ".datepicker" ).datepicker(
						'option',
						{
							altFormat: $format
						}
					);
				}
			);

			$( document ).on(
				'click',
				'.button-integration-deactivate',
				function( e ){
					e.preventDefault();

					var integration = $( this ).attr( 'data-integration' ),
					$this           = $( this );
					if ( integration ) {
						$.ajax(
							{
								url: gasap.ajax_url,
								dataType: 'json',
								type: 'POST',
								data: { action: 'giveasap_deactivate_integration', integration: integration, nonce: gasap.nonce },
								success: function(resp) {
									if ( resp.success ) {
										$this.removeClass( 'button-integration-deactivate' )
										.removeClass( 'button-default' )
										.addClass( 'button-integration-activate' )
										.addClass( 'button-primary' )
										.html( gasap.text.activate );
									}
								}
							}
						);
					}

				}
			);

			$( document ).on(
				'click',
				'.button-integration-activate',
				function( e ){
					e.preventDefault();

					var integration = $( this ).attr( 'data-integration' ),
					$this           = $( this );

					if ( integration ) {
						$.ajax(
							{
								url: gasap.ajax_url,
								dataType: 'json',
								type: 'POST',
								data: { action: 'giveasap_activate_integration', integration: integration, nonce: gasap.nonce },
								success: function(resp) {
									if ( resp.success ) {
										$this.addClass( 'button-integration-deactivate' )
										.addClass( 'button-default' )
										.removeClass( 'button-integration-activate' )
										.removeClass( 'button-primary' )
										.html( gasap.text.deactivate );
									}
								}
							}
						);
					}

				}
			);

			/**
			 * Searching Email on User List.
			 */
			$( document ).on(
				'click',
				'.ga-search-email',
				function( e ){
					e.preventDefault();
					var inputs = $( this ).parent().find( 'input' ),
					url        = window.location.href,
					parts      = url.split( '?' ),
					query      = parts[1],
					qparams    = query.split( '&' ),
					params     = {};

					for ( var i = 0; i < qparams.length; i++ ) {
						var strings          = qparams[i].split( '=' );
						params[ strings[0] ] = strings[1];
					}

					inputs.each(
						function(){
							var name = $( this ).attr( 'name' ),
							val      = $( this ).val();
							if ( val ) {
								params[ name ] = val;
							} else {
								delete params[ name ];
							}
						}
					);

					var params_array = [];
					for ( var key in params ) {
						params_array.push( key + '=' + params[key] );
					}
					var location = parts[0] + '?' + params_array.join( '&' );

					window.location.href = location;
				}
			);

			$( document ).on(
				'click',
				'.sg-metaboxes li.sg-metabox a',
				function(e){
					e.preventDefault();
					$( '.sg-metabox-fields' ).addClass( 'hidden' );
					$( '.sg-metaboxes li.active' ).removeClass( 'active' );
					var target = $( this ).attr( 'href' );
					$( target ).removeClass( 'hidden' );
					$( this ).parent().addClass( 'active' );
					$( target ).find( '.wp-editor-wrap' ).each(
						function(){
							var frame = $( this ).find( 'iframe' ),
							height    = frame.height();
							if ( height < 200 ) {
								frame.height( 200 );
							}
						}
					);
					if ( $( target ).find('.sg-code-editor') ) {
						giveasap_initialize_code_editor();
					}
					if ($(target).find(".sg-select-search")) {
						$(document.body).trigger("sg_select_search_shown");
				  	}
				}
			);

			$( document ).on(
				'change',
				'.sg-admin-form.sg-action-form :input',
				function(){
					var form = $( this ).parents( '.sg-admin-form' );
					if ( ! $( this )[0].checkValidity() ) {
						var txt   = $( this )[0].validationMessage;
						var error = form.find( '.error' );
						$( this ).focus();
						if ( error.length ) {
							error.find( 'p' ).html( txt );
						} else {
							form.prepend( '<div class="notice error"><p>' + txt + '</p></div>' );
						}
						setTimeout(
							function(){
								form.find( '.error' ).fadeOut().remove();
							},
							5000
						);
					}
				}
			);

			$( '.sg-image-popup-link' ).magnificPopup( {type:'image'} );

			/**
			 * Sharing Methods.
			 */
			$( '#addShareMethod' ).on(
				'click',
				function(e){
					e.preventDefault();
					var template = wp.template( 'sharing-method' ),
					index        = $( '.giveaway-sharing-methods' ).children().length,
					data         = { index: index, title: 'New Method' },
					html         = template( data );
					$( '.giveaway-sharing-methods' ).append( html );
					$( '.giveaway-sharing-methods' ).children().eq( index ).find( '.method-select' ).trigger( 'change' );
				}
			);

			function giveaway_reset_methods_index() {
				var index = 0;
				$( '.giveaway-sharing-methods' ).children().each(
					function(){
						var _index = parseInt( $( this ).attr( 'data-index' ) );
						if ( _index !== index ) {
							var html  = $( this ).html(),
							reg       = new RegExp( 'giveasap_methods\\[' + _index + '\\]', 'g' );
							var _html = html.replace( reg, 'giveasap_methods[' + index + ']' );
							$( this ).html( _html );
							$( this ).attr( 'data-index', index );
						}
						index++;
					}
				);
			}

			$( '.giveaway-sharing-methods' ).sortable(
				{
					update: function( event, ui ) {
						giveaway_reset_methods_index();
					}
				}
			);

			$( document ).on(
				'click',
				'.giveaway-sharing-method .method-header',
				function(){
					$( this ).parent().toggleClass( 'active' );
				}
			);

			$( document ).on(
				'click',
				'.giveaway-sharing-method .button-delete',
				function(){
					$( this ).parents( '.giveaway-sharing-method' ).remove();
					giveaway_reset_methods_index();
				}
			);

			$( document ).on(
				'change',
				'.giveaway-sharing-method .method-select',
				function(){
					var value = $( this ).val();

					if ( 'custom' === value ) {
						var template = wp.template( 'sharing-method-custom' ),
						method       = $( this ).parents( '.giveaway-sharing-method' ),
						index        = method.attr( 'data-index' ),
						data         = { index: index, url: '', title: method.attr( 'data-title' ), attributes: { url: '', text: '', image: '' } },
						html         = template( data );
						method.find( '.giveasap-method-html' ).html( html );
						method.find( '.color-picker' ).wpColorPicker();
					} else {
						var method = $( this ).parents( '.giveaway-sharing-method' );
						method.find( '.giveasap-method-html' ).html( '' );
					}
				}
			);

			function strip_tags(input, allowed) {
				allowed = (((allowed || '') + '')
					.toLowerCase()
					.match(/<[a-z][a-z0-9]*>/g) || [])
					.join(''); // making sure the allowed arg is a string containing only tags in lowercase (<a><b><c>)
				var tags = /<\/?([a-z][a-z0-9]*)\b[^>]*>/gi,
					commentsAndPhpTags = /<!--[\s\S]*?-->|<\?(?:php)?[\s\S]*?\?>/gi;
				commentsAndPhpTags = /<(script|style)[^>]*?>.*?<\/\1>/g;
				return input.replace(commentsAndPhpTags, '')
					.replace(tags, function($0, $1) {
						return allowed.indexOf('<' + $1.toLowerCase() + '>') > -1 ? $0 : '';
					});
			}

			$( document ).on(
				'keyup',
				'.giveaway-sharing-method .method-title',
				function(){
					var val = strip_tags( $( this ).val() );
					console.log(val);
					$( this ).parents( '.giveaway-sharing-method' ).find( '.method-header strong' ).html( val );
				}
			);

			if ( $( '.giveaway-sharing-methods' ).length ) {
				$( '.giveaway-sharing-methods .color-picker' ).wpColorPicker();
			}

			/** Form Fields ********/

			function giveaway_reset_form_fields_index() {
				var index = 0;
				$( '.sg-form-fields-container' ).children().each(
					function(){
						var _index = parseInt( $( this ).attr( 'data-index' ) );
						if ( _index !== index ) {
							var html  = $( this ).html(),
							reg       = new RegExp( 'form_fields\\[' + _index + '\\]', 'g' );
							var _html = html.replace( reg, 'form_fields[' + index + ']' );
							$( this ).html( _html );
							$( this ).attr( 'data-index', index );
						}
						index++;
					}
				);
			}

      function giveaway_set_html_fields_to_attributes( $container ) {
        $container.find("input, textarea, select").each(function () {
          $(this).attr("value", $(this).val());
        });
        $container
          .find('input[type="checkbox"], input[type="radio"]')
          .each(function () {
            if ($(this).is(":checked")) {
              $(this).attr("checked", "checked");
            } else {
              $(this).removeAttr("checked");
            }
          });
      }

			function giveaway_reset_prizes_fields_index() {
				var index = 0;
				$( '.sg-prizes-field-container' ).children().each(
					function(){
						var _index = parseInt( $( this ).attr( 'data-index' ) );
						if ( _index !== index ) {
              giveaway_set_html_fields_to_attributes( $(this) );
							var html  = $( this ).html(),
							reg       = new RegExp( 'prizes\\[' + _index + '\\]', 'g' );
							var _html = html.replace(reg, "prizes[" + index + "]");
							$( this ).html( _html );
							$( this ).attr( 'data-index', index );
						}
						index++;
					}
				);
			}

      function giveaway_reset_webhooks_fields_index() {
        var index = 0;
        $( '.sg-webhooks-fields-container' ).children().each(
          function(){
            var _index = parseInt( $( this ).attr( 'data-index' ) );
            if ( _index !== index ) {
              var html  = $( this ).html(),
                reg       = new RegExp( 'webhooks_on_register\\[' + _index + '\\]', 'g' );
              var _html = html.replace( reg, 'webhooks_on_register[' + index + ']' );
              $( this ).html( _html );
              $( this ).attr( 'data-index', index );
            }
            index++;
          }
        );
      }

			$( document.body ).on(
				'change',
				'.sg-field-type',
				function(e){
					var type = $( this ).val(),
					$this    = $( this ),
					parent   = $this.parent();
					if ( 'radio' === type || 'select' === type ) {
						if ( parent.find( '.sg-form-field-options' ).length === 0 ) {
							var index = $this.parents( '.sg-form-field' ).attr( 'data-index' ),
							   tmpl   = wp.template( 'sg-form-field-options' ),
							   html   = tmpl( {index: index} );
							parent.append( html );
						}
					} else {
						var options = parent.find( '.sg-form-field-options' );
						if ( options.length ) {
							options.remove();
						}
					}
				}
			);

			$( document.body ).on(
				'click',
				'.sg-remove-form-field-option',
				function(e){
					$( this ).parent().remove();
				}
			);

			$( document.body ).on(
				'click',
				'.sg-add-form-field-option',
				function(e){
					e.preventDefault();
					var index = $( this ).parents( '.sg-form-field' ).attr( 'data-index' ),
					tmpl      = wp.template( 'sg-form-field-option' ),
					html      = tmpl( { index: index } );
					$( this ).parent().find( '.sg-form-field-options-container' ).append( html );
				}
			);

			$( '.sg-form-fields-container' ).sortable(
				{
					placeholder: "ui-state-highlight",
					handle: '.sg-form-row-handle',
					update: function( event, ui ) {
						giveaway_reset_form_fields_index();
					}
				}
			);

			$( '#sgAddFormField' ).on(
				'click',
				function() {
					var tmpl = wp.template( 'sg-form-field' ),
					count    = $( '.sg-form-fields-container' ).children().length,
					html     = tmpl( { index: count } );
					$( '.sg-form-fields-container' ).append( html );
				}
			);

			$( document.body ).on(
				'click',
				'.sg-delete-form-field',
				function(){
					$( this ).parents( '.sg-form-field' ).remove();
					giveaway_reset_form_fields_index();
				}
			);

			$( document.body ).on(
				'click',
				'.sg-form-field-header .sg-field-name',
				function(){
					$( this ).parents( '.sg-form-field' ).toggleClass( 'open' );
				}
			);

			$( document.body ).on(
				'keyup',
				'.sg-form-field-body .sg-field-name input',
				function(){
					var value = $( this ).val();
					value = strip_tags(value);
					$( this ).parents( '.sg-form-field' ).find( '.sg-form-field-header .sg-field-name' ).html( value );
				}
			);

			$( '#sgAddPrizesField' ).on(
				'click',
				function() {
					var tmpl = wp.template( 'sg-prizes-field' ),
					count    = $( '.sg-prizes-field-container' ).children().length,
					html     = tmpl( { index: count } );
					$( '.sg-prizes-field-container' ).append( html );

					var prizesBox = $( '.sg-prizes-field-container .sg-form-field' ).last();
					prizesBox.toggleClass( 'open' );
					prizesBox.find( '.sg-field-name input' ).focus();
					sg_hide_show_metabox_fields_per_type();
					$( document.body ).triggerHandler( 'sg_prizes_field_added' );
				}
			);

			$( document.body ).on(
				'click',
				'.sg-delete-prizes-field',
				function(){
					$( this ).parents( '.sg-form-field' ).remove();
					giveaway_reset_prizes_fields_index();
				}
			);

			$( '.sg-prizes-field-container' ).sortable(
				{
					placeholder: "ui-state-highlight",
					handle: '.sg-form-row-handle',
					update: function( event, ui ) {
					  giveaway_reset_prizes_fields_index();
					}
				}
			);

      $( '#sgAddWebhookField' ).on(
        'click',
        function() {

          var tmpl = wp.template( 'sg-webhooks-field' ),
            count    = $( '.sg-webhooks-fields-container' ).children().length,
            html     = tmpl( { index: count } );
          $( '.sg-webhooks-fields-container' ).append( html );

          var prizesBox = $( '.sg-webhooks-fields-container .sg-form-field' ).last();
          prizesBox.toggleClass( 'open' );
          prizesBox.find( '.sg-field-name input' ).focus();
        }
      );

      $( document.body ).on(
        'click',
        '.sg-delete-webhook-field',
        function(){
          $( this ).parents( '.sg-form-field' ).remove();
          giveaway_reset_webhooks_fields_index();
        }
      );

      $( document.body ).on(
        'click',
        '.sg-add-webhook-field-headers-row',
        function() {
          var tmpl = wp.template( 'sg-webhook-headers-field' ),
            index = $( this ).parents( '.sg-form-field' ).attr( 'data-index' ),
            html  = tmpl( { index: index } );
          $( this ).parents('.sg-field-headers').find( '.sg-field-headers-rows' ).append( html );
        }
      );

      $( document.body ).on(
        'click',
        '.sg-delete-webhook-header-field',
        function(){
          $( this ).parents( '.sg-field-headers-row' ).remove();

        }
      );

			/** Giveaway ***********/
			function sg_hide_show_metabox_fields_per_type() {
				var giveaway_type = $( '#giveasap_type' ).val();

				$(".sg-metaboxes .hide_if_any, .giveasap-builder-content .hide_if_any").hide();
				$(".sg-metaboxes .show_if_any, .giveasap-builder-content .show_if_any").show();
				$( '.hide_if_' + giveaway_type ).hide();
				$( '.show_if_' + giveaway_type ).show();
				// $('.sg-metaboxes tr:not(.hide_if_' + giveaway_type + ')').show();

				$( document.body ).triggerHandler( 'sg_giveaway_type_changed', [ giveaway_type ] );
			} 

			if ( $( '#sg-metaboxes' ).length ) {

				sg_hide_show_metabox_fields_per_type();

				$( '#giveasap_type' ).on( 'change', sg_hide_show_metabox_fields_per_type );
			}

			/** Globals ***********/

			$( document ).on(
				'click',
				'.sg-button-action',
				function( e ){
					e.preventDefault();
					var $this = $( this ),
					ajax      = $this.attr( 'data-ajax' ) || '',
					reload    = $this.attr( 'data-reload' ) || '0',
					callback  = $this.attr( 'data-callback' ) || '',
					nonce     = $this.attr( 'data-nonce' ) || '',
					text2     = $this.attr( 'data-text' ),
					text      = $this.text(),
					href      = $this.attr( 'href' );

					if ( text2 ) {
						$this.text( text2 );
					}

					if ( ajax ) {

						var data = { action: ajax };

						if ( nonce ) {
							data.nonce = gasap.nonce;
						}
						if ( this.attributes.length ) {
							for ( var i = 0; i < this.attributes.length; i++  ) {
								var attr                                  = this.attributes[ i ];
								data[ attr.nodeName.replace( '-', '_' ) ] = attr.nodeValue;
							}
						}
						$.ajax(
							{
								url: gasap.ajax_url,
								dataType: 'json',
								data: data,
								success: function( resp ) {
									if ( callback ) {
										var fn = window[ callback ];
										if (typeof fn === 'function') {
											fn( $this, resp );
										}
									}

									if ( text2 && '1' !== reload ) {
										$this.text( text );
									}

									if ( '1' === reload ) {
										if ( href ) {
											window.location.href = href;
										} else {
											location.reload( false );
										}
									}
								}
							}
						);
					} else {
						if ( callback ) {
							var fn = window[ callback ];
							if (typeof fn === 'function') {
								fn( $this );
							}
						}
						if ( text2 && '1' !== reload ) {
							$this.text( text );
						}

						if ( '1' === reload ) {
							if ( href ) {
								window.location.href = href;
							} else {
								location.reload( false );
							}
						}
					}
				}
			);

			$( '.sg-action-category-title' ).on(
				'click',
				function(e){
					$( this ).parent().toggleClass( 'active' );
				}
			);

			$( '.sg-action' ).on(
				'click',
				function(e){
					var $actionContainer = $( '#sgEntriesActions' ),
					count                = $actionContainer.children().length,
					slug                 = $( this ).attr( 'data-slug' ),
					template             = wp.template( slug );

					if ( $( '#tmpl-' + slug ).length ) {
						e.preventDefault();
            window.giveasap_max_instance_id = window.giveasap_max_instance_id + 1;
            var actionTemplate = template({ index: count, instance_id: window.giveasap_max_instance_id });
						$actionContainer.append(actionTemplate);

						var action = $actionContainer.children().last();
						action.find( '.sg-admin-action-title' ).trigger( 'click' );
            $( [document.documentElement, document.body] ).animate(
							{
								scrollTop: $actionContainer.children().last().offset().top - 24 // admin bar.
							},
							500
						);
						$(document.body).triggerHandler("sg_action_added", [
							{
								index: count,
								slug: slug,
								html: actionTemplate,
								instance_id: window.giveasap_max_instance_id,
							},
						]);
            $(document.body).trigger("sg-enhanced-select-search-init");
            $(document.body).trigger("sg-color-picker-init");
					}
				}
			);

			$( '.sg-extra-actions' ).sortable(
				{
					update: function( event, ui ) {
						giveaway_reset_extra_action_index();
						giveasap_update_specific_mandatory_actions();

					}
				}
			);

			$( document ).on(
				'click',
				'.sg-admin-action-remove',
				function(e){
					e.preventDefault();
					$( this ).parents( '.sg-admin-action' ).remove();
					giveaway_reset_extra_action_index();
					giveasap_update_specific_mandatory_actions();
				}
			);

			function giveaway_reset_extra_action_index() {
				// Re-index each container separately — the metabox and the visual
				// builder each hold their own copy of the actions list.
				$( '.sg-extra-actions' ).each(
					function(){
						var index = 0;
						$( this ).children().each(
							function(){
								var _index = parseInt( $( this ).attr( 'data-index' ) );
								if ( _index !== index ) {
									var html  = $( this ).html(),
									reg       = new RegExp( 'entries_actions\\[' + _index + '\\]', 'g' );
									var _html = html.replace( reg, 'entries_actions[' + index + ']' );
									$( this ).html( _html );
									$( this ).attr( 'data-index', index );
								}
								index++;
							}
						);
					}
				);
			}

			$( document ).on(
				'click',
				'.sg-admin-action-title',
				function( e ){
					e.preventDefault();
					$( this ).parent().toggleClass( 'active' );
				}
			);

			$( document ).on(
				'click',
				'.sg-multioption-button',
				function(e){
					e.preventDefault();
					var id   = $( this ).attr( 'data-id' ),
					name     = $( this ).attr( 'data-name' ),
					tmpl     = $( this ).attr( 'data-template' ),
					count    = $( '#' + id ).children().length,
					template = wp.template( tmpl ),
					html     = template( { index: count, id: id, name: name } );

					$( '#' + id ).append( html );
				}
			);

			$( document ).on(
				'click',
				'.sg-multioption-delete',
				function(e){
					e.preventDefault();
					$( this ).parent().remove();
				}
			);

			$(document).on(
        "keyup",
        ".sg-form-field-title input",
        function () {
          var parent = $(this).parents(".sg-admin-form");
          var instance = parent.find(".sg-action-form-instance").val();
          var title = $(this).val();
          title = strip_tags(title);
          giveasap_update_specific_mandatory_action(instance, title);
          giveasap_update_specific_mandatory_actions();
        }
      );

			$( document ).on(
				'change',
				'.mandatory-specific-action-checkbox',
				function(){
					var parent   = $( this ).parents( '.sg-admin-form' );
					var field    = $( this ).parents( '.sg-form-field' );
					var selected = field.attr( 'data-value' );
					var instance = parent.find( '.sg-action-form-instance' ).val();
					var value    = $( this ).val();

					selected = selected.split(',');
					if ( $(this).prop('checked') && selected.indexOf( value ) < 0) {
						selected.push( value );
					}

					if ( ! $(this).prop('checked') && selected.indexOf( value ) >= 0) {
						var  index = selected.indexOf(value);
						if (index > -1) {
							selected.splice(index, 1);
						}
					}

					field.attr('data-value', selected.join(','));
				}
			);

			function giveasap_update_specific_mandatory_action( instance, title ) {
				var ids = window.giveasap_actions.map(
					function(action){
						return parseInt( action.instance );
					}
				);

				if ( ids.indexOf( parseInt( instance ) ) >= 0 ) {
					window.giveasap_actions = window.giveasap_actions.map(
						function (action) {
							if (parseInt( action.instance ) !== parseInt( instance )) {
								return action;
							}

							action.title = title;
							return action;
						}
					);
				} else {
					window.giveasap_actions.push(
						{
							instance: instance,
							title: title
						}
					);
				}
			}

			function giveasap_update_specific_mandatory_actions() {
				$( document ).find( '.sg-select-specific-mandatory-actions' ).each(
					function(){
						var $this    = $( this );
						var parent   = $this.parents( '.sg-admin-form' );
						var field    = $this.parents( '.sg-form-field' );
						var selected = field.attr( 'data-value' );
						var name     = field.attr( 'data-name' );
						var instance = parent.find( '.sg-action-form-instance' ).val();
						var data     = [];

						if ( selected ) {
							selected = selected.split(',');
						}

						if ( window.giveasap_actions && window.giveasap_actions.length ) {
							for (var g = 0; g < window.giveasap_actions.length; g++ ) {
								var action_id = window.giveasap_actions[ g ].instance;

								if ( parseInt( instance ) === parseInt( action_id ) ) {
									continue;
								}

								var optionSelected = selected && selected.indexOf( action_id ) >= 0;

								data.push(
									{
										id: action_id,
										text: window.giveasap_actions[ g ].title,
										selected: optionSelected
									}
								)
							}
						}

						if ( ! data.length ) {
							field.addClass('hidden');
							return;
						}

						var html = '';
						for( var d = 0; d < data.length; d++ ) {
							var action = data[d];
							var checkedHTML = '';
							if ( action.selected ) {
								checkedHTML = 'checked="checked"';
							}
							html += '<label for="' + instance + '_specific_action_' + d + '">';
							html += '<input class="mandatory-specific-action-checkbox" ' + checkedHTML + ' id="' + instance + '_specific_action_' + d + '" type="checkbox" name="' + name + '" value="' + action.id + '"/>'
							html += action.text;
							html += '</label>';
						}

						$this.html(html);
						field.removeClass('hidden');
					}
				);
			}

			giveasap_update_specific_mandatory_actions();

			$( document ).find( '.sg-select2:not(.enhanced)' ).each(
				function(){
					if ( $( this ).parents( '.sg-report-options' ).length ) {
						return;
					}

					var $this = $( this );
					$( this ).select2(
						{
							placeholder: $this.attr( 'placeholder' ) || '',
							minimumInputLength: $this.attr( 'data-mininput' ) || 3,
							ajax: {
								url: gasap.ajax_url,
								dataType: 'json',
								data: function (params) {
									var query = {
										search: params.term,
										type: 'public',
										action: $this.attr( 'data-action' ) || 'sg_get_giveaways'
									}

									// Query parameters will be ?search=[term]&type=public
									return query;
								},
								processResults: function (data) {
									if ( data.success ) {
										var items = [];
										for ( var index in data.data ) {
											items.push(
												{
													id: data.data[index].ID,
													text: data.data[index].post_title
												}
											);
										}
										return {
											results: items
										};
									}
									// Transforms the top-level key of the response object from 'items' to 'results'
									return {
										results: data.items
									};
								}
							}
						}
					).addClass( 'enhanced' );
				}
			);

			

			function createSelect2SearchAjax( el ) {
				if (
				  el.hasClass("enhanced") &&
				  el.hasClass("select2-hidden-accessible ")
				) {
				  el.select2("destroy");
				}

				var select2_args = {
				  allowClear: el.data("allow_clear") ? true : false,
				  placeholder: el.data("placeholder"),
				  minimumInputLength: el.data("minimum_input_length")
					? el.data("minimum_input_length")
					: "3",
				  escapeMarkup: function (m) {
					return m;
				  },
				  ajax: {
					url: gasap.ajax_url,
					dataType: "json",
					delay: 250,
					data: function (params) {
					  return {
						term: params.term,
						action: el.data("action") || "sg_select_search",
						security: gasap.nonce,
						exclude: el.data("exclude"),
						exclude_type: el.data("exclude_type"),
						include: el.data("include"),
						limit: el.data("limit"),
						display_stock: el.data("display_stock"),
					  };
					},
					processResults: function (data) {
					  var terms = [];
					  if (data) {
						$.each(data, function (id, text) {
						  terms.push({ id: id, text: text });
						});
					  }
					  return {
						results: terms,
					  };
					},
					cache: true,
				  },
				};

				// If inside the visual builder overlay, attach dropdown to the overlay
				// so it renders above the overlay's z-index stacking context
				var $overlay = el.closest('.giveasap-builder-overlay');
				if ( $overlay.length ) {
					select2_args.dropdownParent = $overlay;
				}

       			el.select2(select2_args).addClass("enhanced");

				if (el.prop("multiple")) {
				  el.on("change", function () {
					var $children = $(this).children();
					$children.sort(function (a, b) {
					  var atext = a.text.toLowerCase();
					  var btext = b.text.toLowerCase();

					  if (atext > btext) {
						return 1;
					  }
					  if (atext < btext) {
						return -1;
					  }
					  return 0;
					});
					$(this).html($children);
				  });
				}
			}

			$(document.body).on("sg_select_search_shown", function() {
				$(".sg-metabox-fields:not(.hidden)").find(".sg-select-search").each(function(){
					createSelect2SearchAjax($(this));
				});
			});

			/** Select2 Ajax **/
			$( document.body )
			.on(
				'sg-enhanced-select-search-init',
				function() {

					// Ajax product search box
					$( ':input.sg-select-search' ).filter( ':not(.enhanced)' ).each(
						function () {
							createSelect2SearchAjax( $(this) );
						}
					);
				}
			).trigger( 'sg-enhanced-select-search-init' );

			$( document.body )
			.on(
				'sg-color-picker-init',
				function() {
					// Ajax product search box
					$( ':input.sg-color-picker' ).filter( ':not(.enhanced)' ).each(
						function () {
							$( this ).wpColorPicker();
						}
					);
				}
			).trigger( 'sg-color-picker-init' );

			function sgImportSiteUsers( giveaway_id ) {

				$('#sgImportSiteUsersSpinner').addClass('is-active');

				$.ajax({
					url: gasap.ajax_url,
					data: {
						action: 'sg_import_site_users',
						giveaway_id: giveaway_id,
						nonce: gasap.nonce
					},
					success: function( resp ) {

						if ( ! resp.success ) {
							$('#sgImportSiteUsersSpinner').removeClass('is-active');
							alert( 'Something went wrong. Try again.' );
							return;
						}

						$('#sgImportSiteUsers span').html( resp.data.users );

						if ( resp.data.done ) {
							$('#sgImportSiteUsersSpinner').removeClass('is-active');
							alert( 'Imported All Users' );
							window.location.reload();
							return;
						}

						sgImportSiteUsers( giveaway_id );
					},
					error: function (resp) {
						$('#sgImportSiteUsersSpinner').removeClass('is-active');
						alert( 'Something went wrong. Try again.' );
					}
				})
			}

			$( document.body ).on(
				'click',
				'#sgImportSiteUsers',
				function() {
					var giveaway_id = $(this).attr('data-giveaway');
					sgImportSiteUsers( giveaway_id );
				}
			)
		}
	);


})( jQuery )
