jQuery( document ).ready( function( $ ) {

	// show image upload form
	$( document ).on( 'click', '.js-pm-img-attach-btn', function( e ) {
		$( '.messages-image-uploader-wrapper' ).show();
		$( this ).parents( '.thread-input-padding' ).find( '.dz-default.dz-message' ).trigger( 'click' );
	});

	// show file upload form
	$( document ).on( 'click', '.js-pm-file-attach-btn', function( e ) {
		$( '.file_upload_pm_attachments' ).siblings( 'input[type="file"]' ).trigger( 'click' );
	});

	// show search user form
	$( document ).on( 'click', '.js-search-users-btn', function( e ) {
		if ( $( '.thread-list-user-search' ).is( ':hidden' ) ) { // open search from
			$( this ).find( 'i' ).removeClass( 'search' ).addClass( 'times' );
			$( '.thread-list-user-search' ).slideDown( 'fast' );

			// for page builder
			$( '.js-search-users-btn-open' ).hide();
			$( '.js-search-users-btn-close' ).css({ display: "flex" });

		} else { // close search form
			$( this ).find( 'i' ).removeClass( 'times' ).addClass( 'search' );
			$( '.thread-list-user-search' ).slideUp( 'fast' );

			// for page builder
			$( '.js-search-users-btn-open' ).css({ display: "flex" });
			$( '.js-search-users-btn-close' ).hide();

			$( '.js-search-conversation-input' ).val( '' ); // reset search input
			wpj_search_conversation_user( '.js-search-conversation-input' ); // show all conversations

			$( '.js-search-conversation-results' ).remove(); // remove results wrapper
			$( '.wpj-load-more-target' ).show(); // display conversations before search
			$( '#no_messages' ).hide(); // hide 'no message' wrapper

		}
	});

	// search conversations action
	$( document ).on( 'click', '.js-search-database-conversations', function( e ) {
		addLoader( '#no_messages' );

		jQuery.ajax({
			url  : wpj_vars.ajaxurl,
			type : 'post',
			data : {
				action  : 'search_conversation_action',
				username: validateInputContent( jQuery( '.js-search-conversation-input' ).val().toLowerCase() )
			},
			success: function( results ) {
				if ( results ) {
					$( '#no_messages' ).hide(); // hide 'no message' wrapper

					// display search results
					if ( $( '.js-search-conversation-results' )[0] )
						$( '.js-search-conversation-results' ).html( results );

					else
						$( '<div class="js-search-conversation-results">' + results + '</div>' ).insertAfter( '#no_messages' );

					$( '.wpj-load-more-target' ).hide(); // hide conversations before search

				} else {
					$( '.ui.active.inverted.dimmer' ).remove();
					$( '#no_messages' ).html( wpj_vars.no_user_found ); // show 'no user found' message

				}
			}
		});
	});

	// show search message form
	$( document ).on( 'click', '.js-search-message-btn', function( e ) {
		if ( $( '.js-search-message-form' ).is( ':hidden' ) ) { // open search from
			$( '.js-search-message-form' ).slideDown({
				start: function () {
					$( this ).css({ display: "flex" });
				}
			});

			// for code
			$( this ).find( 'i' ).removeClass( 'search' ).addClass( 'times' );

			// for page builder
			$( '.js-search-message-btn-open' ).hide();
			$( '.js-search-message-btn-close' ).css({ display: "flex" });

		} else { // close search form
			$( '.js-search-message-form' ).slideUp( 'fast' );

			// remove classes
			$( '.js-search-message-form' ).removeClass( 'error' ).removeClass( 'loading' );

			// reset input
			$( '.js-message-search-input' ).val( '' );

			// for code
			$( this ).find( 'i' ).removeClass( 'times' ).addClass( 'search' );

			// for page builder
			$( '.js-search-message-btn-open' ).css({ display: "flex" });
			$( '.js-search-message-btn-close' ).hide();

			// remove message id from URL
			var message_id_from_url = window.location.href.replace( /\/+$/,'' ).split( '/' ).pop();
			if ( isInt( message_id_from_url ) ) {
				var page_url = wpj_vars.page_url;
				page_url = page_url.slice( 0, page_url.lastIndexOf( '/' ) );
				history.pushState( null, null, page_url );
			}

			// reset content
			refreshContent( '.js-messages-list .kt-inside-inner-col:first' );

		}
	});

	// search message action
	$( document ).on( 'click', '.js-message-search-action', function( e ) {
		if ( $( '.js-message-search-input' ).val() ) {
			$( '.js-search-message-form' ).removeClass( 'error' );
			$( '.js-search-message-form' ).addClass( 'loading' );

			$.ajax({
				type: 'post',
				url : wpj_vars.ajaxurl,
				data: {
					action         : 'search_message_action',
					keyword        : $( '.js-message-search-input' ).val(),
					interlocutor_id: $( '.pm-list' ).attr( 'data-uid' )
				},
				success: function( data ) {
					$( '.js-search-message-form' ).removeClass( 'loading' );

					if ( data ) {
						if ( $( '.js-search-messages-result' )[0] ) // if the search form is already used
							$( '.js-search-messages-result' ).replaceWith( '<div class="pm-list">' + data + '</div>' );
						else // if first search
							$( '.pm-list' ).html( data );

						// init Semantic UI elements
						if ( typeof $.fn.wpjSemanticInit == 'function' ) $.fn.wpjSemanticInit();

						// highlight the searched word
						$( '.pm-list' ).wordHighlight( $( '.js-message-search-input' ).val(), 'highlighted' );

					} else {
						$( '.js-search-message-form' ).notify( wpj_vars.nothing_found, { position: 'top left', className: 'error' } );

					}
				}
			});

		} else {
			$( '.js-search-message-form' ).addClass( 'error' );

		}
	});

	// search results action
	$( document ).on( 'click', '.js-search-message-result-wrapper', function( e ) {
		var message_id = $( this ).attr( 'data-id' );

		// add loader
		addLoader( '.js-messages-list' );

		// go to message
		$.ajax({
			type: 'post',
			url : wpj_vars.ajaxurl,
			data: {
				action         : 'search_message_result_action',
				message_id     : message_id,
				interlocutor_id: $( '.pm-list' ).attr( 'data-uid' )
			},
			success: function( data ) {
				// remove loader
				$( '.ui.active.inverted.dimmer' ).remove();

				// add message id to URL
				var page_url = wpj_vars.page_url;

				var message_id_from_url = window.location.href.replace( /\/+$/,'' ).split( '/' ).pop();
				if ( isInt( message_id_from_url ) )
					page_url = page_url.slice( 0, page_url.lastIndexOf( '/' ) );

				history.pushState( null, null, page_url + '/' + message_id );

				// insert messages
				if ( data ) {
					$( '.pm-list' ).replaceWith( data );
					if ( typeof $.fn.wpjSemanticInit == 'function' ) $.fn.wpjSemanticInit();

				}
			}
		});
	});

	// search message with enter
	$( document ).on( 'keypress', '.js-message-search-input', function( e ) {
		if ( e.keyCode == 13 && ! e.shiftKey ) {
			e.preventDefault();
			$( '.js-message-search-action' ).trigger( 'click' );
		}
	});

	// conversation actions
	$( document ).on( 'click', '.js-pm-action-archive, .js-pm-action-unarchive, .js-pm-action-delete, .js-pm-delete', function ( e ) {
		e.preventDefault();

		var action = '';
		if ( $( this ).attr( 'class' ).includes( 'js-pm-action-archive' ) )
			action = 'archive_conversation_action';
		else if ( $( this ).attr( 'class' ).includes( 'js-pm-action-unarchive' ) )
			action = 'unarchive_conversation_action';
		else if ( $( this ).attr( 'class' ).includes( 'js-pm-action-delete' ) )
			action = 'delete_conversation_action';
		else if ( $( this ).attr( 'class' ).includes( 'js-pm-delete' ) )
			action = 'delete_message_action';

		$.ajax({
			type: 'post',
			url : wpj_vars.ajaxurl,
			data: {
				action      : action,
				interlocutor: $( this ).attr( 'data-uid' ),
				message_id  : $( this ).attr( 'data-pm-id' )
			},
			success: function( data ) {
				if ( action == 'delete_message_action' ) {
					// refresh message body div
					refreshContent( '.js-messages-list .kt-inside-inner-col:first' );

					// refresh conversations body div
					refreshContent( '.thread-list-wrapper' );

				} else {
					// go to pm page
					changeURL( wpj_vars.pm_url );

				}
			}
		});
	});

	// send message
	$( document ).on( 'click', '.submit-private-message', function( e ) {
		e.preventDefault();

		var otheruid = $( '#pm_interlocutor_id' ).val();

		if ( wpj_vars.pm_emoji_enabled == 1 )
			var message = validateInputContent( $( '.cmi-listen.message-field' ).data( 'emojioneArea' ).getText() );

		else
			var message = validateInputContent( $( '.cmi-listen.message-field' ).val() );

		var upload     = $( 'input[name="hidden_files_pm_attachments"]' ).val();
		var img_upload = '';

		if ( $( '.dz-success.dz-complete' )[0] ) {
			var img_upload_arr = [];

			$( '.dz-success.dz-complete' ).each( function () {
				img_upload_arr.push( $( this ).attr( 'data-id' ) );
			});

			img_upload = img_upload_arr.join( ',' );
		}

		var request_id = $( '#pm_request_id' ).val();
		var job_id     = $( '#pm_job_id' ).val();

		if ( wpj_vars.pm_emoji_enabled == 1 )
			var message_length = get_input_length_emoji( $( '.cmi-listen.message-field' ).data( 'emojioneArea' ).getText() );

		else
			var message_length = get_input_length( $( '.cmi-listen.message-field' ) );

		if ( message == '' && ! upload && ! img_upload )
			wpj_focus_pm_input();

		else if ( message_length < parseInt( wpj_vars.characters_pm_min ) && ! upload && ! img_upload )
			$( '.wrapper-pm-to-user' ).notify( wpj_vars.pm_min_content, { position: 'top', className: 'error' } );

		else if ( message_length > parseInt( wpj_vars.characters_pm_max ) && ! upload && ! img_upload )
			$( '.wrapper-pm-to-user' ).notify( wpj_vars.pm_max_content, { position: 'top', className: 'error' } );

		else {
			jQuery.ajax({
				type: 'post',
				url : wpj_vars.ajaxurl,
				data: {
					action    : 'send_message_action',
					otheruid  : otheruid,
					message   : message,
					upload    : upload,
					img_upload: img_upload,
					request_id: request_id,
					job_id    : job_id,
				},
				beforeSend: function() {
					// add loader
					addLoader( '.thread-input' );
				},
				success: function( data ) {
					// refresh message body div
					refreshContent( '.js-messages-list .kt-inside-inner-col:first' );

					// refresh conversations body div
					refreshContent( '.thread-list-wrapper' );

					// remove no message string
					$( '.error-no-messages' ).remove();

					// clear the input
					$( '#message-pm-user' ).val( '' );
					$( '#message-pm-user' ).css( 'height', 'auto' );

					if ( wpj_vars.pm_emoji_enabled == 1 ) $( '.emojionearea-editor' ).text( '' );

					// clear the attachments queue
					$( '#uploadifive-file_upload_pm_attachments-queue' ).empty();
					$( 'input[name="hidden_files_pm_attachments"]' ).val( '' );

					// close image attachments queue
					$( '.messages-image-uploader-wrapper' ).hide();

					// clear the image attachments queue
					$( '.dz-image-wrapper' ).remove();

					// remove has-scroll class
					jQuery( '.thread-input' ).removeClass( 'has-scroll' );

					// remove mb20 class
					jQuery( '.files-attachments-wrapper' ).removeClass( 'mb20' );
				},
				error: function( response ) {
					console.log( response );
				},
				complete: function() {
					// remove loader
					setTimeout( function () { $( '.ui.active.inverted.dimmer' ).remove(); }, 2000 );

					// focus the input
					wpj_focus_pm_input();
				}
			});

		}

	});

	// send message with enter
	$( document ).on( 'keypress', '.cmi-listen.message-field', function( e ) {
		if ( $( '#pm-enter-key' ).is( ':checked' ) && e.keyCode == 13 && ! e.shiftKey ) {
			e.preventDefault();
			if ( $( this ).parents( '.wrapper-pm-to-user' )[0] ) $( '.submit-private-message' ).trigger( 'click' );
			if ( $( this ).parents( '#order-message-form' )[0] ) $( '.send-message' ).trigger( 'click' );
		}
	});

	// auto-resize textarea based on input
	if ( jQuery( '.is-page-pm-single' )[0] ) {

		// TODO: doesn't work on window resize
		$( '.cmi-listen.message-field' ).each( function () {
			// note: this breaks the emojionearea input on Firefox

		}).on( 'input propertychange change blur', function () {
			this.style.height = 'auto';
			this.style.height = ( this.scrollHeight ) + 'px';

			if ( ! wpj_vars.pm_emoji_enabled == 1 ) {
				if ( this.scrollHeight >= 207 )
					$( '.thread-input' ).addClass( 'has-scroll' );

				else
					$( '.thread-input' ).removeClass( 'has-scroll' );
			}
		});

		MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
		var observer = new MutationObserver( function( mutations, observer ) {
			// fired when a mutation occurs
			// note: this triggers 70 times on first input focus for some reason

			// auto-resize content container based on input
			jQuery( '.thread-wrapper' ).css( 'margin-bottom', jQuery( '.thread-input' ).height() );
		});

		// define what element should be observed by the observer
		// and what types of mutations trigger the callback
		observer.observe(document, {
			subtree: true,
			attributes: true,
			childList: true
			//...
		});
	}

	// fire lazy load on messages scroll
	if ( $( '.is-page-pm' )[0] ) {
		$( '.js-messages-list' ).on( 'scroll', _.debounce( function(){
			if ( typeof $.fn.wpjLazyLoadRender == 'function' ) {
				$.fn.wpjLazyLoadRender();
			}
		}, 200 ) );

		$( '.thread-list-viewport' ).on( 'scroll', _.debounce( function(){
			if ( typeof $.fn.wpjLazyLoadRender == 'function' ) {
				$.fn.wpjLazyLoadRender();
			}
		}, 200 ) );
	}

	// display scroll down button
	if ( $( '.js-messages-list' )[0] && wpj_vars.enable_scroll_down_button != 0 ) {
		$( '.pusher' ).on( 'mousewheel DOMMouseScroll scroll', '.js-messages-list', function() {
			if ( $( this ).scrollTop() < -100 )
				$( '.js-scroll-down' ).show();

			else if ( $( this ).scrollTop() >= 0 )
				$( '.js-scroll-down' ).hide();
		});
	}

	// scroll down action
	$( document ).on( 'click', '.js-scroll-down', function( e ) {
		var elem = $( '.pm-messages-row-wrapper.js-messages-list' );

		elem.animate({ scrollTop: elem[0].scrollHeight }, 2000 );

		$( this ).hide();
	});

});

