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

	if ( wpj_vars.chat_enabled && wpj_vars.is_user_logged_in ) {

		var active_popups = []; // this array contains the open message boxes

/*** TOGGLE SIDEBAR ****/
		$( document ).on( 'click', '.chat-sidebar-anchor', function() {

			var sidebar_wrapper = $( this ).parents( '.chat-sidebar-container' ).find( '.chat-sidebar-wrapper' );

			// set cookie
			var sidebar_status = wpj_chat_set_box_status_cookie( sidebar_wrapper );

			if ( sidebar_status == 'minimized' ) {

				if ( $( this ).find( 'div:visible' ).attr( 'class' ) == 'chat-sidebar-anchor-icon' ) {

					sidebar_wrapper.hide( "slide", { direction: ( wpj_vars.is_rtl ? 'left' : 'right' ) }, 300 );

					wpj_chat_animate_element( 'hide' );

				} else if ( $( this ).find( 'div:visible' ).attr( 'class' ) == 'chat-sidebar-anchor-text' ) {

					sidebar_wrapper.slideToggle( 300 );

					$( '.chat-sidebar-anchor-icon' ).removeAttr( 'style' );

				}

				$( '.is-chat-active' ).addClass( 'is-chat-minimized' );
				$( '.is-chat-active' ).removeClass( 'is-chat-maximized' );

			} else {

				if ( $( this ).find( 'div:visible' ).attr( 'class' ) == 'chat-sidebar-anchor-icon' ) {
					sidebar_wrapper.show( "slide", { direction: ( wpj_vars.is_rtl ? 'left' : 'right' ) }, 300 );
					wpj_chat_animate_element( 'show' );

				} else if ( $( this ).find( 'div:visible' ).attr( 'class' ) == 'chat-sidebar-anchor-text' ) {
					sidebar_wrapper.slideToggle( 300 );
					$( '.chat-sidebar-anchor-icon' ).removeAttr( 'style' );

				}

				$( '.is-chat-active' ).addClass( 'is-chat-maximized' );
				$( '.is-chat-active' ).removeClass( 'is-chat-minimized' );

				if ( typeof $.fn.wpjLazyLoadRender == 'function' ) $.fn.wpjLazyLoadRender();
			}

		});
/*** END TOGGLE SIDEBAR ****/

/*** ARCHIVE CONVERSATION ****/
		$( document ).on( 'click', '.archive-conversation', function( e ) {
			e.preventDefault();

			var box_id = $( this ).parents( '.chat-sidebar-user-box' ).attr( "data-box-id" )
			$( '[rel="' + box_id + '"]' ).find( '.message-box-close' ).trigger( 'click' );

			var current_user = $( this ).parents( ".chat-sidebar-user-box" );

			$.ajax({
				type: 'post',
				url : wpj_vars.ajaxurl,
				data: {
					action      : 'archive_conversation_action',
					interlocutor: box_id
				},
				success: function( data ) {
					$( current_user ).hide( 400 );
				}
			});
		});
/*** END ARCHIVE CONVERSATION ****/

/*** OPEN BOX ***/
		$( document ).on( 'click', '.chat-sidebar-user-box', function( e ) {
			// skip action archive icon is clicked
			if ( $( e.target ).hasClass( 'archive-conversation' ) || $( e.target ).parent().hasClass( 'archive-conversation' ) ) {
				return false;
			}

			// get current user data
			var box_id   = $( this ).attr( "data-box-id" ); // box id
			var this_box = $( '[rel="' + box_id + '"]' ); // box id element

			// show user to sidebar if is archived
			if ( $( '.chat-sidebar-user-box[data-box-id="' + box_id + '"]' ).is( ':hidden' ) ) {
				$( '.chat-sidebar-user-box[data-box-id="' + box_id + '"]' ).show();

				$.ajax({
					type: 'post',
					url : wpj_vars.ajaxurl,
					data: {
						action      : 'unarchive_conversation_action',
						interlocutor: box_id
					},
					success: function( data ) {
						if ( typeof $.fn.wpjLazyLoadRender == 'function' ) $.fn.wpjLazyLoadRender();
					}
				});
			}

			// the number of boxes that fit in the screen
			var total_popups = wpj_chat_calculate_popup_no();

			// get only the last total_popups elements from array,
			var screen_popups = active_popups.slice( - total_popups );

			// delete span for unread messages
			$( this ).find( '.msg-unread-count' ).remove();

			// box is already on the first screen
			if ( $.inArray( box_id, screen_popups ) != -1 ) {

				if ( this_box.find( '.message-box-wrapper' ).hasClass( 'minimized' ) ) { // box is minimized
					this_box.find( '.message-box-head' ).trigger( 'click' ); //maximize the box
				} else { // box is maximized
					this_box.find( '.message-box-wrapper' ).addClass( 'has-focus' ); // add class for focus
					this_box.find( '.message-box-input-content' ).focus(); // set focus on the current box
				}

			} else {

				// if box already opened but is hidden,
				// remove from the current position,
				// to be inserted to the first position
				if ( $.inArray( box_id, active_popups ) != -1 ) {
					active_popups.splice( $.inArray( box_id, active_popups ), 1 );
					this_box.remove();
				}

				// add the new box to active popups
				active_popups.push( box_id );

				// MINIMIZE STORED BOXES
				// minimize the boxes when loading the page
				// if they have been minimized on a previous page
				box_status = 'maximized';
				if ( e.originalEvent === undefined ) { // is triggered
					var stored_popups_minimized = wpj_chat_get_stored_active_boxes( 'minimized_popups' );
					if ( $.inArray( box_id, stored_popups_minimized ) != -1 ) {
						box_status = 'minimized'; // minimize the box
					}
				}

				// open boxes
				$.ajax({
					type: 'post',
					url : wpj_vars.ajaxurl,
					data: {
						action    : 'display_box_content_action',
						user_id   : box_id,
						box_status: box_status
					},
					success: function( data ) {
						$( '.pusher' ).append( data );

						// initialize semantic ui fields
						$.fn.wpjSemanticInit();

						// initialize semantic ui tooltips
						wpj_init_chat_tooltips();

						// initialize emoji
						if ( wpj_vars.chat_emoji_enabled == 1 ) wpj_chat_emoji_init( '[rel="' + box_id + '"] .message-box-input-content.' + box_id );

						// initialize quick response
						wpj_init_quick_responses();

						// initialize uploader
						wpj_init_upload_form( 1, 'file_upload_chat_attachments_' + box_id, 'hidden_files_chat_attachments_' + box_id, 'chat_messages_' + box_id );

						// initialize image uploader
						wpj_init_dropzone_images_uploader( wpj_vars.message_pics_nr_max, wpj_vars.message_filesize_max, 'chat_images_' + box_id );

						// initialize pm gallery
						wpj_init_attachments_gallery();

						// init load more messages
						wpj_init_load_more_messages();

						// recalculate the position of the boxes
						wpj_chat_display_boxes( active_popups, 'open_popup' );
					}
				});

			}

			// save active boxes to be loaded to other pages
			wpj_chat_store_active_boxes( active_popups.slice( - total_popups ), 'active_popups' );
		});
/*** END OPEN BOX ***/

/*** MINIMIZE/MAXIMIZE BOX ****/
		$( document ).on( 'click', '.message-box-head', function() {
			var $this = $( this ); // this box

			// maximize
			if ( $( this ).parents( '.message-box-wrapper' ).hasClass( 'minimized' ) ) {
				// add class for focus
				$( this ).parents( '.message-box-wrapper' ).removeClass( 'minimized' ).addClass( 'has-focus' );

				// slide and animate
				$( this ).parents( '.message-box-wrapper' ).find( '.message-box-body' ).slideToggle( 300 );
				$( this ).parents( '.message-box-wrapper' ).animate( { width: '+=80px' }, 300 );

				// set focus on the current box
				$( this ).parents( '.message-box-wrapper' ).find( '.message-box-input-content' ).focus();

				// add extra right space
				wpj_chat_change_boxes_margin( $this, 'extend', 80 );

				// save active boxes to be loaded to other pages
				wpj_chat_store_active_boxes( $( this ).parents( '.message-box-container' ).attr( "rel" ), 'removed' );

			} else { // minimize

				// slide and animate
				$( this ).parents( '.message-box-wrapper' ).find( '.message-box-body' ).slideToggle( 300, function() {
					// remove focus class
					$( this ).parents( '.message-box-wrapper' ).addClass( 'minimized' ).removeClass( 'has-focus' );
				});
				$( this ).parents( '.message-box-wrapper' ).animate( { width: '-=80px' }, 300 );

				// remove extra right space
				wpj_chat_change_boxes_margin( $this, 'reduce', 80 );

				// save active boxes to be loaded to other pages
				wpj_chat_store_active_boxes( $( this ).parents( '.message-box-container' ).attr( "rel" ), 'minimized' );
			}

			// remove class unread
			$( this ).parents( '.message-box-wrapper' ).removeClass( 'unread' );

			return false;
		});
/*** END MINIMIZE/MAXIMIZE BOX ****/

/*** CLOSE BOX ***/
		$( document ).on( 'click', '.message-box-close', function( e ) {
			e.preventDefault();
			e.stopPropagation();

			// remove from array
			var box_id = $( this ).parents( '.message-box-container' ).attr( "rel" );
			active_popups.splice( $.inArray( box_id, active_popups ), 1 );

			// remove from front
			$( this ).parents( '.message-box-container' ).remove();

			// recalculate the position of the boxes
			wpj_chat_display_boxes( active_popups, 'close_popup' );

			// the number of boxes that fit in the screen
			var total_popups = wpj_chat_calculate_popup_no();

			// get only the last total_popups elements from array,
			var screen_popups = active_popups.slice( - total_popups );

			// update stored active boxes
			wpj_chat_store_active_boxes( screen_popups, 'active' );
			wpj_chat_store_active_boxes( box_id, 'removed' );
		});
/*** END CLOSE BOX ***/

/*** CLICK - SEND MESSAGE ***/
		$( document ).on( 'click', '.js-message-box-footer-send-button', function( e ) {
			$( '.message-box-container #message_box_input_content, .message-box-container .emojionearea' ).blur();
		});
/*** END CLICK - SEND MESSAGE ***/

/*** ENTER - SEND MESSAGE ***/
		$( document ).on( 'blur keypress keyup paste input', '.message-box-container #message_box_input_content, .message-box-container .emojionearea', function( e ) {

			// stops enter action
			// if the attachments were not fully loaded
			var attachments_complete = true;

			if ( $( this ).parents( '.message-box-footer' ).find( '.uploadifive-queue-item' )[0] ) {
				$( this ).parents( '.message-box-footer' ).find( '.uploadifive-queue-item' ).each( function() {
					if ( $( this ).hasClass( 'complete' ) ) attachments_complete = true;
					else attachments_complete = false;
				});
			}

			// if the key is enter and shift is not press
			// shift + enter for new line
			if ( ( e.keyCode == 13 || e.originalEvent === undefined ) && ! e.shiftKey && attachments_complete ) {

				if ( wpj_vars.chat_emoji_enabled == 1 && $( this ).is( '#message_box_input_content' ) )
					return false;

				if ( wpj_vars.chat_emoji_enabled == 1 ) {

					// get message
					var msg_orig = validateInputContent( $( this ).siblings( '#message_box_input_content' ).data( 'emojioneArea' ).getText() );

					// get message with line breaks
					var msg = msg_orig.replace( /</g, '&lt;' ).replace( />/g,'&gt;' ).replace( /\n/g, '<br/>' );

				} else {

					// get message
					var msg_orig = validateInputContent( $( this ).text() );

					// get message with line breaks
					var msg = $( this ).text().replace( /</g, '&lt;' ).replace( />/g,'&gt;' ).replace( /\n/g, '<br/>' );

				}

				// get box id
				var box_id = $( this ).parents( '.message-box-container' ).attr( "rel" );

				// get file attachments
				var file_upload = $( 'input[name="hidden_files_chat_attachments_' + box_id + '"]' ).val();

				// get images attachments
				var img_upload = '';

				if ( $( this ).parents( '.message-box-footer' ).find( '.dz-success.dz-complete' )[0] ) {
					var img_upload_arr = [];

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

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

				if ( wpj_vars.chat_emoji_enabled == 1 ) var message_length = get_input_length_emoji( msg );
				else var message_length = get_input_length( $( this ), 'html' );

				// if message is not empty
				if ( file_upload || img_upload || ( msg.trim().length != 0 && message_length >= parseInt( wpj_vars.characters_pm_min ) && message_length <= parseInt( wpj_vars.characters_pm_max ) ) ) {

					// insert to box
					wpj_chat_insert_message_to_box( box_id, msg, img_upload );

					// insert to database
					$.ajax({
						type: 'post',
						url : wpj_vars.ajaxurl,
						data: {
							action    : 'send_message_action',
							otheruid  : box_id,
							message   : msg_orig,
							upload    : file_upload,
							img_upload: img_upload,
							request_id: '',
							job_id    : '',
						},
						success: function( data ) {
							// initialize pm gallery
							wpj_init_attachments_gallery();
						}
					});

					// clear attachments queue
					$( '#uploadifive-file_upload_chat_attachments_' + box_id + '-queue' ).empty();

					// close image attachments queue
					if (
						$( this ).parents( '.message-box-footer' ).find( '.message-box-footer-options' ).is( ':visible' )
						|| $( this ).parents( '.message-box-footer' ).find( '.messages-image-uploader-wrapper' ).is( ':visible' )
					)
						$( this ).parents( '.message-box-footer' ).find( '.js-message-options-btn' ).trigger( 'click' );

					// clear the image attachments queue
					$( this ).parents( '.message-box-footer' ).find( '.dz-image-wrapper' ).remove();

					// clear attachments value
					$( "input[name=hidden_files_chat_attachments_" + box_id + "]" ).val( '' );
				}

				// show placeholder
				if ( ! wpj_vars.chat_emoji_enabled == 1 )
					$( this ).parents( '.message-box-footer' ).find( '.message-box-placeholder-container' ).show();

				// clear the box
				if ( wpj_vars.chat_emoji_enabled == 1 )
					$( this ).siblings( '#message_box_input_content' ).data( 'emojioneArea' ).setText( '' );
				else
					$( this ).text( '' );

				// clear 'no message' pusher div
				$( this ).parents( '.message-box-wrapper' ).find( '.no-results' ).text( '' );

				return false;

			} else { // click on the box input

				if ( $( this ).text() !== '' ) { // input has content
					// hide placeholder
					$( this ).parents( '.message-box-footer' ).find( '.message-box-placeholder-container' ).hide();

				} else { // input is empty
					// show placeholder
					if ( ! wpj_vars.chat_emoji_enabled == 1 )
						$( this ).parents( '.message-box-footer' ).find( '.message-box-placeholder-container' ).show();

				}

				if ( e.keyCode == 13 && ! e.shiftKey ) return false;

			}

			if ( e.key === "Escape" ) {
				$( '[rel="' + box_id + '"]' ).find( '.message-box-close' ).trigger( 'click' );
			}

		});
/*** END ENTER - SEND MESSAGE ***/

/*** LINKS - BOX HEAD ***/
		$( document ).on( 'click', '.message-box-maximize, .message-box-logo-area, .message-box-user-info-title-container', function( e ) {
			// if box is not minimized
			if ( ! $( this ).parents( '.message-box-wrapper' ).hasClass( 'minimized' ) ) {
				// stop other action
				e.preventDefault();
				e.stopPropagation();

				// redirect to url
				window.location.href = $( this ).find( 'a' ).attr( 'href' );
			}
		});
/*** END LINKS - BOX HEAD ***/

/*** MESSAGE OPTIONS ***/
		$( document ).on( 'click', '.js-message-options-btn', function( e ) {
			if ( $( this ).parents( '.message-box-footer' ).find( '.message-box-footer-options' ).is( ':hidden' ) ) {
				if ( $( this ).parents( '.message-box-footer' ).find( '.messages-image-uploader-wrapper' ).is( ':visible' ) ) {
					$( this ).parents( '.message-box-footer' ).find( '.messages-image-uploader-wrapper' ).hide( 'slide', { direction: 'down' }, 300 );
					$( this ).animateStep({ from: 45, to: 0, step: $.fn.rotate });

				} else {
					$( this ).parents( '.message-box-footer' ).find( '.message-box-footer-options' ).slideDown({
						start: function () {
							$( this ).css({ display: "flex" })
						}
					});

					$( this ).animateStep({ from: 0, to: 45, step: $.fn.rotate });

				}

			} else {
				$( this ).parents( '.message-box-footer' ).find( '.message-box-footer-options' ).slideUp();
				$( this ).animateStep({ from: 45, to: 0, step: $.fn.rotate });

			}
		});
/*** END MESSAGE OPTIONS ***/

/*** IMAGE UPLOAD FORM ***/
		$( document ).on( "click", ".js-chat-img-attach-btn", function( e ) {
			$( this ).parents( '.message-box-footer' ).find( '.message-box-footer-options' ).slideUp( 'fast', function() {
				$( this ).parents( '.message-box-footer' ).find( '.messages-image-uploader-wrapper' ).show( 'slide', { direction: 'down' }, 300 );
			});

			$( this ).parents( '.message-box-footer' ).find( '.dz-default.dz-message' ).trigger( 'click' );
		});
/*** END IMAGE UPLOAD FORM ***/

/*** WINDOW RESIZE - SHOW/HIDE BOX ***/
		$( window ).on( 'load resize', function() {
			// call 'wpj_chat_display_boxes' function to show only last boxes
			wpj_chat_display_boxes( active_popups, 'resize_window' );
		});
/*** END WINDOW RESIZE - SHOW/HIDE BOX ***/

/*** BOX FOCUS ***/
		$( document ).on( 'click blur', '.message-box-container' , function( e ) {

			var selection = window.getSelection();

			if ( selection.toString().length === 0 ) {

				if ( e.type == 'click' ) {

					if ( ! $( this ).find( '.message-box-wrapper' ).hasClass( 'has-focus' ) ) {

						// hide placeholder
						$( this ).find( '.message-box-placeholder-container' ).hide();

						// add class for focus
						$( this ).find( '.message-box-wrapper' ).addClass( 'has-focus' );

						// set focus on the current box
						$( this ).find( '.message-box-input-content' ).focus();

						// remove unread class
						$( this ).find( '.message-box-wrapper' ).removeClass( 'unread' );

					}

				} else if ( e.type == 'focusout' ) {

					// remove focus class
					$( this ).find( '.message-box-wrapper' ).removeClass( 'has-focus' );

				}

			} else {

				// text selecting

			}

		});
/*** END BOX FOCUS ***/

/*** SEARCH FORM MINIMAL ***/
		$( document ).on( "click", ".chat-sidebar-user-search-icon", function( e ) {
			if ( $( this ).siblings( '.chat-sidebar-user-search-input' ).is( ':hidden' ) ) {
				$( this ).removeClass( 'search' ).addClass( 'times' );
				$( this ).siblings( '.chat-sidebar-user-search-input' ).show( 'slide', { direction: 'right' }, 300 );

			} else {
				$( this ).removeClass( 'times' ).addClass( 'search' );
				$( this ).siblings( '.chat-sidebar-user-search-input' ).hide( 'slide', { direction: 'right' }, 300 );

			}
		});
/*** END SEARCH FORM MINIMAL ***/

	}

});

