//----------------------------------------
// Initialize theme scripts function
//----------------------------------------
function wpj_initialize_theme_scripts() {
	if ( typeof jQuery.fn.wpjSemanticInit              == 'function' ) jQuery.fn.wpjSemanticInit();
	if ( typeof jQuery.fn.wpjCalendarInit              == 'function' ) jQuery.fn.wpjCalendarInit();
	if ( typeof jQuery.fn.wpjTagsInit                  == 'function' ) jQuery.fn.wpjTagsInit();
	if ( typeof jQuery.fn.pageLoadToolTipInit          == 'function' ) jQuery.fn.pageLoadToolTipInit();
	if ( typeof jQuery.fn.wpjTabsToDropdownInit        == 'function' ) jQuery.fn.wpjTabsToDropdownInit();
	if ( typeof jQuery.fn.wpjPBTabsToDropdownInit      == 'function' ) jQuery.fn.wpjPBTabsToDropdownInit();
	if ( typeof jQuery.fn.wpjToggleArrowInit           == 'function' ) jQuery.fn.wpjToggleArrowInit();
	if ( typeof jQuery.fn.wpjNumberFormatInit          == 'function' ) jQuery.fn.wpjNumberFormatInit();
	if ( typeof jQuery.fn.wpjRangeSliderInit           == 'function' ) jQuery.fn.wpjRangeSliderInit();
	if ( typeof jQuery.fn.wpjNoHrefInit                == 'function' ) jQuery.fn.wpjNoHrefInit();
	if ( typeof jQuery.fn.wpjFlipTimerInit             == 'function' ) jQuery.fn.wpjFlipTimerInit();
	if ( typeof jQuery.fn.wpjAudioFileInit             == 'function' ) jQuery.fn.wpjAudioFileInit();
	if ( typeof jQuery.fn.wpjPhoneNumberInit           == 'function' ) jQuery.fn.wpjPhoneNumberInit();
	if ( typeof jQuery.fn.wpjJobMapDisplayInit         == 'function' ) jQuery.fn.wpjJobMapDisplayInit();
	if ( typeof jQuery.fn.wpjJobMapOverviewDisplayInit == 'function' ) jQuery.fn.wpjJobMapOverviewDisplayInit();
	if ( typeof jQuery.fn.wpjWYSIWYGInit               == 'function' ) jQuery.fn.wpjWYSIWYGInit();
	if ( typeof jQuery.fn.wpjDropzoneUploaderInit      == 'function' ) jQuery.fn.wpjDropzoneUploaderInit();
	if ( typeof jQuery.fn.wpjHTML5UploaderInit         == 'function' ) jQuery.fn.wpjHTML5UploaderInit();
	if ( typeof jQuery.fn.wpjUploadifiveUploaderInit   == 'function' ) jQuery.fn.wpjUploadifiveUploaderInit();

	/* General */
	wpj_set_site_viewport();
	wpj_init_change_triggers();
	wpj_init_inputs_counter();
	wpj_add_margin_bottom_to_legend();

	/* Lazy Load */
	if ( typeof jQuery.fn.wpjLazyLoadImagesInit == 'function' ) jQuery.fn.wpjLazyLoadImagesInit();

	/* Header */
	wpj_change_first_menu_item_alignment();
	wpj_change_main_menu_alignment_by_height();
	wpj_display_header_user_info();

	/* Media */
	wpj_init_attachments_gallery();
	wpj_init_emojis();
	wpj_init_charts();
	wpj_init_carousels();
	wpj_init_work_sample();
	wpj_sort_image_files();

	/* Category */
	wpj_display_fully_visible_subcategoires();

	/* Job */
	wpj_init_post_new_steps();
	wpj_load_job_extras();
	wpj_update_purchase_price();
	wpj_show_sellers_projects_carousel();
	wpj_init_social_share_vertical_panel();

	/* Packages */
	wpj_load_package_custom_fields();

	/* Post New */
	wpj_hide_disabled_post_new_fields();
	wpj_hide_disabled_page_builder_post_new_fields();

	/* User */
	wpj_init_user_profile_tooltips();
	wpj_hide_up_certification_not_expire();
	wpj_add_user_cover_class();

	/* Authentication */
	wpj_change_authentication_page_data();
	wpj_add_password_visibility_icon_to_login_form();

	/* PM */
	wpj_hide_admin_bar_on_pm_page();
	wpj_focus_pm_input();
	wpj_send_message_with_enter();
	wpj_move_conversation_top_by_url();
	wpj_disable_deleted_user_sections();
	wpj_set_pm_page_height();

	/* Messages */
	wpj_display_chat_sidebar();
	wpj_init_send_custom_offer_page_builder_modal();

	/* Notifications */
	if ( wpj_vars.live_notify && wpj_vars.is_user_logged_in ) initLiveNotifications();
	wpj_check_notifications( 'all-email-notify', 'email_notifications' );
	wpj_check_notifications( 'all-sms-notify', 'sms_notifications' );
	if ( jQuery( '.js-resend-sms-code' )[0] ) jQuery( '.js-resend-sms-code' ).trigger( 'click' );

	/* Location */
	if ( wpj_vars.html5_geolocation == 1 ) { wpj_geolocation_autofill(); wpj_geolocation_get(); }
	if ( wpj_vars.locations_api == 'tomtom' ) jQuery.fn.wpjTomTomMapsInit();

	/* Order */
	wpj_init_order_click_actions();
	wpj_scroll_to_last_order_box();

	/* Form */
	wpj_add_form_element();
	wpj_show_contact_or_feature_button();

	/* Load more */
	wpj_display_load_more_button();
	wpj_init_load_more_automatically();
	wpj_init_load_more_messages();

	/* After page load */
	setTimeout( function() { wpj_init_after_page_load(); }, 1000 );
	setTimeout( function() { wpj_init_tinymce_textarea_character_count(); }, 3000 );

	/* Resize & Scroll */
	wpj_init_on_resize();
	wpj_init_on_scroll();

	Hooks.do_action( 'wpj_after_page_load_without_refresh' );
}

