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

	function wpj_open_order_modal( modal_class ) {
		$( '.ui.modal.' + modal_class )
			.modal({
				onVisible: function() { $( '.ui.button.loading' ).removeClass( 'basic' ).removeClass( 'loading' ).removeClass( 'dislabed' ); }
			})
			.modal( 'setting', 'transition', 'fly down' )
			.modal( 'show' )
			.modal( 'refresh' );
	}

	// Open resolution center modal
	$( document ).on( 'click', '.open-modal-resolution-center', function( e ) {
		e.preventDefault();
		wpj_open_order_modal( 'resolution-center' );
	});

	// Open request modification modal
	$( document ).on( 'click', '.open-modal-request-modifications', function( e ) {
		e.preventDefault();
		wpj_open_order_modal( 'request-modification' );
	});

	// Open tips modal
	$( document ).on( 'click', '.open-modal-tips-chatbox', function( e ) {
		e.preventDefault();
		wpj_open_order_modal( 'add-tips' );
	});

	// Resolution center action
	$( document ).on( 'click', '.js-resolution-center-option', function( e ) {
		e.preventDefault();

		var selected_action = $( 'input[name="resolution_center_option"]:checked' ).val();
		if ( ! selected_action ) { selected_action = 'cancellation'; }

		$( '.ui.modal.resolution-center' ).modal( 'hide' );

		if ( selected_action == 'cancellation' )
			wpj_open_order_modal( 'request-mutual-cancellation' );

		else if ( selected_action == 'arbitration' )
			wpj_open_order_modal( 'request-arbitration' );

		else if ( selected_action == 'extended_delivery_time' )
			wpj_open_order_modal( 'request-extended-delivery-time' );

	});

	// Cancel modal button
	$( document ).on( 'click', '.ui.cancel.button', function() {
		$( this ).parents( '.ui.modal' ).modal( 'hide' );
	});

	// Message with scroll
	if ( ! wpj_vars.transaction_emoji_enabled == 1 ) {
		$( document ).on( 'input propertychange change blur', '.order-message-form-textarea', function( e ) {
			if ( $( this ).hasScrollbar() ) {
				if (  wpj_vars.is_rtl )
					$( '.order-message-form-content' ).find( ' .quick-response-wrapper' ).animate({ left : '28px' }, 100 );
				else
					$( '.order-message-form-content' ).find( ' .quick-response-wrapper' ).animate({ right : '28px' }, 100 );

			} else {
				if (  wpj_vars.is_rtl )
					$( '.order-message-form-content' ).find( ' .quick-response-wrapper' ).animate({ left : '18px' }, 100 );
				else
					$( '.order-message-form-content' ).find( ' .quick-response-wrapper' ).animate({ right : '18px' }, 100 );

			}
		});

	}

	// Create tip payment and redirect to checkout
	$( document ).on( 'submit', '.tips_form', function( e ) {
		e.preventDefault();

		$( '.tips_form .button' ).addClass( 'loading' );
		$( '.tips_form .button' ).addClass( 'disabled' );

		var $this = $( this );

		$.ajax({
			data    : "action=new_tip_action&" + $this.serialize(),
			dataType: "json",
			type    : "POST",
			url     : wpj_vars.ajaxurl,
			success: function( msg ) {
				$( '.tips_form .button' ).removeClass( 'loading' );
				$( '.tips_form .button' ).removeClass( 'disabled' );

				$( '.js-create-tip-payment' ).notify( msg.description, { position: 'top center', className: msg.code } );

				if ( msg['code'] == 'success' ) {
					$( '.ui.modal.add-tips' ).modal( 'hide' );
					window.location.replace( wpj_vars.checkout_url );

					var form_content = '\
						<form id="accept_tips" method="post" name="purchase_tips' + msg['tips_id'] + '" action="' + wpj_vars.checkout_url + '" style="display: none;">\
							<input type="hidden" name="oid" value="' + msg['oid'] + '" />\
							<input type="hidden" name="tips" value="' + msg['tips_id'] + '" />\
							<input type="hidden" name="purchaseformvalidation" value="ok" />\
						</form>\
					';
					$( form_content ).insertAfter( $( '#order-notification-messages-wrapper' ) );
					$( "form[name='purchase_tips" + msg['tips_id'] + "']" ).submit();
				}
			}
		});
	});

	// Send transaction message action
	$( document ).on( 'click', '.send-message', function( e ) {
		e.preventDefault();

		if ( wpj_vars.transaction_emoji_enabled == 1 )
			var message = validateInputContent( $( '.cmi-listen.message-field' ).data( 'emojioneArea' ).getText() );
		else
			var message = validateInputContent( $( '.cmi-listen.message-field' ).val() );

		if ( wpj_vars.transaction_emoji_enabled == 1 )
			var message_length = get_input_length_emoji( $( '.cmi-listen.message-field' ).data( 'emojioneArea' ).getText() );
		else
			var message_length = get_input_length( $( '.cmi-listen.message-field' ) );

		if ( message == "" )
			$( this ).notify( wpj_vars.msg_err, { position: 'top right', className: 'error' } );

		else if ( message_length < parseInt( wpj_vars.characters_pm_min ) )
			$( this ).notify( wpj_vars.pm_min_content, { position: 'top right', className: 'error' } );

		else if ( message_length > parseInt( wpj_vars.characters_pm_max ) )
			$( this ).notify( wpj_vars.pm_max_content, { position: 'top right', className: 'error' } );

		else {
			var data = $( '#order-message-form' ).serialize();

			if ( wpj_vars.transaction_emoji_enabled == 1 ) {
				var element  = data.split( "&" );
				var new_data = "";

				for ( i = 0; i < element.length; i++ ) {
					var keyValue = element[i].split( "=" );
			        var key      = keyValue[0];
			        var value    = keyValue[1];

			        if ( key === "message" ) {
			            new_data += key + "=" + encodeURIComponent( message ) + "&";

			        } else {
			            new_data += key + "=" + value + "&";

			        }
				}

				data = new_data.slice( 0, -1 ); // Remove the trailing '&'
			}

			$( this ).attr( "disabled", "disabled" );

			$.ajax({
				type: "POST",
				url : wpj_vars.ajaxurl,
				data: data,
				success: function( msg ) {
					$( '.order-message-form-textarea' ).val( '' );

					if ( wpj_vars.transaction_emoji_enabled == 1 ) {
						$( '.emojionearea-editor' ).text( '' );
						$( '.emojionearea-editor' ).focus();
					}

					// clear the attachments queue
					$( '#uploadifive-file_upload_chat_box_attachments-queue' ).empty();
					$( 'input[name="hidden_files_chat_box_attachments"]' ).val( '' );

					refreshContent( '#order-notification-messages-wrapper' );

					setTimeout( 'jQuery( ".send-message" ).removeAttr( "disabled" )', 500 );
				}
			});

		}

	});

	// User rating
	$( document ).on( 'click', '.submit-user-rating', function( e ) {
		var $this = $( this );
		var rid   = $this.attr( 'rel' );

		if ( ! $( "#reason-" + rid ).val() && $( "#reason-" + rid ).val().length < wpj_vars.characters_feedback_min ) {
			$this.notify( wpj_vars.feedback_min_desc, { position: 'top center', className: 'error' } );

		} else if ( $( "#reason-" + rid ).val() && $( "#reason-" + rid ).val().length > wpj_vars.characters_feedback_max ) {
			$this.notify( wpj_vars.feedback_max_desc, { position: 'top center', className: 'error' } );

		} else if ( ! $( "input[name=stars]:checked", "#rating-" + rid ).val() ) {
			$this.notify( wpj_vars.feedback_stars, { position: 'top center', className: 'error' } );

		} else {

			var skills = [];

			$this.parents( '.js-review-form' ).find('.cb-skills-wrapper').find( '.ui.label[data-active="1"]' ).each( function() {
				skills.push( $.trim( $( this ).attr( 'data-slug' ) ) );
			});

			$.ajax({
				type   : "POST",
				url    : wpj_vars.ajaxurl,
				data   : {
					action   : 'save_user_review_action',
					oid      : $this.attr( 'data-order-id' ),
					rid      : rid,
					stars    : $( "input[name=stars]:checked", "#rating-" + rid ).val(),
					reason   : encodeURIComponent( validateInputContent( $( "#reason-" + rid ).val() ) ),
					sample   : $this.attr( 'data-sample' ),
					skills   : skills,
					user_type: $this.attr( 'data-user' )
				},

				beforeSend: function() {
					$this.addClass( 'ui loading button' );
				},

				success: function( msg ) {
					$( "#order-message-form-wrapper" ).hide( 'slow' );
					$( "#post-" + rid ).hide( 'slow' );
				},

				complete: function() {
					refreshContent( '#order-feedback-form-wrapper' ); // hide review form
					refreshContent( '#order-notification-messages-wrapper' ); // order notifications
				}
			});

		}

		return false;
	});

	// User endorsements
	$( document ).on( 'click', '.js-endorse-skill', function() {
		if ( $( this ).parents( '.label' ).hasClass( 'basic' ) ) { // add +1
			$( this ).parents( '.label' ).removeClass( 'basic' ).css( 'background-color', '#FBBD08' );
			$( this ).parents( '.label' ).css( 'color', '#FFFFFF' );
			$( this ).find( 'i' ).removeClass( 'plus' ).addClass( 'minus' );
			$( this ).parents( '.label' ).attr( 'data-active', 1 );

		} else { // remove +1
			$( this ).parents( '.label' ).addClass( 'basic' ).css( 'background-color', '#FFFFFF' );
			$( this ).parents( '.label' ).css( 'color', '#000000' );
			$( this ).find( 'i' ).removeClass( 'minus' ).addClass( 'plus' );
			$( this ).parents( '.label' ).removeAttr( 'data-active' );

		}
	});

	// Cancel order
	$( document ).on( 'click', '.js-order-cancel-button', function( e ) {
		e.preventDefault();

		var orderid = window.location.pathname.split( '/' ).filter( Boolean ).pop();
		var method  = $( '.js-payment-method' ).attr( 'data-method' );

		take_to_gateway_job_purchase_process( 'cancel', orderid, method );
	});

	// Process order
	$( document ).on( 'click', '.js-order-process-button', function( e ) {
		e.preventDefault();

		var orderid = window.location.pathname.split( '/' ).filter( Boolean ).pop();
		var method  = $( '.js-payment-method' ).attr( 'data-method' );

		take_to_gateway_job_purchase_process( 'process', orderid, method );
	});

	// Save proof of payment
	$( document ).on( 'click', '.save-job-payment-proof', function( e ) {
		e.preventDefault();

		var $this = $( this );
		var data     = $( '#job-order-bank-payment-proof' ).serialize();
		var order_id = $( this ).siblings( 'input[name="order_id"]' ).val();

		$this.addClass( 'ui loading disabled button' );

		$.ajax({
			type: "POST",
			url : wpj_vars.ajaxurl,
			data: data,
			success: function( msg ) {
				refreshContent( '#job-payment-proof-attachments' );

				setTimeout( function() {
					$this.removeClass( 'ui loading disabled button' );

					// clear the attachments queue
					$( '#uploadifive-file_upload_bank_transfer_job_proof_attachments_' + order_id + '-queue' ).empty();
					$( 'input[name="hidden_files_bank_transfer_job_proof_attachments_' + order_id + '"]' ).val( '' );

					$this.addClass( 'div-disabled' );
				}, 1000 );
			}
		});
	});

});