/*** FUNCTIONS ***/
function wpj_chat_calculate_popup_no() {
	// get window width
	var width = window.innerWidth;

	if ( width < 540 ) { // hide boxes if windows width < 540
		total_popups = 0;
	} else { // calculate the number of boxes we can insert
		width = width - 200;
		total_popups = parseInt( width / 300 );
	}

	// return the number of boxes that fit in the screen
	return total_popups;
}

function wpj_chat_display_boxes( active_popups, action ) {
	// the number of boxes that fit in the screen
	var total_popups = wpj_chat_calculate_popup_no();

	// first right to be opened after sidebar
	var sidebar_width             = parseInt( jQuery( '.chat-sidebar-container' ).outerWidth() );
	var sidebar_margin_width      = parseInt( jQuery( '.chat-sidebar-container' ).css( ( wpj_vars.is_rtl ? 'left' : 'right' ) ) );
	var space_between_sidebar_box = 15;

	var right = sidebar_width + sidebar_margin_width + space_between_sidebar_box;
	if ( ! right ) {
		right = jQuery( '.is-sidebar-minimalist' )[0] ? 65 : 220;
	}

	// get only the last total_popups elements from array,
	var screen_popups = active_popups.slice( - total_popups );

	for ( var i = 0; i < total_popups; i++ ) {
		if ( screen_popups[i] != undefined ) {

			// calculate the right for next element
			var new_right = jQuery( '[rel="' + screen_popups[i] + '"]' ).prev( '.message-box-container' ).find( '.message-box-wrapper' ).width();
			if ( new_right && i > 0 ) { right += ( new_right + space_between_sidebar_box ); }

			// set right css value
			jQuery( '[rel="' + screen_popups[i] + '"]' ).find( '.message-box-wrapper' ).css( ( wpj_vars.is_rtl ? 'left' : 'right' ), right );

			// show the box
			jQuery( '[rel="' + screen_popups[i] + '"]' ).show();

			// set focus on the new box
			jQuery( '[rel="' + screen_popups[i] + '"]' ).find( '.message-box-input-content' ).focus();

		}
	}

	if ( active_popups.length > total_popups ) {
		// get hidden boxes
		var hidden_popups = active_popups.slice( 0, - total_popups );

		// hide the rest of the boxes
		for ( var j = 0; j < hidden_popups.length; j++ ) {
			jQuery( '[rel="' + hidden_popups[j] + '"]' ).hide();
		}
	}
}