function wpj_focus_pm_input() {
	if ( jQuery( '.is-page-pm-single' )[0] ) {
		var username = window.location.pathname.split( '/' ).filter( Boolean ).pop();

		if ( isNaN( username ) ) {
			if ( wpj_vars.pm_emoji_enabled == 1 ) {
				setTimeout( function() {
					jQuery( '.emojionearea-editor' ).focus();
				}, 300 );

			} else {
				jQuery( '#message-pm-user' ).focus();

			}
		}
	}
}

function wpj_send_message_with_enter() {
	if ( jQuery( '.ui.checkbox.send-message-enter-key' )[0] ) {

		jQuery( '.ui.checkbox.send-message-enter-key' ).checkbox({
			onChange: function() {
				jQuery.ajax({
					type: 'post',
					url : wpj_vars.ajaxurl,
					data: {
						action: 'save_pm_enter_key_action',
						value : jQuery( '#pm-enter-key' ).is( ':checked' ) ? true : false,
					},
					success: function( data ) {}
				});
			}
		});

	}
}

function wpj_hide_admin_bar_on_pm_page() {
	if ( jQuery( '.is-page-pm' )[0] ) jQuery( 'html' ).attr( 'style', 'margin-top: 0 !important' );
	else jQuery( 'html' ).removeAttr( 'style' );
}

