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

	// New Item
	var toggle_new_item = false;
	$( document ).on( "click", ".user-new-item", function( e ) {
		e.preventDefault();

		var $this = $( this );
		var item_name = $( this ).data( 'type' );

		if ( item_name == 'education' || item_name == 'certification' ) {
			wpj_up_open_modal( item_name, 'new', $this );

		} else {

			/* EDIT */ if ( ! toggle_new_item ) { toggle_new_item = true;

				// Change the label to "Save";
				$( this ).text( wpj_vars.save_lbl );

				// Append inputs to complete the content
				if ( item_name == 'skills' )
					$( this ).siblings( '.content-wrapper' ).find( '.new_item' ).show();

				else
					wpj_get_html_for_inputs( $this, item_name );

			/* SAVE */ } else { toggle_new_item = false;

				// Get values
				var value = false;
				if ( item_name == "languages" ) {
					if ( validateInputContent( $( ".up_language" ).val() ) && validateInputContent( $( ".up_proficiency" ).dropdown( 'get value' ) ) )
						value = true;
				}

				else if ( item_name == "skills" ) {
					if ( validateInputContent( $( ".up_skills" ).val() ) )
						value = true;
				}

				if ( value && ! $( 'span' ).hasClass( sanitizeTitle( validateInputContent( $( ".up_" + item_name ).val() ) ) ) ) {

					// Save the data to user_meta
					wpj_send_via_ajax( wpj_get_ajax_data( item_name + "_new", validateInputContent( $( ".up_" + item_name ).val() ) ), '.user-' + item_name + '-wrapper' );

					// Remove "no item" paragraph
					$( '.' + item_name + '-content' ).children( '.no_item' ).remove();

				}

				// Change the label to "Add New";
				$(this).html( '<i class="plus icon"></i>' );

				// Remove editable content
				$( ".new_item" ).not( ".new-skill-wrapper" ).remove();
			}

		}
	});

	// Edit Item
	var click_count      = 0;
	var toggle_edit_item = false;

	$( document ).on( "click", ".user-edit-item", function( e, item_name ) { click_count++;
		e.preventDefault();

		var $this = $( this );

		if ( e.originalEvent !== undefined ) { // is clicked
			item_name = $( this ).data( 'type' );
		} else { // is triggered
			toggle_edit_item = true;
		}

		if ( item_name == 'education' || item_name == 'certification' ) {
			wpj_up_open_modal( item_name, 'edit', $this );
		} else {

			/* EDIT */ if ( ! toggle_edit_item ) { if ( item_name != "tagline" ) { toggle_edit_item = true; }
				// Change the label to "Save Description";
				if ( item_name == "description" ) { $( this ).text( wpj_vars.save_lbl ); }

				// Hide paragraph description until edit is done
				if ( item_name == "tagline" ) {
					$( this ).hide();
				} else {
					$( this ).siblings( '.' + item_name + '-content' ).find( '.' + item_name ).hide();
				}

				// Append inputs to complete the content
				if ( item_name == "description" ) {
					var value = wpj_vars.desc_content;
					if ( click_count > 1 ) {
						var value = wpj_vars.wysiwyg_enabled? $( '.description-content' ).html() : $( '.description-content' ).text();
						if ( value.includes( "no_item" ) ) {
							value = '';
						}
					}
				} else if ( item_name == "tagline" ) {
					var value = $( this ).attr( 'class' ).includes( "no_item" ) ? '' : $( this ).text();
				}

				// Show editable content
				wpj_get_html_for_inputs( $this, item_name, value );

				// Set Focus
				$( '#tmp_' + item_name ).focus();

				// Initialize Textarea
				if ( item_name == "description" ) { wpj_initialize_and_remove_textarea( "initialize" ); }

			/* SAVE */ } else { toggle_edit_item = false;

				// Change the label to "Edit Description";
				if ( item_name == "description" ) { $( this ).html( '<i data-type="languages" class="user-edit-language pencil alternate icon"></i>' ); }

				// Show paragraph
				if ( item_name == "description" ) {
					if ( $( '.tmp_' + item_name ).val().replace( /<(.|\n)*?>/g, '' ) == '' ) {
						$( '.user-description-wrapper' ).find( '.description-content' ).find( '.' + item_name ).html( '<p class="no_item">' + wpj_vars.no_description + '</p>' ).show();
					} else {
						$( '.user-description-wrapper' ).find( '.description-content' ).find( '.' + item_name ).html( $( '.tmp_' + item_name ).val() ).show();
					}
				} else {
					$( '.' + item_name ).html( validateInputContent( $( '.tmp_' + item_name ).val() ) ).show();
				}

				// Lost Focus
				$( '#tmp_' + item_name ).blur();

				// Save the data to user_meta
				wpj_send_via_ajax( wpj_get_ajax_data( item_name + "_edit", $( '#tmp_' + item_name ).val() ) );

				// Remove editable content
				if ( item_name == "description" ) {
					wpj_initialize_and_remove_textarea( "remove" );
				}
			}
		}
	});

	// Remove Item
	$( document ).on( "click", ".user-remove-item", function( e ) {
		e.preventDefault();

		var item_name = $( this ).data( 'type' );

		// Remove in front-end
		$( this ).parents( 'span' ).remove();

		// Insert no item text if items list is empty
		if ( $( '.' + item_name + '-content > span' ).length == 0 ) {
			var message = '';

			if ( item_name == "languages" )
				message = wpj_vars.no_languages;

			else if ( item_name == "skills" )
				message = wpj_vars.no_skills;

			else if ( item_name == "education" )
				message = wpj_vars.no_educations;

			else if ( item_name == "certification" )
				message = wpj_vars.no_certifications;

			$( '.' + item_name + '-content' ).append( '<p class="no_item">' + message + '</p>' );
		}

		// Save the data to user_meta
		var item_to_be_removed = item_name == 'skills' ? $( this ).parents( "span" ).attr( "data-slug" ) : $( this ).parents( "span" ).attr( "class" );
		wpj_send_via_ajax( wpj_get_ajax_data( item_name + "_remove", validateInputContent( item_to_be_removed ) ) );
	});

	// Tagline
	$( document ).on( "click", ".save-info", function( e ) {
		e.preventDefault();

		var tagline_value = validateInputContent( $( ".tmp_tagline" ).val() );
		if ( ! tagline_value ) {
			tagline_value = wpj_vars.no_tagline;
			$( this ).parents( '.user-tagline-wrapper' ).find( '.tagline' ).addClass( 'no_item' );
		} else {
			$( this ).parents( '.user-tagline-wrapper' ).find( '.tagline' ).removeClass( 'no_item' );
		}

		$( ".tagline" ).html( tagline_value ).show();

		wpj_send_via_ajax( wpj_get_ajax_data( "tagline_edit", validateInputContent( $( "#tmp_tagline" ).val() ) ) );

		$( ".tagline-temp" ).remove();
	});

	// Languages
	var toggle_edit_language = false;
	$( document ).on( "click", ".user-edit-language", function( e ) {
		e.preventDefault();

		var item_name = $( this ).data( 'type' );

		/* EDIT */ if ( ! toggle_edit_language ) { toggle_edit_language = true;

			// Current SPAN
			var this_span = $( this ).parents( "span" );

			// Reset divs to store the value before edit
			$( '.old_language, .old_proficiency' ).remove();

			// Make the content editable
			this_span.find( ".inp_language, .inp_proficiency" ).removeClass( "not_editable" );
			this_span.find( ".inp_language" ).attr( "readonly", false );

			// Remove "edit" class and add "save" class
			this_span.find( ".user-edit-language" ).removeClass( "edit" ).addClass( "save" );
			this_span.find( ".user-edit-language" ).parent().attr( "data-tooltip", wpj_vars.save_lbl );

			// Store the value before edit
			var old_content = '\
				<div class="old_language" style="display:none">' + this_span.find( ".inp_language" ).val() + '</div>\
				<div class="old_proficiency" style="display:none">' + this_span.find( ".inp_proficiency" ).dropdown( 'get value' ) + '</div>\
			';
			$( old_content ).insertAfter( this_span.find( ".inp_proficiency" ) );

		/* SAVE */ } else { toggle_edit_language = false;

			// Current SPAN
			var this_span = $( this ).parents( "span" );

			// Transform the content to paragraph
			this_span.find( ".inp_language, .inp_proficiency" ).addClass( "not_editable" );
			this_span.find( ".inp_language" ).attr( "readonly", true );

			// Remove "save" class and add "edit" class
			this_span.find( ".user-edit-language" ).removeClass( 'save' ).addClass( 'edit' );
			this_span.find( ".user-edit-language" ).parent().attr( "data-tooltip", wpj_vars.edit_lbl );

			// Save the content
			var data = {
				action          : 'change_user_language_content',
				old_language    : this_span.find( ".old_language" ).html(),
				language        : validateInputContent( this_span.find( ".inp_language" ).val() ),
				old_proficiency : this_span.find( ".old_proficiency" ).html(),
				proficiency     : validateInputContent( this_span.find( ".inp_proficiency" ).dropdown( 'get value' ) ),
				uid             : jQuery( '.content-wrapper' ).attr( 'data-uid' )
			};

			wpj_send_via_ajax( data );

		}
	});

	// Education & Certification - Conditional Selector
	var classes = [ "user_from_year", "user_to_year" ];
	classes.forEach( function( class_name ) {
		$( document ).on( 'change', '.' + class_name, function() {
			var this_val = $( this ).dropdown( 'get value' );

			if ( class_name.includes( "to" ) ) {

				$( ".user_from_year" ).find( '.item' ).each( function() {
					if ( parseInt( this_val ) && parseInt( $( this ).attr( 'data-value' ) ) <= parseInt( this_val ) ) {
						$( this ).removeClass( "disabled" );
					} else {
						$( this ).addClass( "disabled" );
					}
				});

			} else {

				$( ".user_to_year" ).find( '.item' ).each( function() {
					if ( parseInt( this_val ) && parseInt( $( this ).attr( 'data-value' ) ) >= parseInt( this_val ) ) {
						$( this ).removeClass( "disabled" );
					} else {
						$( this ).addClass( "disabled" );
					}
				});

			}
		});
	});

	// Education & Certification - Conditional Button
	$( document ).on( 'input paste blur change', 'input[name="user_school"], input[name="user_certification_name"]', function( e ) {
		if ( $( this ).val().length !== 0 ) $( '.save-item' ).removeClass( 'disabled' );
		else $( '.save-item' ).addClass( 'disabled' );
	});

	// Education & Certification - Save
	$( document ).on( 'submit', '.modal_form', function( e ) {
		e.preventDefault();

		var item_name = $( this ).data( 'type' );

		$( '.modal_form .actions .button' ).addClass( 'loading' );

		jQuery.ajax({
			type : "POST",
			url  : wpj_vars.ajaxurl,
			data : "action=save_user_" + item_name + "_content&" + $( this ).serialize(),
			success: function( msg ) {
				$( '.modal_form .actions .button' ).removeClass( 'loading' );

				$( '.ui.modal.up-' + item_name + '-modal-wrapper' ).modal( 'hide' );

				if ( item_name == 'education' ) {
					addLoader( '.info-widget.user-education-wrapper' );
					refreshContent( '.info-widget.user-education-wrapper' );

				} else {
					addLoader( '.info-widget.user-certification-wrapper' );
					refreshContent( '.info-widget.user-certification-wrapper' );

				}
			}
		});
	});

	// Portfolio - Display
	$( document ).on( "click", ".js-toggle-portfolio-handler", function( e ) {
		e.preventDefault();

		$( this ).parent().children( ".js-image-attachments-carousel" ).hide();
		$( this ).hide();

		$( this ).parent().children( ".js-profile-portfolio-uploader" ).show();
		$( this ).parent().children( ".js-refresh-portfolio-handler" ).show();

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

	// Portfolio - Save
	$( document ).on( "click", ".js-refresh-portfolio-handler", function( e ) {
		e.preventDefault();
		addLoader( '.profile-main-content.user-portfolio-wrapper' );
		refreshContent( '.profile-main-content.user-portfolio-wrapper' );
	});

});