function wpj_chat_change_boxes_margin( this_elem, operation, value ) {
	this_elem.parents( '.message-box-container' ).nextAll( '.message-box-container' ).each( function() {
		// box id
		var box_id = jQuery( this ).attr( "rel" );

		// get right value of current box id
		var old_right = jQuery( '[rel="' + box_id + '"]' ).find( '.message-box-wrapper' ).css( ( wpj_vars.is_rtl ? 'left' : 'right' ) ).replace( /[^-\d\.]/g, '' );

		// calculate and chagne right value
		var new_right = operation == 'extend' ? parseInt( old_right ) + parseInt( value ) : parseInt( old_right ) - parseInt( value );

		// apply new right value to current box id
		jQuery( '[rel="' + box_id + '"]' ).find( '.message-box-wrapper' ).css( ( wpj_vars.is_rtl ? 'left' : 'right' ), new_right );
	});
}

function wpj_chat_open_box( box_id, e ) {
	if (
		wpj_vars.chat_enabled == 1
		&& ! isMobile()
		&& wpj_vars.is_user_logged_in
		&& jQuery( window ).width() >= 768
		&& ! jQuery( '.is-page-without-chat' )[0]
		&& jQuery( '.chat-sidebar-user-box[data-box-id="' + box_id + '"]' )[0]
	) {
		// Hide preview window
		jQuery( '.messages-icon-dropdown' ).hide();

		// Hide count box
		jQuery( '.messages-icon' ).find( '.unread-label' ).hide();

		// Open message box
		jQuery( '.chat-sidebar-user-box[data-box-id="' + box_id + '"]' ).trigger( 'click' );

		return false;

	}

	return true;
}

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

	jQuery( ".chat-sidebar-users-list > .chat-sidebar-user-box" ).each( function() {
		if ( jQuery( this ).find( '.user-name' ).text().toLowerCase().search( value ) > -1 )
			jQuery( this ).show();
		else
			jQuery( this ).hide();
	});

	// show/hide "No user found" message
	if ( jQuery( ".chat-sidebar-users-list > .chat-sidebar-user-box" ).children( ':visible' ).length == 0 )
		jQuery( '.chat-sidebar-notifications' ).show();
	else
		jQuery( '.chat-sidebar-notifications' ).hide();

	if ( typeof jQuery.fn.wpjLazyLoadRender == 'function' ) jQuery.fn.wpjLazyLoadRender();
}