function wpj_init_after_page_load() {
	wpj_init_tinymce_textarea_character_count();
	wpj_display_video_poster();
	wpj_change_kadence_active_tab(); // for page builder
	wpj_init_quick_responses();
	
	if ( wpj_vars.locations_api_key && wpj_vars.locations_api == 'google' && typeof google !== 'undefined' ) {
		jQuery.fn.wpjGoogleMapsInit();
	}
}

( function ( $ ) {

	//------------------------------------------
	// Initialize Semantic UI fields
	//------------------------------------------
	$.fn.wpjSemanticInit = function() {
		// Remove authentication & user profile modals
		if ( jQuery( '.page-id-' + wpj_vars.user_profile_page_id )[0] || ! wpj_vars.is_user_logged_in ) {
			if ( $( '.ui.dimmer.modals' )[0] ) {
				$( '.ui.dimmer.modals' ).find( '.ui.modal' ).each( function() {
					if ( $( this ).attr( 'class' ).length > 1 ) {
						$( this.remove() );
					}
				});
			}
		}

		// Progress
		if ( $( '.ui.progress' )[0] )
			$( '.ui.progress' ).progress();

		// Dropdown
		if ( $( '.ui.dropdown' )[0] )
			$( '.ui.dropdown' ).dropdown( { message: { noResults: wpj_vars.nothing_found } } );

		if ( $( '.ui.dropdown.full-text-search' )[0] )
			$( '.ui.dropdown.full-text-search' ).dropdown( { fullTextSearch: true, message: { noResults: wpj_vars.nothing_found } } );

		window.onload = function() {
			if ( $( '.ui.dropdown.upward' )[0] ) {
				$( '.ui.dropdown.upward' ).each( function() {
					$( this ).dropdown({ direction: 'upward', fullTextSearch: true, message: { noResults: wpj_vars.nothing_found } });
				});
			}
		}

		if ( $( '.ui.dropdown.clearable' )[0] ) {
			$( '.ui.dropdown.clearable' ).each( function() {
				if ( $( this ).dropdown( 'get value' ) ) {
					$( this ).find( '.dropdown.icon' ).removeClass( 'dropdown' ).addClass( 'x' ).addClass( 'clear-dropdown' );
				} else {
					$( this ).removeClass( 'clear-dropdown' ).removeClass( 'x' ).addClass( 'dropdown' );
				}

				$( this ).on( 'change', function() {
					$( this ).find( '.dropdown.icon' ).removeClass( 'dropdown' ).addClass( 'x' ).addClass( 'clear-dropdown' );
				});

				$( document ).on( 'click', '.clear-dropdown', function() {
					$( this ).parents( '.clearable' ).dropdown( 'clear' );
					$( this ).removeClass( 'clear-dropdown' ).removeClass( 'x' ).addClass( 'dropdown' );
				});
			});
		}

		// Input
		if ( $( '.ui.input.clearable' )[0] ) {
			$( '.ui.input.clearable' ).each( function() {
				var $clearable = $( this );
				$clearable.addClass( 'icon' );
				$clearable.prepend( '<i class="icon clear link hidden"></i>' );

				var $input = $clearable.find( 'input' );
				var $icon  = $clearable.find( 'i.clear.icon' );

				if ( $input.val() ) $icon.removeClass( 'hidden' );
				else $icon.addClass( 'hidden' );

				$input.on( 'change paste keyup', function() {
					if ( $input.val() ) $icon.removeClass( 'hidden' );
					else $icon.addClass( 'hidden' );
				});

				$icon.click( function( e ) {
					$input.val( '' );
					$icon.addClass( 'hidden' );
					e.stopPropagation();
				});
			});
		}

		// Tab
		if ( $( '.ui.menu' ).find( '.item' )[0] )
			$( '.ui.menu .item' ).tab();

		// Accordion
		if ( $( '.ui.accordion' )[0] )
			$( '.ui.accordion' ).accordion();

		// Checkbox
		if ( $( '.ui.checkbox' )[0] )
			$( '.ui.checkbox' ).checkbox();

		// Sticky
		if ( $( '.ui.sticky' )[0] )
			$( '.ui.sticky' ).sticky();

		// Tooltip
		$.fn.wpjTooltipInit();
	}

	//------------------------------------------
	// Initialize calendar fields
	//------------------------------------------
	$.fn.wpjCalendarInit = function() {
		if ( $( '.js-calendar' )[0] ) {
			jQuery( '.js-calendar' ).each( function() {
				var $this = $( this );

				var datetype_attr   = $( this ).attr( 'data-datetype' );
				var datepage_attr   = $( this ).attr( 'data-page' );
				var timeformat_attr = $( this ).attr( 'data-timeformat' );

				if ( typeof datetype_attr !== typeof undefined && datetype_attr !== false ) wpj_init_calendar_input( $this, datepage_attr, datetype_attr, timeformat_attr );
				else wpj_init_calendar_input( $this );
			});
		}
	}

	//------------------------------------------
	// Initialize tag fields
	//------------------------------------------
	$.fn.wpjTagsInit = function() {
		if ( $( '.js-tags' )[0] ) {
			jQuery( '.js-tags' ).each( function() {
				$( this ).tagsInput({
					'defaultText':'',
					'height': 'auto',
					'width' : '100%'
				});
			});
		}
	}

	//------------------------------------------
	// Initialize location autocomplete fields
	//------------------------------------------
	$.fn.wpjGoogleMapsInit = function() { // Google Places API
		if ( wpj_vars.locations_api_key && typeof google !== 'undefined' ) {
			if ( jQuery( '.js-location-autocomplete' )[0] ) {
				jQuery( '.js-location-autocomplete' ).each( function() {
					var location_input = jQuery( this );
					if ( ! location_input.is( 'input' ) ) {
						location_input = location_input.find( 'input' );
					}

					var maps_return = wpj_vars.locations_types[0] ? wpj_vars.locations_types[0] : '(cities)';

					var options = {
						componentRestrictions: {country: wpj_vars.locations_country},
						types: [maps_return],
						language: [wpj_vars.language_code]
					}

					if ( wpj_vars.location_fields ) {
						options['fields'] = JSON.parse( wpj_vars.location_fields );
					}

					var autocomplete = new google.maps.places.Autocomplete( location_input[0], options );

					google.maps.event.addListener( autocomplete, 'place_changed', function() {
						var place = autocomplete.getPlace();
						if ( place.geometry ) {
							location_input.next( 'input' ).val( place.geometry.location.lat() );
							location_input.next( 'input' ).next( 'input' ).val( place.geometry.location.lng() );
						}
					});
				});
			}
		}
	}

	$.fn.wpjTomTomMapsInit = function() { // TomTom Search API
		if ( jQuery( '.js-location-autocomplete' )[0] ) {
			jQuery( '.js-location-autocomplete' ).each( function() {
				var this_ui_input     = jQuery( this );
				var locations_country = wpj_vars.locations_country ? encodeURI( wpj_vars.locations_country.join() ) : '';

				this_ui_input.search({
					apiSettings: {
						onResponse: function(tomtomResponse) {
							var response = { results: [] };
							// translate TomTom API response to work with search
							$.each(tomtomResponse.results, function(index, item) {
								response.results.push({
									title : item.address.freeformAddress,
									lat   : item.position.lat,
									lng   : item.position.lon
								})
							});
							return response;
						},
						url: 'https://api.tomtom.com/search/2/search/{query}.json?countrySet=' + locations_country + '&key=' + wpj_vars.tomtom_api_key
					},
					fields: {
						results : 'results',
						title   : 'title',
						description: false,
						url     : false
					},
					minCharacters : 2,
					showNoResults: false,
					onSelect: function(result, response) {
						jQuery( this_ui_input.find( 'input' )[1] ).val( result.lat );
						jQuery( this_ui_input.find( 'input' )[2] ).val( result.lng );
					}
				});
			});
		}
	}

	//------------------------------------------
	// Initialize job presentation map
	//------------------------------------------
	$.fn.wpjJobMapDisplayInit = function() { // Fill the map div with the url address
		if ( $( "#job_map" )[0] ) {
			$( "#job_map" ).each( function() {
				if ( $( this ).attr( 'data-address' )[0] ) {
					var src   = 'https://maps.google.com/maps?&amp;q=' + encodeURIComponent( $( this ).attr( 'data-address' ) ) + '&amp;output=embed';
					var embed = '<iframe class="job_google_map" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="' + src + '"></iframe>';

					$( '#job_map' ).html( embed );
				}
			});
		}
	}

	//------------------------------------------
	// Initialize jobs map overview
	//------------------------------------------
	$.fn.wpjJobMapOverviewDisplayInit = function() {
		if ( wpj_vars.locations_api_key && typeof google !== 'undefined' ) {
			if ( $( '#job_map_overview' )[0] ) {
				var element = $( '#job_map_overview' );

				var locations = JSON.parse( element.attr( 'data-locations' ) );

				window.map = new google.maps.Map( document.getElementById( 'job_map_overview' ), {
					mapTypeId: google.maps.MapTypeId.ROADMAP
				});

				var infowindow = new google.maps.InfoWindow();

				var bounds = new google.maps.LatLngBounds();

				for ( i = 0; i < locations.length; i++ ) {
					marker = new google.maps.Marker({
						position: new google.maps.LatLng( locations[i]['latitude'], locations[i]['longitude'] ),
						map: map
					});

					bounds.extend( marker.position );

					google.maps.event.addListener( marker, 'click', ( function ( marker, i ) {
						return function () {
							var content = '';

							content += '<div>';

								if ( element.attr( 'data-show-title' ) == 1 ) {
									content += '<h4><a target="_blank" href="' + locations[i]['url'] + '">' + locations[i]['title'] + '</a></h4>';
								}

								if ( element.attr( 'data-show-excerpt' ) == 1 ) {
									content += '<p>' + locations[i]['excerpt'] + '</p>';
								}

								if ( element.attr( 'data-show-description' ) == 1 ) {
									content += '<p>' + locations[i]['description'] + '</p>';
								}

								if ( element.attr( 'data-show-price' ) == 1 ) {
									content += '<p>' + locations[i]['price'] + '</p>';
								}

								if ( element.attr( 'data-show-location' ) == 1 ) {
									content += '<p>' + locations[i]['location'] + '</p>';
								}

								if ( element.attr( 'data-show-author' ) == 1 ) {
									content += '<p><b><a target="_blank" href="' + locations[i]['author_url'] + '">' + locations[i]['author_name'] + '</a></b></p>';
								}

							content += '</div>';

							infowindow.setContent( content );
							infowindow.open( map, marker );
						}
					} ) ( marker, i ) );
				}

				map.fitBounds( bounds );

				var listener = google.maps.event.addListener( map, 'idle', function () {
					map.setZoom( 5 );
					google.maps.event.removeListener( listener );
				});
			}
		}
	}

	//------------------------------------------
	// Initialize reCAPTCHA Responsive
	//------------------------------------------
	$.fn.wpjResizeReCaptchaInit = function() {
		if ( $( '.g-recaptcha-class' )[0] ) {
			var width;
			$( '.g-recaptcha-class' ).each( function() {
				if ( ! width ) {
					width = $( this ).parent().width();
				}
				if ( width ) {
					var scale = width / 302;
					$( this ).css( 'transform', 'scale(' + scale + ')' );
					$( this ).css( '-webkit-transform', 'scale(' + scale + ')' );

					if ( wpj_vars.is_rtl ) {
						$( this ).css( 'transform-origin', '100% 0' );
						$( this ).css( '-webkit-transform-origin', '100% 0' );

					} else {
						$( this ).css( 'transform-origin', '0 0' );
						$( this ).css( '-webkit-transform-origin', '0 0' );

					}
				}
			});
		}
	}

	//------------------------------------------
	// Initialize tooltip fields
	//------------------------------------------
	$.fn.wpjTooltipInit = function() {
		if ( $( '.js-tooltip-handler' )[0] ) {
			if (
				(
					$( '.page-id-' + wpj_vars.new_job_page_id )[0]
						&& ( ( isMobile() && wpj_vars.op_enable_job_instructions_responsive == 1 ) || ! isMobile() )
				)
				||
				(
					$( '.page-id-' + wpj_vars.new_request_page_id )[0]
						&& ( ( isMobile() && wpj_vars.op_enable_request_instructions_responsive == 1 ) || ! isMobile() )
				)
			) {
				$( '.js-tooltip-handler' ).each( function() {
					var handler_id     = $( this ).attr( 'data-handler-id' );
					var this_handler   = $( this );
					var other_handlers = $( '.js-tooltip-handler:not([data-handler-id="' + handler_id + '"])' );
					var ui_popup       = $( '[data-tooltip-id="' + handler_id + '"]' );

					if ( ui_popup.text().length > 0 ) {
						this_handler.popup({
							target      : this_handler,
							on          : isMobile() ? 'click' : 'manual',
							popup       : ui_popup,
							position    : 'right center',
							lastResort  : 'right center',
							transition  : 'fade down',
							distanceAway: 0,
							offset      : 0,
							hoverable   : false, // creates issues
							exclusive   : false, // creates issues
							inline      : true,
							preserve    : true,
						});

						if ( ! isMobile() ) {
							this_handler.hover( function() {
								other_handlers.popup( 'hide' );
								this_handler.popup( 'show' );
							});
						}

					} else {
						this_handler.removeClass( 'js-tooltip-handler' );
						ui_popup.removeClass( 'ui popup' );
						ui_popup.hide();

					}
				});
			}
		}
	}

	//------------------------------------------
	// Run only on post new job & request
	//------------------------------------------
	$.fn.pageLoadToolTipInit = function() {
		if ( $( '.post-new-wrapper' )[0] ) {
			var data_handler_id = $( '.post-new-wrapper' ).find( '.js-tooltip-handler:first' ).attr( 'data-handler-id' );

			if ( data_handler_id && data_handler_id.indexOf( 'cfield' ) === -1 && $( window ).width() > 1024 )
				$( '[data-handler-id="' + data_handler_id + '"]' ).mouseenter().mouseleave();
		}
	}

	//------------------------------------------
	// Initialize tabs to dropdown responsive
	//------------------------------------------
	$.fn.wpjTabsToDropdownInit = function() {
		if ( $( ".js-tab-to-dropdown" )[0] ) {
			$( ".js-tab-to-dropdown" ).each( function() {
				var $cnt         = $( this );
				var selected_val = false;

				$( "<select />" ).appendTo( $cnt );
				$cnt.find( "div.item.js-tab-item" ).each( function() {
					var $el = $( this );

					if ( $el.hasClass( 'active' ) == true ) {
						selected_val = $el.index();
					}

					$( "<option />", {
						"value"   : $el.attr( "data-tab" ),
						"text"    : $el.text().replace( /[0-9]/g, '' ),
					}).appendTo( $cnt.find( "select" ) );
				});

				if ( selected_val ) {
					$cnt.find( "select" ).find( "option" ).eq( selected_val - 1 ).prop( 'selected', true );
				}

				$cnt.find( "select" ).change( function() {
					var active_tab = $( '.item.js-tab-item.active' ).attr( 'data-tab' );
					$( 'div[data-tab="' + active_tab + '"]' ).removeClass( 'active' );
					$( 'div[data-tab="' + $( this ).find( "option:selected" ).val() + '"]' ).addClass( 'active' );
				});

				$cnt.find( "select" ).addClass( 'fluid' );
				$cnt.find( "select" ).dropdown( { message: { noResults: wpj_vars.nothing_found } } );
			});
		}
	}

	//----------------------------------------
	// Initialize autohide keyboard iOS
	//----------------------------------------
	$.fn.wpjAutoHideKeyboardInit = function() {
		if ( $( '.autohide-keyboard' )[0] ) {
			$( '.autohide-keyboard' ).form({
				on: 'blur',
				keyboardShortcuts: false
			});
		}
	}

	//----------------------------------------
	// Initialize toggle arrow
	//----------------------------------------
	$.fn.wpjToggleArrowInit = function() {
		if ( $( ".js-toggle-arrow" )[0] ) {
			$( ".js-toggle-arrow" ).each( function() {
				var $cnt = $( this );

				if ( ! $cnt.find( '.dynamically-title' )[0] ) {

					// iOS workaround for on click event
					$cnt.css( 'cursor', 'pointer' );

					// Add parent element classes
					$cnt.addClass( 'js-toggle-wrapper' );

					// Move existing title inside a div
					$cnt.find( ':header' ).wrap( '<div class="dynamically dynamically-title flex-master"></div>' );

					// Append icon
					$cnt.append( '<div class="dynamically dynamically-icon"><i class="js-toggle-angle-icon toggle-angle-icon toggle-angle-icon-up icon"></i></div>' );

				}

			});
		}
	}

	//----------------------------------------
	// Initialize number format
	//----------------------------------------
	$.fn.wpjNumberFormatInit = function() {
		Number.prototype.formatMoney = function( c, d, t ) {
			var n = Math.round( this * 100 ) / 100,
			c = isNaN( c = Math.abs( c ) ) ? 2 : c,
			d = d == undefined ? "." : d,
			t = t == undefined ? "," : t,
			s = n < 0 ? "-" : "",
			i = parseInt( n = Math.abs( +n || 0 ).toFixed( c ) ) + "",
			j = ( j = i.length ) > 3 ? j % 3 : 0;
			return s + ( j ? i.substr( 0, j ) + t : "" ) + i.substr( j ).replace( /(\d{3})(?=\d)/g, "$1" + t ) + ( c ? d + Math.abs( n - i ).toFixed( c ).slice( 2 ) : "" );
		};

		// disable mousewheel on a input number field when not in focus
		// (to prevent Cromium browsers change the value when scrolling)
		$( 'form' ).on( 'blur', 'input[type=number]', function ( e ) {
			$( this ).off( 'mousewheel.disableScroll' );
		});

		// accepts only numbers in numeric inputs
		$( 'input[type="number"]' ).on( 'keypress', function( e ) {

			var allowed_key_codes_arr = [/*backspace*/8,/*tab*/9,/*arrows*/37,39,/*numbers*/48,49,50,51,52,53,54,55,56,57,/*dot*/46,110,190]; // allowed keys

			// if event key is not in array and its not Ctrl+V (paste) return false
			if ( $.inArray( e.keyCode, allowed_key_codes_arr ) === -1 && ( e.keyCode != 17 && e.keyCode != 86 ) ) {
				e.preventDefault();

			// if float decimal exists and key is not backspace return false
			} else if ( $.trim( $( this ).val() ).indexOf( '.' ) > -1 && $.inArray( e.keyCode, [110, 190] ) != -1 ) {
				e.preventDefault();

			// return true
			} else {
				return true;

			}

		}).on( 'paste', function( e ) {

			// get event text and filter out letter characters
			var pasted_text = e.originalEvent.clipboardData.getData( 'Text' ).replace( /[^0-9.]/g, '' );

			if ( $.isNumeric( pasted_text ) ) {
				e.originalEvent.target.value = pasted_text;
				e.preventDefault();

			} else {
				e.preventDefault();

			};

		});
	}

	//----------------------------------------
	// Initialize lazy load
	//----------------------------------------
	$.fn.wpjLazyLoadInit = function() {
		if ( wpj_vars.lazy_loading_enabled == 1 && jQuery.isFunction( echo.init ) ) {
			echo.init({
				offset  : 100,
				throttle: 250,
				unload  : false,
				callback: function ( element, op ) {
					jQuery( element ).addClass( 'echo-lazy-loaded' );
				}
			});
		}
	}

	//----------------------------------------
	// Render lazy load
	//----------------------------------------
	$.fn.wpjLazyLoadRender = function() {
		if ( wpj_vars.lazy_loading_enabled == 1 && jQuery.isFunction( echo.render ) ) {
			echo.render({
				offset  : 100,
				throttle: 250,
				unload  : false,
				callback: function ( element, op ) {
					setTimeout( function() {
						jQuery( element ).addClass( 'echo-lazy-loaded' );
					}, 1000 );
				}
			});
		}
	}

	//-----------------------------------
	// Lazy loading to all site images
	//-----------------------------------
	$.fn.wpjLazyLoadImagesInit = function() {
		if ( $( 'img' )[0] && wpj_vars.lazy_loading_enabled == 1 ) {
			$( 'img' ).each( function() {

				if (
					! $( this ).hasClass( 'brz-img' )
					&& ! $( this ).hasClass( 'portfolio-image' )
					&& ! $( this ).hasClass( 'rs-pzimg' )
					&& ! $( this ).hasClass( 'rev-slidebg' )
					&& ! $( this ).parents( '.message-box-logo-container' )[0]
					&& ! $( this ).parents( '.header-wrapper' )[0]
					&& ! $( this ).parents( '.footer-wrapper' )[0]
					&& ! $( this ).parents( '.home-hero-slider-wrapper' )[0]
					&& ! $( this ).parents( '.ui.modal' )[0]
					&& ! $( this ).parents( '.pm-messages-row-wrapper' )[0]
					&& ! $( this ).parents( '.trp-language-switcher-container' )[0]
					&& ! $( this ).parents( '.trp_language_switcher_shortcode' )[0]
					&& ! $( this ).parents( '.wpj-carousel' )[0]
					&& ! $( this ).parents( '.pm-conversations-row-wrapper' )[0]
				) { // exclude brizy, featherlight (portofolio), revslider images, modals

					$( this ).attr( 'data-echo', $( this ).attr( 'src' ) );
					$( this ).addClass( 'echo-lazy-load' );
					$( this ).attr( 'src', wpj_vars.theme_path + "/assets/images/media/blank.gif" );

				}

			});

			$.fn.wpjLazyLoadInit();
		}
	}

	//-----------------------------------
	// Initialize range slider
	//-----------------------------------
	$.fn.wpjRangeSliderInit = function() {
		if ( $( "#slider-range-min" )[0] ) {
			var slider_default = $( "#slider-range-min" ).data( "value" );

			$( "#slider-range-min" ).slider({
				range: "min",
				value: slider_default,
				min  : 1,
				max  : slider_default,
				slide: function( e, ui ) {
					$( "#amount" ).val( ui.value );

					jQuery.ajax({
						type    : 'POST',
						url     : wpj_vars.ajaxurl,
						data    : {
							action : 'day_translation_action',
							value  : ui.value
						},
						success : function( data ) {
							$( "#amount-label" ).html( data );
						}
					});
				}
			});

			$( "#amount" ).val( $( "#slider-range-min" ).slider( "value" ) );
		}
	}

	//-----------------------------------
	// Initialize no href
	//-----------------------------------
	$.fn.wpjNoHrefInit = function() {
		if ( $( '.js-no-href' )[0] ) {
			$( '.js-no-href' ).removeAttr( 'href' );
			$( document ).on( 'click', '.js-no-href', function( e ) { e.preventDefault(); });
		}
	}

	//-----------------------------------
	// Initialize fliptimer
	//-----------------------------------
	$.fn.wpjFlipTimerInit = function() {
		if ( $( '.flipTimer' )[0] ) {
			$( '.flipTimer' ).flipTimer({
				direction: 'down',
				date: wpj_vars.order_expected_delivery,
			});
		}
	}

	//-----------------------------------
	// Initialize audio player
	//-----------------------------------
	$.fn.wpjAudioFileInit = function() {
		if ( typeof wpj_audio_js_player_init === 'function' && jQuery( '.audios-wrapper' )[0] ) {
			jQuery( '.audios-wrapper' ).removeClass( 'div-disabled' );

			$.each( JSON.parse( jQuery( '.audios-wrapper' ).attr( 'data-audio-details' ) ), function( key, value ) {
				wpj_audio_js_player_init( value['attachment_id'], value['url'], value['filename'] );
			});
		}
	}

	//-----------------------------------
	// Initialize wysiwyg textarea
	//-----------------------------------
	$.fn.wpjWYSIWYGInit = function() {
		if ( jQuery( '.wysiwyg-description-textarea' )[0] ) {
			jQuery( '.wysiwyg-description-textarea' ).each( function() {
				var action               = jQuery( this ).attr( 'data-type' );
				var max_chr_limit        = jQuery( this ).attr( 'maxlength' );
				var post_status          = jQuery( this ).attr( 'data-post-status' );
				var rejected_description = jQuery( this ).attr( 'data-rejected' );
				var indx                 = jQuery( this ).attr( 'data-indx' );
				var id                   = jQuery( this ).attr( 'id' );

				if ( action == 'job_edit' )
					wpj_init_wysiwyg_textarea( max_chr_limit, post_status , rejected_description );

				else if ( action == 'packages' )
					wpj_init_wysiwyg_textarea( max_chr_limit, '', '', indx );

				else
					wpj_init_wysiwyg_textarea( max_chr_limit, '', '', '', id );
			});
		}
	}

	//-----------------------------------
	// Initialize phone number
	//-----------------------------------
	$.fn.wpjPhoneNumberInit = function() {
		if ( $( '.cell_number' )[0] ) {
			var user_country = $( '.cell_number' ).attr( 'data-country' );
			user_country = user_country ? user_country.toLowerCase() : 'us';

			var default_country = $( '.cell_number' ).attr( 'data-default-country' );
			default_country = default_country ? default_country.toLowerCase() : 'us';

			var only_countries = $( '.cell_number' ).attr( 'data-only-countries' );
			if ( only_countries ) {
				only_countries = only_countries.toLowerCase().split( ',' );
				if ( $.inArray( user_country, only_countries ) === -1 ) user_country = '';
				if ( $.inArray( default_country, only_countries ) === -1 ) default_country = '';

			} else only_countries = [];

			$( '.cell_number' ).intlTelInput({
				nationalMode      : false,
				initialCountry    : default_country,
				preferredCountries: [ user_country ],
				onlyCountries     : only_countries
			});
		}
	}

	//-----------------------------------
	// Initialize copy of a string
	//-----------------------------------
	$( document ).on( 'click', 'a', function( e ) {
		if ( $( this ).prop( "hash" ) == '#copy' ) {
			e.preventDefault();
			copyString( $( this ) );
			$( this ).notify( wpj_vars.copied, { position: 'top center', className: 'success' } );
		}
	});

} ( jQuery ) );