function wpj_get_html_for_inputs( $this, item_name, item_value ) {
	var content = "";

	if ( item_name == "languages" ) {
		content = '\
			<div class="new_item">\
				<div class="ui input new-item-content w100">\
					<input placeholder="' + wpj_vars.language_lbl + '" class="di up_language w50" type="text" name="language" />\
					&nbsp;\
					<select class="ui dropdown w50 up_proficiency" name="proficiency">\
						<option value="elementary">' + wpj_vars.lbl_elementary + '</option>\
						<option value="limited">' + wpj_vars.lbl_limited + '</option>\
						<option value="professional">' + wpj_vars.lbl_professional + '</option>\
						<option value="native">' + wpj_vars.lbl_native + '</option>\
					</select>\
				</div>\
			</div>\
		';

	} else if ( item_name == "tagline" ) {
		content = '\
			<div class="tagline-temp">\
				<div class="ui input"><input type="text" id="tmp_tagline" class="tmp_tagline" value="' + item_value + '" /></div>\
				<a data-type="tagline" class="save-info">' + wpj_vars.save_lbl + '</a>\
			</div>\
		';

	} else if ( item_name == "description" ) {
		if ( item_value == null || item_value === false ) { item_value = ''; }

		if ( wpj_vars.wysiwyg_enabled ) {
			content = '<textarea class="tmp_description" id="tmp_description">' + item_value + '</textarea>\
				\
				<div id="tmp_description_toolbar" class="tmp_description-wysiwyg-toolbar">\
					<a data-wysihtml5-command="bold"><i class="bordered bold icon"></i></a>\
					<a data-wysihtml5-command="italic"><i class="bordered italic icon"></i></a>\
					<a data-wysihtml5-command="underline"><i class="bordered underline icon"></i></a>\
					<a data-wysihtml5-command="insertUnorderedList"><i class="bordered unordered list icon"></i></a>\
					<a data-wysihtml5-command="insertOrderedList"><i class="bordered ordered list icon"></i></a>\
				</div>\
			';
		} else {
			content = '<textarea class="tmp_description" id="tmp_description">' + item_value + '</textarea>';

		}

	}

	jQuery( $this ).parents( '.user-' + item_name + '-wrapper' ).find( '.' + item_name + '-content' ).append( content );

	jQuery( '.ui.dropdown.up_proficiency' ).dropdown( { message: { noResults: wpj_vars.nothing_found } } );
}