function wpj_chat_get_stored_active_boxes( item_name ) {
	if ( localStorage.getItem( item_name ) ) {

		// return stored active boxes
		return JSON.parse( localStorage.getItem( item_name ) );
	}

	return false;
}

function wpj_chat_store_active_boxes( popups, status ) {
	if ( status == 'minimized' || status == 'removed' ) {

		current_items = wpj_chat_get_stored_active_boxes( 'minimized_popups' );

		// remove the new box from minimized popups if exist
		if ( current_items ) {
			if ( jQuery.inArray( popups, current_items ) != -1 ) {
				current_items.splice( jQuery.inArray( popups, current_items ), 1 );
			}
		} else {
			current_items = [];
		}

		// add the new box to minimized popups
		if ( status == 'minimized' ) {
			current_items.push( popups );
		}

		// store minimized boxed
		localStorage.setItem( 'minimized_popups', JSON.stringify( current_items ) );

	} else {
		// remove old boxes
		localStorage.removeItem( 'active_popups' );

		// add the new boxes
		localStorage.setItem( 'active_popups', JSON.stringify( popups ) );
	}
}

function wpj_chat_set_box_status_cookie( element ) {
	if ( element.is( ':hidden' ) ) {
		jQuery.cookie( 'sidebar', 'maximized', { expires: 7, path: '/' } );
		return 'maximized';

	} else {
		jQuery.cookie( 'sidebar', 'minimized', { expires: 7, path: '/' } );
		return 'minimized';

	}
}