//----------------------------------------
// Initialize triggers
//----------------------------------------
function wpj_init_change_triggers() {
	// location
	if ( jQuery( '.js-lets-meet-trigger' )[0] ) jQuery( '.js-lets-meet-trigger' ).trigger( 'change' );

	// post new job
	if ( jQuery( '.page-id-' + wpj_vars.new_job_page_id )[0] ) {
		if ( jQuery( '#max_days' )[0] ) jQuery( '#max_days' ).trigger( 'change' );
		if ( jQuery( 'select[name="price_type"]' )[0] ) jQuery( 'select[name="price_type"]' ).trigger( 'change' );
		if ( jQuery( 'select[name="job_cat"]' )[0] ) jQuery( 'select[name="job_cat"]' ).trigger( 'change' );
	}
}

//----------------------------------------
// Initialize audio player
//----------------------------------------
function wpj_audio_js_player_init( id, url, filename ) {
	if ( jQuery( "#jquery_jplayer_" + id )[0] ) {
		jQuery( "#jquery_jplayer_" + id ).jPlayer({
			ready: function() {
				jQuery( this ).jPlayer( "setMedia", {
					title:filename,
					mp3: url,
					wav: url
				});
			},
			play: function() { // to avoid multiple jPlayers playing together.
				jQuery( this ).jPlayer( "pauseOthers" );
			},
			swfPath            : "../../js",
			supplied           : "mp3, wav",
			cssSelectorAncestor: "#jp_container_" + id,
			wmode              : "window",
			globalVolume       : true,
			useStateClassSkin  : true,
			autoBlur           : false,
			smoothPlayBar      : true,
			keyEnabled         : true
		});
	}
}