function wpj_initialize_and_remove_textarea( action ) {
	if ( action == "initialize" ) {
		if ( wpj_vars.wysiwyg_enabled ) {
			wpj_init_wysiwyg_textarea( 1000, '', '', '', 'tmp_description' );

		} else {
			jQuery( "#tmp_description" ).height( jQuery( "#tmp_description" )[0].scrollHeight );
			jQuery( "#tmp_description" ).focus();

		}

	} else if ( action == "remove" ) {
		if ( wpj_vars.wysiwyg_enabled ) {
			jQuery( '#tmp_description' ).remove();
			jQuery( '.wysihtml5-sandbox' ).remove();
			jQuery( '#tmp_description_toolbar' ).remove();

		} else {
			jQuery( '#tmp_description' ).remove();

		}

	} else {
		return false;

	}
}

function wpj_get_ajax_data( item_name, item_value ) {
	if ( item_name == "languages_new" )
		action = "save_user_language_content";

	else if ( item_name == "languages_remove" )
		action = "remove_user_language_content";

	else if ( item_name == "skills_new" )
		action = "save_user_skill_content";

	else if ( item_name == "skills_remove" )
		action = "remove_user_skill_content";

	else if ( item_name == "description_edit" )
		action = "save_user_description_content";

	else if ( item_name == "tagline_edit" )
		action = "save_user_tagline_content";

	else if ( item_name == "education_remove" )
		action = "remove_user_education_content";

	else if ( item_name == "certification_remove" )
		action = "remove_user_certification_content";

	var data = {};

	if ( item_name == "languages_new" ) {
		data = {
			action      : action,
			language    : validateInputContent( jQuery( ".up_language" ).val() ),
			proficiency : validateInputContent( jQuery( ".up_proficiency" ).dropdown( 'get value' ) ),
			uid         : jQuery( '.content-wrapper' ).attr( 'data-uid' )
		};

	} else if ( item_name == 'skills_new' ) {
		data = {
			action   : action,
			item     : item_value,
			item_logo: jQuery( '.skill-image-wrapper' ).attr( 'data-id' ),
			uid      : jQuery( '.content-wrapper' ).attr( 'data-uid' )
		};

	} else {
		data = {
			action : action,
			item   : item_value,
			uid    : jQuery( '.content-wrapper' ).attr( 'data-uid' )
		};

	}

	return data;
}