function wpj_chat_animate_element( action ) {
	var is_rtl = typeof wpj_vars !== 'undefined' && wpj_vars.is_rtl ? true : false;

	if ( ! jQuery( '.is-sidebar-minimalist' )[0] ) {

		if ( action == 'show' ) {

			if ( is_rtl == true ) {
				jQuery( '.chat-sidebar-anchor-icon' ).animate({ 'left' : '206px' }, 300 );
				jQuery( '#main-wrapper' ).animate( { 'padding-left' : '200px' }, 300 );

			} else {
				jQuery( '.chat-sidebar-anchor-icon' ).animate({ 'right' : '206px' }, 300 );
				jQuery( '#main-wrapper' ).animate( { 'padding-right' : '200px' }, 300 );

			}

		} else if ( action == 'hide' ) {

			if ( is_rtl == true ) {
				jQuery( '.chat-sidebar-anchor-icon' ).animate({ 'left' : '0' }, 300 );
				jQuery( '#main-wrapper' ).animate( { 'padding-left' : '0' }, 300 );

			} else {
				jQuery( '.chat-sidebar-anchor-icon' ).animate({ 'right' : '0' }, 300 );
				jQuery( '#main-wrapper' ).animate( { 'padding-right' : '0' }, 300 );

			}

		}

	}
}

