// declare initLiveNotifications timeout handle in global scope
// in order to clear it when the function is called repeatedly
// and prevent flooding
var ilnTimeoutHandle;

function initLiveNotifications( previous ) {
	clearTimeout( ilnTimeoutHandle );

	var previous = typeof previous !== 'undefined' ? previous : [];
	jQuery.ajax({
		type: "POST",
		url : wpj_vars.ligh_ajax_enabled == 0 ? wpj_vars.ajaxurl : wpj_vars.light_ajax_url,
		data: {
			action: 'check_live_site_changes_action',
			uid: wpj_vars.uid
		},
		success: function( data ) {
			// Add messages & notifications number
			addNotify( "new", data.notifications, "notifications-icon" );
			addNotify( "new", data.messages, "messages-icon" );
			window.parent.postMessage( {data: data}, "*" );

			// Add messages
			if ( isNumeric( data.messages ) && data.messages > 0 && data.notification_info ) {
				var notification_info = JSON.parse( data.notification_info );

				// messages & custom offers
				if (
					notification_info.notify_type == 'new_message'
					|| notification_info.notify_type == 'custom_offer_paid_new'
					|| notification_info.notify_type == 'decline_custom_offer'
					|| notification_info.notify_type == 'widthdraw_custom_offer'
				) {
					if ( jQuery( '.page-id-' + wpj_vars.proposal_page_id )[0] ) { // proposal page
						if ( jQuery( '.user-proposals-wrapper' )[0] ) refreshContent( '.user-proposals-wrapper' ); // for code
						else wpj_refresh_kadence_tab_content(); // for page builder
					}

					if ( jQuery( '.is-page-pm' )[0] ) // pm page
						refreshContent( '.thread-list-wrapper' );

					if ( jQuery( '.is-page-pm.is-page-pm-single' )[0] && jQuery( '[data-interlocutor-id="' + notification_info.user2 + '"]' )[0] ) // pm user page
						refreshContent( '.js-messages-list .kt-inside-inner-col:first' );

					if ( wpj_vars.chat_enabled && ! jQuery( '.is-page-pm' )[0] )
						addMessage( notification_info ); // chat

				}
			}

			// Add notifications
			if ( isNumeric( data.notifications ) && data.notifications > 0 && data.notification_info ) {
				var notification_info = JSON.parse( data.notification_info );

				if (
					notification_info.notify_type
					&& notification_info.notify_type != 'new_message'
					&& notification_info.notify_type != 'custom_offer_paid_new'
					&& notification_info.notify_type != 'decline_custom_offer'
					&& notification_info.notify_type != 'widthdraw_custom_offer'
				) {
					if ( jQuery( '.js-notifications-list' )[0] )
						refreshContent( '.js-notifications-list' ); // all notifications page

					if ( jQuery( '.page-id-' + wpj_vars.order_page_id )[0] && jQuery( '[data-order-id="' + notification_info.order_id + '"]' )[0] ) { // order page
						refreshContent( '.order-header-action-buttons-wrapper' ); // header buttons
						refreshContent( '#order-notification-messages-wrapper' ); // order notifications
						refreshContent( '.order-message-form-buttons' ); // bottom buttons

						if ( notification_info.notify_type == 'order_accepted'
							|| notification_info.notify_type == 'order_delivered'
							|| notification_info.notify_type == 'order_complete'
							|| notification_info.notify_type == 'extend_delivery_accept'
						) {
							refreshContent( '.order-timer-wrapper' ); // show/hide timer

							if ( notification_info.notify_type == 'order_accepted' ) {
								refreshContent( '#' + jQuery( '.order-buyer-instructions-row-wrapper' ).siblings( '.wp-block-kadence-rowlayout' ).children( '.kt-row-layout-inner' ).attr( 'id' ) ); // show instant delivery files
							}

							if ( notification_info.notify_type == 'order_delivered' || notification_info.notify_type == 'order_complete' ) {
								refreshContent( '#order-message-form-wrapper' ); // hide message form
								refreshContent( '#order-feedback-form-wrapper' ); // show review form
							}

						}

						if ( notification_info.notify_type == 'custom_extra_paid_new' ) {
							refreshContent( '.order-custom-extras-row-wrapper' ); // update paid custom extras
							refreshContent( '.order-processing-fees-row-wrapper' ); // update processing fees
							refreshContent( '.order-tax-row-wrapper' ); // update tax
							refreshContent( '.order-total-price-row-wrapper' ); // update total price
						}

						if ( notification_info.notify_type == 'tips_paid_new' ) {
							refreshContent( '.order-tips-row-wrapper' ); // update paid tips
							refreshContent( '.order-processing-fees-row-wrapper' ); // update processing fees
							refreshContent( '.order-tax-row-wrapper' ); // update tax
							refreshContent( '.order-total-price-row-wrapper' ); // update total price
						}

						if ( notification_info.notify_type == 'order_rejected' || notification_info.notify_type == 'mutual_cancellation_answer' ) {
							refreshContent( '.order-timer-wrapper' ); // show/hide timer
							refreshContent( '.js-cancelled-order-wrapper' ); // update cancelled box
							refreshContent( '.js-order-notices-wrapper' ); // show cancelled box
							refreshContent( '#order-message-form-wrapper' ); // hide message form
						}

						if ( notification_info.notify_type == 'new_feedback' ) {
							refreshContent( '#order-message-form-wrapper' ); // hide message form
							refreshContent( '#order-feedback-form-wrapper' ); // show review form
						}

					}
				}
			}

			if ( data.enabled == '1' ) {

				// check previous request
				var timeout = data.timeout;
				if ( previous.timeout > data.timeout ) {
					if ( previous.timeout <= data.max_timeout )
						timeout = previous.timeout;
					else
						timeout = data.max_timeout;
				}

				// add delay or reset for the next one
				if ( data.notifications == previous.notifications
					&& data.messages == previous.messages )
					data.timeout += timeout;
				else
					timeout = data.timeout;

				clearTimeout( ilnTimeoutHandle );
				ilnTimeoutHandle = setTimeout(
					function() {
						initLiveNotifications( data );
					},
					timeout
				);
			}
		},
		error: function( XMLHttpRequest, textStatus, errorThrown ) {
			clearTimeout( ilnTimeoutHandle );
			ilnTimeoutHandle = setTimeout(
				function() {
					initLiveNotifications();
				},
				32000
			);
		}
	});
}

