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

	// modernizr library
	if ( typeof Modernizr !== 'undefined' ) {
		if ( Modernizr.touch ) $( 'body' ).addClass( 'touch' );
		else $( 'body' ).addClass( 'no-touch' );
	}

	// initialize scripts on page load
	wpj_initialize_theme_scripts();

	// change page without refresh
	if ( wpj_vars.page_transition == 'animation' && typeof Modernizr !== 'undefined' && Modernizr.history ) {

		$( '#page-wrap' ).delegate( 'a', 'click', function( e ) {
			var _link     = $( this ).attr( 'href' );
			var _is_local = new RegExp( location.host );

			if ( /* exclude ajax load for: */
				typeof _link !== 'undefined' // undefined link
				&& _link !== false // empty link
				&& _is_local.test( _link ) // external link

				&& ! $( this ).hasID( '#wp-submit' ) // authentication forms
				&& ! $( this ).hasClass( '.js-authentication-button' ) // custom authentication forms

				&& ! $( this ).hasClass( 'user-notification-icon-link' ) // preview panel buttons
				&& ! $( this ).hasClass( 'attachment-item-link' ) // attachment download link
				&& ! $( this ).hasClass( 'js-pm-image-attachments-gallery' ) // gallery image
				&& ! $( this ).hasClass( 'js-search-users-btn' ) // pm search conversation button
				&& ! $( this ).hasClass( 'js-invoice-link' ) // generate invoice link

				&& ! $( this ).hasClass( 'register_button' ) // register button
				&& ! $( this ).hasClass( 'register-link' ) // register link
				&& ! $( this ).hasClass( 'login_button' ) // login button
				&& ! $( this ).hasClass( 'login-link' ) // login link
				&& ! $( this ).hasClass( 'log-out' ) // logout link
				&& ! $( this ).hasClass( 'forgot_button' ) // forgot password button

				&& ! $( this ).hasClass( 'lostpassword-link' ) // forgot password modal
				&& ! $( this ).hasClass( 'already-registered-handle' ) // login modal
				&& ! $( this ).hasClass( 'not-a-member-handle' ) // register modal

				&& ! $( this ).hasClass( 'owl-prev' ) // carousel navigation prev
				&& ! $( this ).hasClass( 'owl-next' ) // carousel navigation next

				&& ! $( this ).hasClass( 'page-numbers' ) // pagination

				&& ! $( this ).hasClass( 'js-mobile-menu-toggle' ) // mobile menu

				&& ! $( this ).attr( 'data-featherlight' ) // portofolio image

				&& ! $( this ).parents( '#wpadminbar' )[0] // top admin bar

				&& ! $( this ).parents( '.wpj-language-switcher' )[0] // wpj language switcher
				&& ! $( this ).parents( '.trp-language-switcher-container' )[0] // translatepress language switcher
				&& ! $( this ).parents( '.trp_language_switcher_shortcode' )[0] // translateoress shortcode language switcher

				&& $( this ).attr( 'target' ) != '_blank'
			) {
				if ( ! e.ctrlKey && ! e.metaKey ) {
					if (
						wpj_vars.chat_enabled && $( this ).attr( 'onclick' ) && $( this ).attr( 'onclick' ).includes( 'wpj_chat_open_box' )
						|| ( $( this ).hasClass( 'link-to-pm' ) && ( $( e.target ).hasClass( 'icon' ) || $( e.target ).hasClass( 'item' ) ) )
					) {
						/* do not call the function if the click is made on the links in the preview panels and the chat is active (opens the message box)
						or if the click is made on the settings icon in the conversation list on the message page */

					} else {
						if ( $( this ).parents( '.wpj-view-all-cnt' )[0] || $( this ).parents( '.message-box-maximize' )[0] ) // close boxes if is PM page
							jQuery( '.message-box-close' ).trigger( 'click' );

						if ( $( this ).parents( '.wpj-view-all-cnt' )[0] && isMobile() ) // close tooltip if is mobile
							refreshContent( '.header-wrapper.header-mobile .user-notification-icons' );

						if ( $( window ).scrollTop() > 100 ) $( 'html, body' ).animate({ scrollTop : 0 }, 800 ); // scroll to top before change the page
						history.pushState( null, null, _link ); // change the url
						loadContent( _link ); // load the new content of the page
						return false;

					}
				}

			}
		});

		var current_hash = window.location.hash;
		$( window ).bind( 'popstate', function() { /* browser & slider navigation */
			if ( window.location.hash == current_hash || location.hash.includes( 'step' ) ) {
				loadContent( location.pathname.replace( /^.*[\\\/]/, '' ) );
			}

			current_hash = window.location.hash;
		});

	}

});