function wpj_init_order_click_actions() {
	var actions = new Map();

	actions.set( "js-accept-order",                          { action: "accept_order_action"                   } );
	actions.set( "js-deny-order",                            { action: "deny_order_action"                     } );

	actions.set( "js-mark-order-delivered",                  { action: "mark_order_delivered_action"           } );
	actions.set( "js-mark-order-completed",                  { action: "mark_order_completed_action"           } );

	actions.set( "js-request-arbitration",                   { action: "request_arbitration_action"            } );
	actions.set( "js-abort-arbitration-request",             { action: "abort_arbitration_action"              } );

	actions.set( "js-request-modification",                  { action: "request_modification_action"           } );

	actions.set( "js-request-cancellation",                  { action: "request_cancellation_action"           } );
	actions.set( "js-abort-cancellation-request",            { action: "abort_cancellation_action"             } );
	actions.set( "js-accept-cancellation-request",           { action: "accept_cancellation_action"            } );
	actions.set( "js-deny-cancellation-request",             { action: "deny_cancellation_action"              } );

	actions.set( "js-cancel-expired-order",                  { action: "cancel_expired_order_action"           } );

	actions.set( "js-accept-custom-extra",                   { action: "accept_custom_extra_action"            } );
	actions.set( "js-decline-custom-extra",                  { action: "decline_custom_extra_action"           } );
	actions.set( "js-cancel-custom-extra",                   { action: "cancel_custom_extra_action"            } );

	actions.set( "js-decline-custom-offer",                  { action: "decline_custom_offer_action"           } );
	actions.set( "js-withdraw-custom-offer",                 { action: "withdraw_custom_offer_action"          } );

	actions.set( "js-cancel-tip",                            { action: "cancel_tip_action"                     } );

	actions.set( "js-request-extended-delivery-time",        { action: "request_extended_delivery_time_action" } );
	actions.set( "js-abort-extended-delivery-time-request",  { action: "abort_extended_delivery_time_action"   } );
	actions.set( "js-accept-extended-delivery-time-request", { action: "accept_extended_delivery_time_action"  } );
	actions.set( "js-deny-extended-delivery-time-request",   { action: "deny_extended_delivery_time_action"    } );

	actions.forEach ( ( action_json, button_class ) => {
		jQuery( document ).on( 'click', '.' + button_class, function() {
			var element = jQuery( this );

			var data = {
				action: action_json.action,
				oid   : jQuery( 'input[name="oid"]' ).val()
			};

			if ( action_json.action == 'request_arbitration_action' )
				data['message_to_admin'] = jQuery( '#message_to_admin' ).val();

			else if ( action_json.action == 'request_modification_action' )
				data['message_request_modification'] = jQuery( '#message_to_seller' ).val();

			else if ( action_json.action == 'request_cancellation_action' ) {
				data['message_to_buyer'] = jQuery( '#message_to_buyer' ).val();
				data['process_action']   = jQuery( '#process_action' ).val();

			} else if ( action_json.action == 'accept_cancellation_action' )
				data['accept'] = 'yes';

			else if ( action_json.action == 'deny_cancellation_action' )
				data['accept'] = 'no';

			else if ( action_json.action == 'accept_custom_extra_action' || action_json.action == 'decline_custom_extra_action' || action_json.action == 'cancel_custom_extra_action' )
				data['custom_extra'] = jQuery( this ).attr( 'data-custom-extra' );

			else if ( action_json.action == 'decline_custom_offer_action' || action_json.action == 'withdraw_custom_offer_action' ) {
				data['custom_offer'] = jQuery( this ).attr( 'data-custom-offer' );
				data['pm_id']        = jQuery( this ).attr( 'data-id' );

			} else if ( action_json.action == 'cancel_tip_action' )
				data['tips'] = jQuery( this ).attr( 'data-tip' );

			else if ( action_json.action == 'request_extended_delivery_time_action' ) {
				data['extended_days_message']  = jQuery( '#extended_days_message' ).val();
				data['extended_days_selector'] = jQuery( '#extended_days_selector' ).val();
			}

			jQuery.ajax({
				type   : "POST",
				url    : wpj_vars.ajaxurl,
				data   : data,
				beforeSend: function() {
					element.addClass( 'ui basic button loading dislabed' );

					if ( button_class == 'js-accept-order'
						|| button_class == 'js-deny-order'
						|| button_class == 'js-accept-cancellation-request'
						|| button_class == 'js-deny-cancellation-request'
						|| button_class == 'js-accept-extended-delivery-time-request'
						|| button_class == 'js-deny-extended-delivery-time-request'
					)
						jQuery( '.' + button_class ).parent().addClass( 'div-disabled' );

					element.parents( '.ui.modal' ).find( '.ui.message' ).removeClass( 'negative visible' ).addClass( 'hidden' ).html( '' );

				},
				success: function( response ) {
					if ( response && button_class == 'js-request-arbitration' ) {
						var data = JSON.parse( response );
						if ( data.err === 1 )
							element.parents( '.ui.modal' ).find( '.ui.message' ).removeClass( 'hidden' ).addClass( 'negative visible' ).html( data.msg );

					}

					if ( ! response || ( response && response != 0 && data.err !== 1 ) ) {

						// Reset form
						if ( jQuery( '#message_to_admin' )[0] ) jQuery( '#message_to_admin' ).val( '' );
						if ( jQuery( '#message_to_seller' )[0] ) jQuery( '#message_to_seller' ).val( '' );
						if ( jQuery( '#message_to_buyer' )[0] ) jQuery( '#message_to_buyer' ).val( '' );
						if ( jQuery( '#extended_days_message' )[0] ) jQuery( '#extended_days_message' ).val( '' );
						if ( jQuery( '#extended_days_selector' )[0] ) jQuery( '#extended_days_selector' ).dropdown( 'set selected', 1 );
						jQuery( '.actions' ).find( '.ui.button.disabled' ).removeClass( 'disabled' );

						// Hide modal
						if ( element.parents( '.ui.modal' )[0] )
							element.parents( '.ui.modal' ).modal( 'hide' );

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

							if ( button_class == 'js-accept-order'
								|| button_class == 'js-mark-order-delivered'
								|| button_class == 'js-mark-order-completed'
								|| button_class == 'js-accept-extended-delivery-time-request'
								|| button_class == 'js-decline-custom-extra'
							) {
								refreshContent( '.order-timer-wrapper' ); // show/hide timer

								if ( button_class == 'js-decline-custom-extra' || button_class == 'js-mark-order-completed' ) {
									refreshContent( '#order-message-form-wrapper' ); // hide message form
									refreshContent( '#order-feedback-form-wrapper' ); // show review form
								}
							}

							if ( button_class == 'js-deny-order' || button_class == 'js-accept-cancellation-request' ) {
								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
							}
						}

						// PM
						if ( button_class == 'js-decline-custom-offer' || button_class == 'js-withdraw-custom-offer' ) { // custom offer response
							if ( jQuery( '.is-page-pm' )[0] ) // pm page
								refreshContent( '.thread-list-wrapper' );

							if ( jQuery( '.is-page-pm.is-page-pm-single' )[0] ) // pm user page
								refreshContent( '.js-messages-list .kt-inside-inner-col:first' );

							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

							}
						}

					}

				}
			});

		});
	});
}

function wpj_scroll_to_last_order_box() {
	if ( jQuery( ".order-box-wrapper " )[0] ) {
		jQuery( 'html, body' ).animate({
			scrollTop: jQuery( ".order-box-wrapper " ).last().offset().top - 150
		}, 2000 );
	}
}