//----------------------------------------
// Initialize calendar input
//----------------------------------------
function wpj_init_calendar_input( this_elem, page, date_type, time_format ) {
	var today = new Date();

	if ( ! date_type ) date_type = 'date';
	if ( ! time_format ) time_format = 'false';

	var inp_val_ts    = this_elem.find( "input" ).val();
	var inp_val_ts_js = inp_val_ts * 1000;

	var new_date = getSafeDateFormat( inp_val_ts_js, date_type );
	if ( inp_val_ts ) this_elem.find( "input" ).val( new_date );

	var inp_name = this_elem.find( "input" ).attr( 'name' );
	if ( ! inp_name.includes( '-old' ) ) {
		this_elem.find( "input" ).attr( 'name', inp_name + '-old' );

		var new_input = jQuery( '<input type="hidden" name="' + inp_name + '" value="' + inp_val_ts + '" />' );
		new_input.insertAfter( this_elem );
	}

	var min_date = page == 'vacation' ? new Date( today.getFullYear(), today.getMonth(), today.getDate() ) : null;

	this_elem.calendar({
		type           : date_type,
		ampm           : time_format == 'true' ? true : false,
		firstDayOfWeek : parseInt( wpj_vars.starting_day ),
		minDate        : min_date,
		popupOptions   : {
			position   : isMobile() ? 'bottom left' : 'top left',
			lastResort : 'bottom left'
		},
		text           : {
			days       : [
				wpj_vars.days.sun,
				wpj_vars.days.mon,
				wpj_vars.days.tue,
				wpj_vars.days.wed,
				wpj_vars.days.thu,
				wpj_vars.days.fri,
				wpj_vars.days.sat
			],
			months     : [
				wpj_vars.months.jan,
				wpj_vars.months.feb,
				wpj_vars.months.mar,
				wpj_vars.months.apr,
				wpj_vars.months.may,
				wpj_vars.months.jun,
				wpj_vars.months.jul,
				wpj_vars.months.aug,
				wpj_vars.months.sep,
				wpj_vars.months.oct,
				wpj_vars.months.nov,
				wpj_vars.months.dec
			],
			monthsShort: [
				wpj_vars.monthsShort.jan,
				wpj_vars.monthsShort.feb,
				wpj_vars.monthsShort.mar,
				wpj_vars.monthsShort.apr,
				wpj_vars.monthsShort.may,
				wpj_vars.monthsShort.jun,
				wpj_vars.monthsShort.jul,
				wpj_vars.monthsShort.aug,
				wpj_vars.monthsShort.sep,
				wpj_vars.monthsShort.oct,
				wpj_vars.monthsShort.nov,
				wpj_vars.monthsShort.dec
			],
			today      : wpj_vars.today,
			now        : wpj_vars.now,
			am         : wpj_vars.am,
			pm         : wpj_vars.pm
		},
		monthFirst: false,
		onChange: function( date, text, mode ) {
			var timestamp = '';
			if ( date ) timestamp = Math.floor( date.getTime() / 1000 );

			this_elem.find( 'input' ).attr( 'data-timestamp', timestamp );

			this_elem.next( 'input[type=hidden]' ).attr( 'data-timestamp', timestamp );
			this_elem.next( 'input[type=hidden]' ).val( timestamp );
		}
	});

	if ( typeof new_input === 'undefined' )
		var new_input = jQuery( 'input[name="' + inp_name + '"]' );

	new_input.attr( 'data-timestamp', inp_val_ts );
	if ( inp_val_ts ) new_input.val( inp_val_ts );

	return this;
}