function wpj_chat_set_sidebar_height() {
	if ( jQuery( '#wpadminbar' )[0] && jQuery( '.chat-sidebar-users-list' )[0] )
		jQuery( '.chat-sidebar-users-list' ).css( 'height', 'calc(100% - 30px)' );

	if ( jQuery( '.is-page-without-chat' )[0] )
		jQuery( '#main-wrapper' ).removeAttr( 'style' );
}

function wpj_chat_open_boxes_on_load() {
	if ( ! jQuery( '.is-page-without-chat' )[0] ) {
		var stored_popups = wpj_chat_get_stored_active_boxes( 'active_popups' );
		if ( stored_popups ) {
			stored_popups.forEach( function( box_id ) {
				// trigger click to open the boxes
				jQuery( '.chat-sidebar-user-box[data-box-id="' + box_id + '"]' ).trigger( 'click' );
			});
		}
	}
}

function wpj_init_chat_tooltips() {
	if ( jQuery( '.option-wrapper' )[0] )
		jQuery( '.option-wrapper' ).popup({ position: 'top center', on: 'hover', variation: 'inverted' });
}

function wpj_chat_hide_sidebar_responsive() {
	// pusher full width if width < 1258
	if ( ! jQuery( '.is-sidebar-minimalist' )[0] ) {

		if ( jQuery( this ).width() < 1258 ) jQuery( '#main-wrapper' ).css( 'padding-' + ( wpj_vars.is_rtl ? 'left' : 'right' ), '0' );
		else jQuery( '#main-wrapper' ).removeAttr( 'style' );

	}
}