function wpj_search_conversation_user( element ) {
	// user to search
	var value = validateInputContent( jQuery( element ).val().toLowerCase() );

	// if the wanted user existed, display it
	jQuery( '#user_messages .js-tpm-holder' ).each( function() {
		if ( jQuery( this ).find( '.pm-user' ).text().toLowerCase().search( value ) > -1 ) jQuery( this ).show();
		else jQuery( this ).hide();
	});

	// render the images
	if ( typeof jQuery.fn.wpjLazyLoadRender == 'function' ) jQuery.fn.wpjLazyLoadRender();

	// show/hide "No user found" message
	var message = '<div class="p10 text-center">';

		if ( jQuery( '#user_messages .js-tpm-holder' ).children( ':visible' ).length == 0 )
			message += '<p>' + wpj_vars.no_user_current_screen + '</p>';

		message += '<p>' + wpj_vars.looking_recent_conversations + '</p>';

		message += '<a class="js-search-database-conversations cursor-pointer">';
			message += '<i class="search blue icon"></i>' + wpj_vars.search_older_conversations;
		message += '</a>';

	message += '</div>';

	jQuery( '#no_messages' ).show().html( message );

}

function wpj_filter_message( msg ) {
	ret = '';

	jQuery.ajax({
		url  : wpj_vars.ajaxurl,
		type : 'post',
		async: false,
		data : {
			action : 'filter_message_action',
			message: msg
		},
		success: function( result ) {
			ret = result;
		}
	});

	// return filtered message
	return ret;
}