//----------------------------------------
// Initialize counters
//----------------------------------------
function wpj_init_inputs_counter() {
	if ( jQuery( '.charlimit-request-title' )[0] ) jQuery( '.charlimit-request-title' ).counted({ count:wpj_vars.characters_request_title_max });
	if ( jQuery( '.charlimit-request-description' )[0] ) jQuery( '.charlimit-request-description' ).counted({ count:wpj_vars.characters_request_desc_max });
	if ( jQuery( '.charlimit-message' )[0] ) jQuery( '.charlimit-message' ).counted({ count: wpj_vars.characters_pm_max });
	if ( jQuery( '.charlimit-jobtitle' )[0] ) jQuery( '.charlimit-jobtitle' ).counted( { count: wpj_vars.characters_job_title_max });
	if ( jQuery( '.charlimit-jobdescription' )[0] ) jQuery( '.charlimit-jobdescription' ).counted( { count: wpj_vars.characters_job_desc_max });
	if ( jQuery( '.charlimit-jobinstruction' )[0] ) jQuery( '.charlimit-jobinstruction' ).counted( { count: wpj_vars.characters_job_instr_max });
	if ( wpj_vars.enable_extra && jQuery( '.charlimit-extradescription-1' )[0] ) jQuery( '.charlimit-extradescription-1' ).counted( { count: wpj_vars.characters_extradesc_max });
}