function addNotify( type, msgs, cls ) {
	var html = '';

	if ( isNumeric( msgs ) && msgs > 0 ) {
		if ( msgs > 99 ) msgs = 99;
		html = '<div class="unread-label digits"><span class="messages_count">' + msgs + '</span></div>';
	}

	jQuery( "." + cls + " .user-notification-icon-link" ).each( function() {
		jQuery( this ).html( html );
	});

	jQuery( "." + cls + ".label" ).each( function() {
		if ( ( msgs ) > 0 ) jQuery( this ).show();
		else jQuery( this ).hide();

		jQuery( this ).html( msgs );
	});
}

function addMessage( notification_info ) {
	jQuery.ajax({
		type: "POST",
		url: wpj_vars.ajaxurl,
		data: {
			action : 'receive_live_messages_action'
		},
		success: function( data ) {
			var box_id_element = jQuery( '[rel="' + notification_info.user2 + '"]' );

			if ( box_id_element[0] ) {
				// Add class unread
				if ( ! box_id_element.find( '.message-box-wrapper' ).hasClass( 'has-focus' ) )
					box_id_element.find( '.message-box-wrapper' ).addClass( 'unread' );

				// Clear 'no message' pusher div
				if ( box_id_element.find( '.pm-list' ).find( '.no-results' )[0] )
					box_id_element.find( '.pm-list' ).find( '.no-results' ).text( '' );

				// Insert the message to chatbox
				if ( box_id_element.find( '.pm-list' ).find( '.row' )[0] ) {
					if (
						notification_info.notify_type == 'widthdraw_custom_offer'
						|| notification_info.notify_type == 'decline_custom_offer'
						|| notification_info.notify_type == 'custom_offer_paid_new'
					) { // custom offer response
						var pm_id_element = box_id_element.find( '.message-wrapper[data-pm-id="' + notification_info.notify_id + '"]' );

						if ( pm_id_element[0] ) {
							if ( ! pm_id_element.find( '.custom-offer-response' )[0] ) {
								if ( notification_info.notify_type == 'widthdraw_custom_offer' ) var response = wpj_vars.withdrawn;
								if ( notification_info.notify_type == 'decline_custom_offer' ) var response = wpj_vars.declined;
								if ( notification_info.notify_type == 'custom_offer_paid_new' ) var response = wpj_vars.accepted;

								pm_id_element.find( '.message-custom-offer' ).append( '<span class="ui mini right label custom-offer-response ' + notification_info.notify_type + '">' + response + '</span>' );
							}
						}

					} else { // message
						box_id_element.find( '.pm-list' ).find( '.row' ).append( '<div class="multiple-messages-wrapper">' + data + '</div>' );
						wpj_init_attachments_gallery(); // initialize PM gallery

					}
				}

				// Scroll to the last message
				if ( box_id_element.find( '.message-box-content' )[0] )
					box_id_element.find( '.message-box-content' ).scrollTop( box_id_element.find( '.message-box-content' )[0].scrollHeight );

			} else {
				// Open message box
				wpj_chat_open_box( notification_info.user2 );

				// Audio notification
				playSound(
					wpj_vars.theme_path + "/assets/audio/new_message.ogg",
					wpj_vars.theme_path + "/assets/audio/new_message.mp3",
					wpj_vars.theme_path + "/assets/audio/new_message.m4a"
				);

			}
		}
	});
}