function wpj_chat_hide_sidebar_elements_minimalist() {
	if ( jQuery( '.is-sidebar-minimalist' )[0] ) {
		jQuery( '.chat-sidebar-user-box' ).each( function() {
			if ( ! jQuery( this ).isOnScreen() ) {
				jQuery( this ).hide();

				if ( jQuery( '#wpadminbar' )[0] )
					jQuery( this ).prev().hide();
			}
		});
	}
}

function wpj_chat_insert_message_to_box( box_id, message, images ) {
	// get date now
	var date = new Date();

	// get am/pm
	var ampm = date.getHours() >= 12 ? wpj_vars.pm : wpj_vars.am;

	// filter the message
	if ( ! message.includes( 'pwd=' + box_id + wpj_vars.uid ) ) {
		message = wpj_filter_message( message );
	}

	// insert the attachments to the box
	var attachments = '';
	var attachments_post = jQuery( 'input[name="hidden_files_chat_attachments_' + box_id + '"]' ).val();

	if ( attachments_post ) {
		var pm_files_array = attachments_post.split( "," );

		if ( pm_files_array ) {
			attachments = '<div class="attachments-wrapper">';

				for ( var i = 0; i < pm_files_array.length; i++ ) {
					attachments = attachments + '\
						<div class="attachment-item-wrapper file-wrapper" id="' + pm_files_array[i] + '">\
							<div class="attachment-item-content">\
								<a class="attachment-item-link" target="_blank" href="' + wpj_vars.site_URL + '/?secure_download=' + pm_files_array[i] + '" download="">' + jQuery( '.uploadifive-queue-item[data-id=' + pm_files_array[i] + ']' ).find( '.filename' ).text() + '</a>\
							</div>\
						</div>\
					';
				}

			attachments = attachments + '</div>';
		}
	}

	// insert the attachments to the box
	var image_attachments = '';

	if ( images ) {

		var pm_images_array = images.split( "," );

		if ( pm_images_array ) {
			image_attachments = '<div class="attachments-wrapper">';

				for ( var i = 0; i < pm_images_array.length; i++ ) {
					image_attachments = image_attachments + '\
						<a href="' + jQuery( '[rel="' + box_id + '"]' ).find( '.dz-success.dz-complete[data-id="' + pm_images_array[i] + '"]' ).attr( 'data-url' ) + '" class="js-pm-image-attachments-gallery">\
							<img src="' + jQuery( '[rel="' + box_id + '"]' ).find( '.dz-success.dz-complete[data-id="' + pm_images_array[i] + '"]' ).attr( 'data-url-thumb' ) + '">\
						</a>\
					';
				}

			image_attachments = image_attachments + '</div>';
		}
	}

	// insert the message to the box
	var content = jQuery( '\
		<div class="multiple-messages-wrapper">\
			<div class="message-wrapper ' + ( ! message && ! attachments ? 'only-images' : '' ) + ' sent">\
				<div class="message-text-content" data-inverted="" data-tooltip="' + date.getHours() + ':' + date.getMinutes() + ' ' + ampm.toLowerCase() + '" data-position="top right">\
					<div class="message-send">' + linkify( message ) + attachments + image_attachments + '</div>\
				</div>\
			</div>\
		</div>\
	' );

	jQuery( '[rel="' + box_id + '"]' ).find( '.message-box-content' ).find( '.pm-list' ).find( '.row' ).append( content );
}
/*** END FUNCTIONS ***/