//----------------------------------------
// Initialize carousels
//----------------------------------------
function wpj_init_carousels() {
	var is_rtl = typeof wpj_vars !== 'undefined' && wpj_vars.is_rtl ? true : false;

	wpj_initialize_news_carousel( is_rtl );
	wpj_initialize_jobs_slider_carousel( is_rtl );
	wpj_initialize_wpj_carousel( is_rtl );
	wpj_initialize_portfolio_carousel( is_rtl );
	wpj_initialize_home_carousel( is_rtl );
	wpj_initialize_photo_categories_carousel( is_rtl );
	wpj_initialize_jobs_images_carousel( is_rtl );
	wpj_initialize_category_icons_carousel( is_rtl );
	wpj_initialize_news_hero_slider( is_rtl );
	wpj_initialize_user_reviews_carousel( is_rtl );
}

//----------------------------------------
// Initialize emojis
//----------------------------------------
function wpj_init_emojis() {
	wpj_pm_emoji_init();
	wpj_chat_emoji_init();
	wpj_transaction_emoji_init();
}

//----------------------------------------
// Initialize charts
//----------------------------------------
function wpj_init_charts() {
	if ( jQuery( ".js-user-chart-wrapper" )[0] ) {
		if ( ( typeof google === 'undefined' ) || ( typeof google.visualization === 'undefined' ) )
			google.charts.load( 'current', {'packages' : ['corechart']} );
		google.charts.setOnLoadCallback( wpj_get_user_account_graph );
	}
}

