(function ( $ ) {
	'use strict';

	if ( typeof qodefFramework !== 'object' ) {
		window.qodefFramework = {};
	}

	$( window ).load(
		function () {
			qodeBadgesForWooCommerceDisplayPreview.init();
			qodeBadgesForWooCommerceDisplayPreviewList.init();
		}
	);

	var qodeBadgesForWooCommerceDisplayPreview = {
		init: function () {
			this.holder      = $( '.qbfw-badge-preview-holder' );
			this.styleObject = {};

			if ( this.holder.length ) {
				this.holder.each(
					function () {
						qodeBadgesForWooCommerceDisplayPreview.initPreview( $( this ) );
						qodeBadgesForWooCommerceDisplayPreview.initContentChange( $( this ) );
						setTimeout(
							function () {
								qodeBadgesForWooCommerceDisplayPreview.initStickyPreview();
							},
							300
						);

						qodeBadgesForWooCommerceDisplayPreview.onTypeChange( $( this ) );
					}
				);
			}
		},
		initPreview: function ( $preview, restyle = false ) {
			var $metaHolder    = $( '#qode-framework-woo-meta-box-qbfw_badge' ),
				$fields        = $metaHolder.find(
					'.qodef-field.qodef-input,' +
					'input[type=radio].qodef-field,' +
					'.qodef-field.qodef-select2,' +
					'.wp-picker-container'
				).filter( ':not([data-exclude=yes])' ),
				$positionField = $metaHolder.find( '.qodef-field[name=qode_badges_for_woocommerce_badge_position]' );

			if ( $fields.length ) {
				$fields.each(
					function () {
						var $this = $( this );

						qodeBadgesForWooCommerceDisplayPreview.addStyleProperty( $this );

						if ( ! restyle ) {
							$this.on(
								'click change keyup',
								function () {
									qodeBadgesForWooCommerceDisplayPreview.addStyleProperty( $( this ) );

									qodeBadgesForWooCommerceDisplayPreview.initStyle( $preview, $positionField );
								}
							);
						}
					}
				);
			}

			qodeBadgesForWooCommerceDisplayPreview.initStyle( $preview, $positionField );
		},
		addStyleProperty: function ( $field ) {
			var $input, defaultValue = 0, suffixVal = '';

			if ( $field.hasClass( 'qodef-field' ) ) {
				$input = $field;
			} else {
				$input       = $field.find( '.qodef-field.qodef-color-field' );
				defaultValue = 'transparent';
			}

			// special check for radio buttons due to collecting them separately.
			if ( 'radio' === $input.attr( 'type' ) ) {
				if ( ! $input.prop( 'checked' ) ) {
					return;
				}
			}

			var value    = $input.val(),
				property = $input.data( 'property' ),
				$suffix  = $input.siblings( '.input-suffix' );

			if ( $suffix.length ) {
				var commaPos;

				suffixVal = $suffix.html().trim();
				commaPos  = suffixVal.indexOf( ',' );

				suffixVal = -1 !== commaPos ? suffixVal.substring( 0,commaPos ) : suffixVal;

				value = value == parseInt( value ) ? value + suffixVal : value;
			}

			if ( property !== undefined ) {
				var autoProperties = [ '--qbfw-width', '--qbfw-height', '--qbfw-opacity' ];
				if ( -1 !== $.inArray( property, autoProperties ) ) {
					defaultValue = 'auto';
				}

				if ( '' !== value ) {
					qodeBadgesForWooCommerceDisplayPreview.styleObject[property] = value;
				} else {
					var propertiesToSkip = [ '--qbfw-width-880', '--qbfw-height-880', '--qbfw-padding-880' ];

					if ( -1 !== $.inArray( property, propertiesToSkip ) ) {
						qodeBadgesForWooCommerceDisplayPreview.styleObject[property] = property.replace( '-880', '' );
					} else {
						qodeBadgesForWooCommerceDisplayPreview.styleObject[property] = 0 === defaultValue ? 0 + suffixVal : defaultValue;
					}
				}
			}
		},
		initStyle: function ( $preview, $positionField ) {
			var style    = '',
				$badge   = $preview.find( '.qbfw-badge' ),
				position = $positionField.val();

			if ( 'on_image' === position ) {
				if ( qodeBadgesForWooCommerceDisplayPreview.styleObject.horizontal !== undefined ) {
					switch (qodeBadgesForWooCommerceDisplayPreview.styleObject.horizontal) {
						case 'left':
							qodeBadgesForWooCommerceDisplayPreview.styleObject.left            = 0;
							qodeBadgesForWooCommerceDisplayPreview.styleObject.right           = 'initial';
							qodeBadgesForWooCommerceDisplayPreview.styleObject.translateXFinal = undefined;
							break;
						case 'center':
							qodeBadgesForWooCommerceDisplayPreview.styleObject.left            = '50%';
							qodeBadgesForWooCommerceDisplayPreview.styleObject.right           = 'initial';
							qodeBadgesForWooCommerceDisplayPreview.styleObject.translateXFinal = '-50%';
							break;
						case 'right':
							qodeBadgesForWooCommerceDisplayPreview.styleObject.left            = 'initial';
							qodeBadgesForWooCommerceDisplayPreview.styleObject.right           = 0;
							qodeBadgesForWooCommerceDisplayPreview.styleObject.translateXFinal = undefined;
							break;
					}
				}
				if ( qodeBadgesForWooCommerceDisplayPreview.styleObject.vertical !== undefined ) {
					switch (qodeBadgesForWooCommerceDisplayPreview.styleObject.vertical) {
						case 'top':
							qodeBadgesForWooCommerceDisplayPreview.styleObject.top             = 0;
							qodeBadgesForWooCommerceDisplayPreview.styleObject.bottom          = 'initial';
							qodeBadgesForWooCommerceDisplayPreview.styleObject.translateYFinal = undefined;
							break;
						case 'middle':
							qodeBadgesForWooCommerceDisplayPreview.styleObject.top             = '50%';
							qodeBadgesForWooCommerceDisplayPreview.styleObject.bottom          = 'initial';
							qodeBadgesForWooCommerceDisplayPreview.styleObject.translateYFinal = '-50%';
							break;
						case 'bottom':
							qodeBadgesForWooCommerceDisplayPreview.styleObject.bottom          = 0;
							qodeBadgesForWooCommerceDisplayPreview.styleObject.top             = 'initial';
							qodeBadgesForWooCommerceDisplayPreview.styleObject.translateYFinal = undefined;
							break;
					}
				}
				if ( qodeBadgesForWooCommerceDisplayPreview.styleObject.translateXFinal === undefined ) {
					if ( qodeBadgesForWooCommerceDisplayPreview.styleObject.translateX !== undefined ) {
						qodeBadgesForWooCommerceDisplayPreview.styleObject.translateXFinal = qodeBadgesForWooCommerceDisplayPreview.styleObject.translateX;
					} else {
						qodeBadgesForWooCommerceDisplayPreview.styleObject.translateXFinal = '0px';
					}
				}

				if ( qodeBadgesForWooCommerceDisplayPreview.styleObject.translateYFinal === undefined ) {
					if ( qodeBadgesForWooCommerceDisplayPreview.styleObject.translateY !== undefined ) {
						qodeBadgesForWooCommerceDisplayPreview.styleObject.translateYFinal = qodeBadgesForWooCommerceDisplayPreview.styleObject.translateY;
					} else {
						qodeBadgesForWooCommerceDisplayPreview.styleObject.translateYFinal = '0px';
					}
				}
			} else {
				qodeBadgesForWooCommerceDisplayPreview.styleObject.translateXFinal = '0px';
				qodeBadgesForWooCommerceDisplayPreview.styleObject.translateYFinal = '0px';
			}

			for ( var key in qodeBadgesForWooCommerceDisplayPreview.styleObject ) {
				if ( -1 !== $.inArray( key, [ 'translateX', 'translateXFinal', 'horizontal', 'translateY', 'translateYFinal', 'vertical' ] ) ) {
					continue;
				}
				style += key + ':' + qodeBadgesForWooCommerceDisplayPreview.styleObject[key] + ';';
			}

			style += '--qbfw-translate-x: ' + qodeBadgesForWooCommerceDisplayPreview.styleObject.translateXFinal + ';';
			style += '--qbfw-translate-y: ' + qodeBadgesForWooCommerceDisplayPreview.styleObject.translateYFinal + ';';

			$badge.attr( 'style', style );
		},
		initContentChange: function ( $preview, trig = false ) {
			var $contentTextarea = $( '.qode-badges-for-woocommerce-textarea-editor' ),
				$imageThumb      = $( '#qodef_qode_badges_for_woocommerce_image .qodef-image-thumb' ),
				$imagePredefined = $( '.qodef-field[name=qode_badges_for_woocommerce_badge_image_predefined]' );

			if ( ! trig ) {
				if ( tinymce.activeEditor !== null ) {
					tinymce.activeEditor.on(
						'keyup change',
						function () {
							// has to get badge again in here due to html change in preview.
							var $badge = $preview.find( '.qbfw-badge .qbfw-badge-text' );
							$badge.html( tinymce.activeEditor.getContent() );
						}
					);
				}

				if ( $contentTextarea.length ) {
					$contentTextarea.each(
						function () {
							$( this ).on(
								'keyup change',
								function ( e, content ) {
									// has to get badge again in here due to html change in preview.
									var $badge = $preview.find( '.qbfw-badge .qbfw-badge-text' );

									$badge.html( $.parseHTML( $( this ).val() ) );
								}
							);
						}
					);
				}

				if ( $imageThumb.length ) {
					$imageThumb.each(
						function () {
							$( this ).on(
								'change',
								function () {
									// has to get badge again in here due to html change in preview.
									var $badge       = $preview.find( '.qbfw-badge' ),
										$imageHolder = $( this ).find( '.qodef-single-image' ),
										$clone       = $imageHolder.clone().removeClass( 'qodef-single-image' );

									$badge.html( $clone );
								}
							);
						}
					);
				}

				if ( $imagePredefined.length ) {
					$imagePredefined.each(
						function () {
							$( this ).on(
								'change',
								function () {
									var $image       = $( this ).filter( ':checked' ).val(),
										$imageHolder = $preview.find( '.qbfw-badge-type-image img' );

									// if there is an img tag, we can just replace src, if there is not, we need to create it.
									if ( $imageHolder.length ) {
										$imageHolder.prop(
											'src',
											$image
										);
									} else {
										var image = '<img src="' + $image + '" />';
										$preview.find( '.qbfw-badge-type-image' ).html( image );
									}
								}
							);
						}
					);
				}
			}

			if ( 'textual' === trig ) {
				// trigger change on tinymce when active editor is visual ( isNotDirty returns true when textual editor).
				// trigger change on textarea when editor is textual.
				if ( ! tinymce.activeEditor.isNotDirty ) {
					tinymce.activeEditor.fire( 'change' );
				} else if ( $contentTextarea.length && tinymce.activeEditor.isNotDirty ) {
					$contentTextarea.trigger( 'change' );
				}
			} else if ( 'predefined_image' === trig ) {
				if ( $imagePredefined.length ) {
					$imagePredefined.filter( ':checked' ).trigger( 'change' );
				}
			} else if ( 'custom_image' === trig ) {
				if ( $imageThumb.length ) {
					$imageThumb.trigger( 'change' );
				}
			}

			if ( trig ) {
				setTimeout(
					function () {
						$preview.find( '.qbfw-badge' ).addClass( 'qbfw--show' );
					},
					500
				);
			}
		},
		initStickyPreview: function () {
			var contentHeight  = $( '#postbox-container-2' ).height() + $( '#post-body-content' ).outerHeight( true ),
				$stickyWrapper = $( '#side-sortables' ),
				adminBarHeight = $( '#wpadminbar' ).height(),
				$stickyInner   = $( '#qbfw-badge-preview' );

			$stickyWrapper.css( 'min-height', contentHeight );
			$stickyInner.css( 'top', adminBarHeight );
		},
		onTypeChange: function ( $preview ) {
			var $metaHolder     = $( '#qode-framework-woo-meta-box-qbfw_badge' ),
				$typeField      = $metaHolder.find( '.qodef-field[name=qode_badges_for_woocommerce_badge_type]' ),
				$positionField  = $metaHolder.find( '.qodef-field[name=qode_badges_for_woocommerce_badge_position]' ),
				$imageTypeField = $metaHolder.find( '.qodef-field[name=qode_badges_for_woocommerce_image_type]' );

			if ( $typeField.length ) {
				var options  = {},
					badge_id = $preview.data( 'badge-id' );

				options.badge_id = badge_id;

				$typeField.on(
					'change',
					function () {
						var type     = $typeField.val(),
							position = $positionField.val();

						options.type     = type;
						options.position = position;
						options.preview  = 'yes';

						$.ajax(
							{
								type: 'GET',
								url: qodeBadgesForWooCommercePreview.vars.restUrl + qodeBadgesForWooCommercePreview.vars.previewRestRoute,
								data: {
									options: options,
									security_token: qodeBadgesForWooCommercePreview.vars.restNonce,
								},
								beforeSend: function ( request ) {
									request.setRequestHeader(
										'X-WP-Nonce',
										qodeBadgesForWooCommercePreview.vars.restNonce
									);
								},
								success: function ( response ) {

									if ( response.status === 'success' ) {
										// depending on position change html on specific holder.
										if ( 'on_image' === position ) {
											$preview.find( '.qbfw-badge-preview-image-holder' ).html( response.data.html );
										} else {
											$preview.find( '.qbfw-badge-preview-before-title' ).html( response.data.html );
										}

										// reattach style.
										qodeBadgesForWooCommerceDisplayPreview.initPreview( $preview, true );

										// for image type check field value and use that for a type.
										if ( 'image' === options.type ) {
											options.type = $imageTypeField.val();
										}

										// trigger content change (text, img).
										qodeBadgesForWooCommerceDisplayPreview.initContentChange( $preview, options.type );

										$( 'body' ).trigger(
											'qode_badges_for_woocommerce_preview_trigger_after_ajax_call',
											[$preview, options]
										);
									} else {
										console.log( response.message );
									}
								},
								complete: function () {
								}
							}
						);
					}
				)
			}

			if ( $imageTypeField.length ) {
				$imageTypeField.on(
					'change',
					function () {
						var type = $imageTypeField.val();

						qodeBadgesForWooCommerceDisplayPreview.initContentChange( $preview, type );
					}
				)
			}

			if ( $positionField.length ) {
				$positionField.on(
					'change',
					function () {
						var $badge = $preview.find( '.qbfw-badge' );

						$badge.remove();

						$typeField.trigger( 'change' );
					}
				)
			}
		}
	};

	qodeBadgesForWooCommercePreview.qodeBadgesForWooCommerceDisplayPreview = qodeBadgesForWooCommerceDisplayPreview;

	var qodeBadgesForWooCommerceDisplayPreviewList = {
		init: function () {
			var hasBodyClass = $( 'body' ).hasClass( 'post-type-qbfw_badge' );
			this.holder      = $( '#posts-filter' );

			if ( hasBodyClass && this.holder.length ) {
				this.holder.each(
					function () {
						var $badgeItems = $( this ).find( '.column-qode_badge_preview .qbfw-badge' );

						if ( $badgeItems.length ) {
							$badgeItems.each(
								function () {
									qodeBadgesForWooCommerceDisplayPreviewList.recalc( $( this ) );
								}
							)
						}
					}
				);
			}
		},
		recalc: function ( $badge ) {
			var size         = 60,
				$badgeWidth  = $badge.outerWidth(),
				$badgeHeight = $badge.outerHeight(),
				scale;

			if ( $badgeWidth < $badgeHeight ) {
				scale = size / $badgeHeight;
			} else {
				scale = size / $badgeWidth;
			}

			$badge.css( 'transform', 'scale(' + scale + ')' );
		}
	};

})( jQuery );