function loadContent( href, mainWrapper, mainContentClass ) {

	if ( typeof mainWrapper === 'undefined' ) var mainWrapper = '#main-wrapper';
	var mainWrapper = jQuery( mainWrapper );

	if ( typeof mainContentClass === 'undefined' ) var mainContentClass = '#main-content';

	var transition_options = {};

	if ( wpj_vars.page_transition_effect == 'blind' || wpj_vars.page_transition_effect == 'drop' || wpj_vars.page_transition_effect == 'shake' || wpj_vars.page_transition_effect == 'slide' )
		transition_options = { direction: wpj_vars.page_transition_direction };

	else if ( wpj_vars.page_transition_effect == 'highlight' )
		transition_options = { color: wpj_vars.page_transition_colour };

	else if ( wpj_vars.page_transition_effect == 'scale' )
		transition_options = { percent: 50 };

	else if ( wpj_vars.page_transition_effect == 'size' )
		transition_options = { to: { width: 150, height: 150 } };

	mainWrapper.load( href + " " + mainContentClass, function( response, status, xhr ) {
		// refresh header
		if ( ! wpj_vars.is_user_logged_in ) {
			if ( isMobile() ) refreshContent( '.header-wrapper.header-mobile .logo-holder' );
			else refreshContent( '.header-wrapper.header-pc' );
		}

		// get head & body
		const doc = new DOMParser().parseFromString( response, 'text/html' );

		// set title
		document.title = jQuery( response ).filter( 'title' ).text();

		// set body classes
		jQuery( 'body' ).attr( 'class', doc.body.getAttribute( 'class' ) );

		// set pusher classes
		jQuery( '#page-wrap' ).attr( 'class', jQuery( response ).filter( '#page-wrap' ).attr( 'class' ) );

		// set metas
		jQuery( 'meta' ).remove();
		jQuery( response ).filter( 'meta' ).each( function() {
			if ( jQuery( this ).attr( 'name' ) )
				jQuery( '<meta name="' + jQuery( this ).attr( 'name' ) + '" content="' + jQuery( this ).attr( 'content' ) + '">' ).insertAfter( 'title' );

			else
				jQuery( '<meta property="' + jQuery( this ).attr( 'property' ) + '" content="' + jQuery( this ).attr( 'content' ) + '">' ).insertAfter( 'title' );
		});

		// set analytics
		if ( jQuery( '.analytics-wrapper' )[0] && jQuery( response ).find( '.analytics-wrapper' )[0] )
			jQuery( '.analytics-wrapper' ).replaceWith( jQuery( response ).find( '.analytics-wrapper' )[0].outerHTML );

		// set menu
		if ( jQuery( '.categories-menu-list' )[0] && jQuery( response ).find( '.categories-menu-list' )[0] )
			jQuery( '.categories-menu-list' ).replaceWith( jQuery( response ).find( '.categories-menu-list' )[0].outerHTML );

		// set fonts
		jQuery( doc.head ).find( 'link[href*="fonts.googleapis.com/css?family"]' ).each( function() {
			if ( jQuery( 'head link[href="' + jQuery( this ).attr( 'href' ) + '"]' ).length <= 0 )
				jQuery( '<link href="' + jQuery( this ).attr( 'href' ) + '" rel="stylesheet">' ).appendTo( 'head' );
		});

		jQuery( response ).find( '.wp-footer-scripts' ).find( 'link' ).each( function() {
			jQuery( jQuery( this )[0].outerHTML ).appendTo( '.wp-footer-scripts' );
		});

		// set menu bar items
		if ( jQuery( '#wpadminbar' )[0] && jQuery( response ).find( '#wpadminbar' )[0] )
			jQuery( '#wpadminbar' ).replaceWith( jQuery( response ).find( '#wpadminbar' )[0].outerHTML );

		// set localize vars
		if ( jQuery( '#wpj-front-scripts-js-extra' )[0] && jQuery( response ).find( '#wpj-front-scripts-js-extra' )[0] )
			jQuery( '#wpj-front-scripts-js-extra' ).replaceWith( jQuery( response ).find( '#wpj-front-scripts-js-extra' )[0].outerHTML );

		// hide preview panel
		jQuery( '.nh-submenu.preview-dropdown' ).hide();

		// initialize kadence page builder
		if ( jQuery( '.wp-block-kadence-rowlayout' )[0] || jQuery( '.wp-block-kadence-advancedheading' )[0] ) {

			// set head styles - for page builder
			jQuery( doc.head ).find( 'link[href*="kadence-blocks"]' ).not( 'noscript link[href*="kadence-blocks"]' ).each( function() {
				if ( jQuery( 'head link[href="' + jQuery( this ).attr( 'href' ) + '"]' ).length <= 0 ) {
					jQuery( '\
						<link rel="preload" href="' + jQuery( this ).attr( 'href' ) + '" as="style" onload="this.onload=null;this.rel=\'stylesheet\'" />\
						<noscript><link rel="stylesheet" href="' + jQuery( this ).attr( 'href' ) + '"></noscript>\
					' ).appendTo( 'head' );
				}
			});

			// set head inline styles - for page builder - new kadence version
			if ( jQuery( doc.head ).find( 'style[id^="kadence-blocks"]' )[0] ) {
				jQuery( 'head' ).find( 'style[id^="kadence-blocks"]' ).remove();
				jQuery( doc.head ).find( 'style[id^="kadence-blocks"]' ).each( function() {
					jQuery( jQuery( this )[0].outerHTML ).appendTo( 'head' );
				});
			}

			if ( jQuery( doc.head ).find( 'style[id^="kadence_blocks"]' )[0] ) {
				jQuery( 'head' ).find( 'style[id^="kadence_blocks"]' ).remove();
				jQuery( doc.head ).find( 'style[id^="kadence_blocks"]' ).each( function() {
					jQuery( jQuery( this )[0].outerHTML ).appendTo( 'head' );
				});
			}

			if ( jQuery( doc.head ).find( 'style[id^="kt-blocks_"]' )[0] ) {
				jQuery( 'head' ).find( 'style[id^="kt-blocks_"]' ).remove();
				jQuery( doc.head ).find( 'style[id^="kt-blocks_"]' ).each( function() {
					jQuery( jQuery( this )[0].outerHTML ).appendTo( 'head' );
				});
			}

			// set footer scripts - for page builder
			jQuery( '.wp-footer-scripts script[src*="kadence-blocks"]' ).remove();

			jQuery( response ).find( '.wp-footer-scripts' ).find( 'script[src*="kadence-blocks"]' ).each( function() {
				if ( jQuery( this ).attr( 'id' ) != 'kadence-blocks-advancedheading-js' ) {
					jQuery( '<script src="' + jQuery( this ).attr( 'src' ) + '" defer="defer" id="' + jQuery( this ).attr( 'id' ) + '"></script>' ).appendTo( '.wp-footer-scripts' );

				} else if ( jQuery( this ).attr( 'id' ) == 'kadence-blocks-advancedheading-js' && typeof kbAdvHeadingTypedListener === 'undefined' ) {
					jQuery( '<script src="' + jQuery( this ).attr( 'src' ) + '" defer="defer" id="' + jQuery( this ).attr( 'id' ) + '"></script>' ).appendTo( '.wp-footer-scripts' );

				}
			});

			// init user account searches
			if ( jQuery( '.js-user-account-search' )[0] ) {
				if ( jQuery( '.wp-block-kadence-tabs' ).find( '.js-user-account-search' )[0] && ! jQuery( '.page-id-' + wpj_vars.my_payments_page_id )[0] ) {
					jQuery( '.wp-block-kadence-tabs' ).replaceWith( jQuery( response ).find( '.wp-block-kadence-tabs' )[0].outerHTML );

				} else if ( jQuery( '.page-id-' + wpj_vars.my_payments_page_id )[0] ) {
					jQuery( '.js-user-account-search' ).each( function() {
						jQuery( this ).replaceWith( jQuery( response ).find( '.js-user-account-search[data-tab-name="' + jQuery( this ).attr( 'data-tab-name' ) + '"]' )[0].outerHTML );
					});

				} else {
					jQuery( '.js-wpj-table-wrapper' ).replaceWith( jQuery( response ).find( '.js-wpj-table-wrapper' )[0].outerHTML );

				}
			}

		}

		// initialize aiosc plugin
		if ( jQuery( '.aiosc-window' )[0] || jQuery( '.aiosc-ticket-list' )[0] ) {

			// set footer scripts - for aiosc plugin
			jQuery( '.wp-footer-scripts script[src*="di-aiosc"]' ).remove();
			jQuery( response ).find( '.wp-footer-scripts' ).find( 'script[src*="di-aiosc"]' ).each( function() {
				jQuery( '<script src="' + jQuery( this ).attr( 'src' ) + '" defer="defer" id="' + jQuery( this ).attr( 'id' ) + '"></script>' ).appendTo( '.wp-footer-scripts' );
			});

			// set tinymce & uploader scripts - for aiosc plugin
			if ( jQuery( '.aiosc-window' )[0] ) {
				jQuery( response ).find( '.wp-footer-scripts' ).find( 'script' ).each( function() {
					if (
						( ! jQuery( this ).attr( 'src' ) && ! jQuery( this ).attr( 'id' ) )
						|| jQuery( this ).attr( 'id' ) == 'wp-tinymce-root-js'
						|| jQuery( this ).attr( 'id' ) == 'wp-tinymce-js'
						|| jQuery( this ).attr( 'id' ) == 'utils-js'
					) {
						jQuery( jQuery( this )[0].outerHTML ).appendTo( '.wp-footer-scripts' );
					}
				});
			}

			if ( jQuery( '.aiosc-ticket-preview' )[0] ) {
				var aiosc_content = "\
					<script>\
						jQuery( document ).ready( function( $ ) {\
							aioscupload = new aioscUploader({\
								ul            : 'ul.aiosc-uploader-files',\
								inputName     : 'attachments[]',\
								maxFileNameLen: 20,\
								maxFiles      : " + wpj_vars.max_files_per_reply + "\
							});\
							\
							jQuery( '#aiosc-premade-responses' ).appendTo( jQuery(' #wp-aiosc-content-wrap .wp-editor-tools' ) );\
							\
							jQuery( document ).on( 'click', '#aiosc-premade-responses button', function( e ) {\
								e.preventDefault();\
								var sel = jQuery( this ).parent().find( 'select' );\
								if ( sel.val() > 0 ) {\
									aiosc_insert_premade_response( sel, jQuery( this ) );\
								}\
							})\
						});\
					</script>\
				";

				jQuery( aiosc_content ).appendTo( '.wp-footer-scripts' );
			}

		}

		// initialize theme scripts
		wpj_initialize_theme_scripts();

		// show content
		mainWrapper.hide().show( wpj_vars.page_transition_effect, transition_options, 500 );

		// simulate resize to set the correct width for carousel items
		if ( jQuery( response ).find( '.owl-carousel' )[0] ) {
			var event = document.createEvent( 'HTMLEvents' );
			event.initEvent( 'resize', true, false );
			document.dispatchEvent( event );
		}

		// set post new url args
		if ( jQuery( '.page-id-' + wpj_vars.new_job_page_id )[0] && ! getUrlParameter( 'jobid' ) ) {
			history.pushState( null, null, href + '?jobid=' + jQuery( 'input[name="_wp_http_referer"]' ).val().split( '=' ).pop() );

		} else if ( jQuery( '.page-id-' + wpj_vars.new_request_page_id )[0] && ! getUrlParameter( 'requestid' ) ) {
			history.pushState( null, null, href + '?requestid=' + jQuery( 'input[name="_wp_http_referer"]' ).val().split( '=' ).pop() );

		}

		// add loader to tinymce until it loads
		if ( jQuery( '.tinyMCE-textarea-wrapper' )[0] && jQuery( response ).find( '.tinyMCE-textarea-wrapper' )[0] )
			addLoader( jQuery( '.tinyMCE-textarea-wrapper' ).find( '#wp-job_description-wrap' ) );

		jQuery( document ).trigger( '_load_ready' );

		// after page load
		setTimeout( function() {
			wpj_init_after_page_load();
			wpj_init_tinyMCE_textarea( response );
		}, 100 );

	});

}

function changeURL( url ) {
	if ( wpj_vars.page_transition == 'animation' && typeof Modernizr !== 'undefined' && Modernizr.history ) {
		history.pushState( null, null, url ); // change the url
		loadContent( url ); // load the new content of the page

	} else window.location.href = url;
}