//----------------------------------------
// Initialize wysiwyg textarea
//----------------------------------------
function wpj_init_wysiwyg_textarea( max_chr_description, post_status, rejected_description, pck_index, identifier_id ) {
	if ( ! identifier_id ) { var identifier_id = 'job_description'; }

	var wysihtml5ParserRules = {
		classes: "any",
		classes_blacklist: {
			"Apple-interchange-newline": 1,
			"MsoNormal": 1,
			"MsoPlainText": 1
		},
		tags: {
			strong : { rename_tag: "b" },
			b      : {},
			i      : {},
			em     : { rename_tag: "i" },
			u      : {},
			br     : {},
			p      : {},
			span   : 1,
			div    : 1,
			ul     : {},
			ol     : {},
			li     : {},
			comment: { remove: 1 },
			style  : { remove: 1 },
		}
	};

	if ( typeof pck_index !== 'undefined' && pck_index ) {
		var input_id = 'package_description_' + pck_index;
		var input_id_toolbar = 'package_description_' + pck_index + '_toolbar';

	} else {
		var input_id = identifier_id;
		var input_id_toolbar = identifier_id + '_toolbar';

	}

	if ( jQuery( 'body' ).hasClass( "rtl" ) )
		var stylesheets = [wpj_vars.theme_path + '/assets/css/front-rtl/wysiwyg-rtl.css'];

	else
		var stylesheets = [wpj_vars.theme_path + '/assets/css/vendor/front/wysiwyg.css'];

	var editor = new wysihtml5.Editor( input_id, {
		toolbar    : input_id_toolbar,
		autoLink   : false,
		parserRules: wysihtml5ParserRules,
		stylesheets: stylesheets
	});

	editor.on( "load", function() {

		if ( typeof pck_index === 'undefined' || ! pck_index  ) {
			var $iframe = jQuery( this.composer.iframe );
			var $body   = jQuery( this.composer.element );
			var $html   = $body.parent();

			$body.css({ 'min-height': '100px', 'height': 'auto' });
			$html.css({ 'height': 'auto' });

			var scrollHeightInit = $body[0].scrollHeight;
			var bodyHeightInit   = $body.height();
			var heightInit       = Math.min( scrollHeightInit, bodyHeightInit );
			$iframe.height( heightInit );

			$body.bind( 'keypress keyup keydown paste change focus blur', function( e ) {
				var scrollHeight = $body[0].scrollHeight;
				var bodyHeight   = $body.height();
				var height       = Math.min( scrollHeight, bodyHeight );
				$iframe.height( height );
			});
		}

		add_input_length_listener( editor, jQuery( "#" + input_id ).siblings( ".char-count" ), max_chr_description, "html" );

		jQuery( '#' + identifier_id ).parents( '#job_description_field' ).removeClass( 'error' );

		if ( jQuery( 'body' ).hasClass( 'wpj-is-ios' ) ) {
			if ( jQuery( '#' + input_id + '_iosblurfix' ).length == 0 ) {
				// create fake input to help with blur
				jQuery( '#' + input_id ).after( '<input id="' + input_id + '_iosblurfix" type="text" disabled="disabled" style="width: 0; height: 0; padding: 1px; border: 0; position: absolute; opacity: 0;">' );
			}

			jQuery( document ).mouseup( function( e ) {
				// if the target of the click isn't the container nor a descendant of the container
				if ( ! jQuery( '#' + input_id ).is( e.target )
					&& jQuery( '#' + input_id ).has( e.target ).length === 0
					&& ( e.target.tagName.toUpperCase() !== 'INPUT' )
					&& ( e.target.tagName.toUpperCase() !== 'TEXTAREA' )
				) {
					jQuery( '#' + input_id + '_iosblurfix' ).removeAttr( "disabled" ).focus().blur().attr( "disabled", "disabled" );
				}
			});
		}
	})
	.on( "focus", function() {
		jQuery( '#' + identifier_id ).parents( ".job-description-wysiwyg" ).eq( 0 ).addClass( 'has-focus' );
		jQuery( '#' + identifier_id ).parents( ".input-block" ).eq( 0 ).find( 'iframe' ).addClass( 'focus' );
		jQuery( '#' + identifier_id ).parents( "#job_description_field" ).removeClass( 'error' );
	})
	.on( "blur", function() {
		jQuery( '#' + identifier_id ).parents( ".job-description-wysiwyg" ).eq( 0 ).removeClass( 'has-focus' );
		jQuery( '#' + identifier_id ).parents( ".input-block" ).eq( 0 ).find( 'iframe' ).removeClass( 'focus' );
	})

	editor.observe( "load", function() {

	});
}