function wpj_send_via_ajax( data, wrapper_reload ) {
	jQuery.ajax({
		type   : "POST",
		url    : wpj_vars.ajaxurl,
		data   : data,
		beforeSend: function() { if ( wrapper_reload !== undefined ) addLoader( wrapper_reload ); },
		success: function() { if ( wrapper_reload !== undefined ) refreshContent( wrapper_reload ); }
	});
}

function wpj_up_open_modal( item_name, action_type, $this ) {

	if ( ! action_type ) action_type = 'new';

	jQuery( '.up-' + item_name + '-modal-wrapper.' + $this.attr( 'data-indx' ) )
		.modal({
			onShow: function() {
				var item_action = action_type == 'new' ? wpj_vars.add_lbl : wpj_vars.edit_lbl;
				jQuery( '.add-or-edit-title' ).html( item_action );

				if ( action_type == 'new' )
					jQuery( '.save-item' ).addClass( 'disabled' );

				if ( jQuery( '.user_from_year' ).val() ) {
					jQuery( '.user_to_year' ).find( 'option' ).each( function() {
						if ( parseInt( jQuery( '.user_from_year' ).val() ) && parseInt( jQuery( this ).val() ) >= parseInt( jQuery( '.user_from_year' ).val() ) )
							jQuery( this ).attr( 'disabled', false );

						else
							jQuery( this ).attr( 'disabled', true );

					});
				}

				if ( jQuery( '.user_to_year' ).val() ) {
					jQuery( '.user_from_year' ).find( 'option' ).each( function() {
						if ( parseInt( jQuery( '.user_to_year' ).val() ) && parseInt( jQuery( this ).val() ) <= parseInt( jQuery( '.user_to_year' ).val() ) )
							jQuery( this ).attr( 'disabled', false );

						else
							jQuery( this ).attr( 'disabled', true );

					});
				}

				if ( item_name == 'education' ) jQuery.fn.wpjUploadifiveUploaderInit();
			}
		})
		.modal( 'setting', 'transition', 'fly down' )
		.modal( 'show' )
		.modal( 'refresh' );

	return false;
}

function wpj_hide_up_certification_not_expire() {
	if ( jQuery( '.certification-not-expire' )[0] ) {
		jQuery( '.certification-not-expire' ).checkbox({
			onChecked: function() {
				jQuery( '.user_to_year' ).dropdown( 'clear' );
				jQuery( '.user_to_month' ).dropdown( 'clear' );

				jQuery( '.to_year' ).addClass( 'disabled' );
				jQuery( '.to_month' ).addClass( 'disabled' );
			},
			onUnchecked: function() {
				jQuery( '.to_year' ).removeClass( 'disabled' );
				jQuery( '.to_month' ).removeClass( 'disabled' );
			}
		});
	}
}