function wpj_move_conversation_top_by_url() {
	if ( jQuery( '.is-page-pm.is-page-pm-single' )[0] ) {
		var username = window.location.pathname.split( '/' ).filter( Boolean ).pop();

		jQuery( '#user_messages .js-tpm-holder' ).each( function() {
			if ( jQuery( this ).find( '.pm-user' ).text().toLowerCase().search( username ) > -1 ) {
				if ( jQuery( '.wpj-load-more-target' )[0] ) {
					jQuery( this ).detach().prependTo( '#user_messages .wpj-load-more-target' );

				} else {
					jQuery( this ).detach().prependTo( '#user_messages' );

				}
			}
		});
	}
}

function wpj_disable_deleted_user_sections() {
	if ( jQuery( '.is-page-pm.is-page-pm-single' )[0] ) {
		var username = window.location.pathname.split( '/' ).filter( Boolean ).pop();

		if ( isNumeric( username ) ) {
			jQuery( '.thread-input' ).addClass( 'div-disabled' );
			jQuery( '.js-message-custom-offer-action-btn' ).addClass( 'div-disabled' );
		}
	}
}

function wpj_set_pm_page_height() {
	if ( jQuery( '.is-page-pm' )[0] ) {
		var window_height = jQuery( window ).height();
		var header_height = jQuery( '.header-wrapper:visible' ).outerHeight();
		var header_offset = jQuery( '.header-wrapper:visible' )[0].offsetHeight;

		if ( jQuery( window ).width() <= 767 ) {
			var space = 40;

		} else if ( jQuery( window ).width() <= 1024 ) {
			var space = 30;

		} else {
			var space = 20;

		}

		if ( jQuery( '.is-page-pm' )[0] && jQuery( '.is-page-pm-single' )[0] ) {
			jQuery( '.pm-messages-row-wrapper' ).css( 'height', window_height - header_height - header_offset - space );

		} else if ( jQuery( '.is-page-pm' )[0] && ! jQuery( '.is-page-pm-single' )[0] ) {
			jQuery( '.pm-conversations-row-wrapper' ).css( 'height', window_height - header_height - header_offset - space + 10 );

		}
	}
}