//----------------------------------------
// Initialize tinyMCE textarea
//----------------------------------------
function wpj_init_tinyMCE_textarea( response ) {
	if ( jQuery( '.tinyMCE-textarea-wrapper' )[0] && jQuery( response ).find( '.tinyMCE-textarea-wrapper' )[0] ) {
		jQuery( '.tinyMCE-textarea-wrapper' ).replaceWith( jQuery( response ).find( '.tinyMCE-textarea-wrapper' )[0].outerHTML );

		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' );
			}
		});

		setTimeout( function() { wpj_init_tinymce_textarea_character_count(); }, 5000 );
	}
}

//----------------------------------------
// Initialize tinyMCE textarea count
//----------------------------------------
function wpj_init_tinymce_textarea_character_count() {
	if ( jQuery( '#job_description_ifr' )[0] ) {
		// load
		var job_description_length = get_input_length( jQuery( '#job_description_ifr' ).contents().find( 'body' ), 'html' );

		jQuery( '#chars_counter' ).text( job_description_length );

		// keyup
		jQuery( '#job_description_ifr' ).contents().find( 'body' ).on( 'keyup input change paste', function( e ) {
			job_description_length = get_input_length( jQuery( '#job_description_ifr' ).contents().find( 'body' ), 'html' );

			jQuery( 'textarea[name="job_description"]' ).val( tinyMCE.activeEditor.getContent() );
			jQuery( '#chars_counter' ).text( job_description_length );
		});

		// rejected class
		if ( jQuery( 'textarea[name="job_description"]' ).hasClass( 'rejected-input' ) ) {
			jQuery( '#job_description_ifr' ).parents( '#wp-job_description-wrap' ).addClass( 'rejected-input' );
		}
	}
}