/*** HOOKS ***/
Hooks.add_action( 'wpj_after_custom_offer_saved', wpj_chat_insert_custom_offer_to_box, 2 );
function wpj_chat_insert_custom_offer_to_box( data, action ) {
	// push custom offer to chat message box
	if ( data.custom_offer ) {

		// clear 'no message' pusher div
		jQuery( '[rel="' + data.user + '"]' ).find( '.no-results' ).text( '' );

		var content = jQuery( '\
			<div class="multiple-messages-wrapper">\
				<div class="message-wrapper sent" data-pm-id="' + data.pm_id + '">\
					<div class="message-text-content custom-offer" data-inverted="" data-tooltip="' + data.message_date + '" data-position="top right">\
						<div class="message-send">\
							<div class="message-custom-offer">\
								<div class="message-custom-offer-icon">\
									<img src="' + wpj_vars.theme_path + '/assets/images/misc/custom-offer.svg" alt="Custom Offer" class="icon" width="30" height="30">\
								</div>' + data.custom_offer + '\
							</div>\
						</div>\
					</div>\
				</div>\
			</div>\
		' );
		jQuery( '[rel="' + data.user + '"]' ).find( '.message-box-content' ).find( '.pm-list' ).find( '.row' ).append( content );

		// hide chat options
		if ( jQuery( '[rel="' + data.user + '"]' ).find( '.message-box-footer-options' ).is( ':visible' ) )
			jQuery( '[rel="' + data.user + '"]' ).find( '.js-message-options-btn' ).trigger( 'click' );
	}
}
/*** END HOOKS ***/