(function( $ ) {
	'use strict';

	function mojitoShippingGetAjaxErrorMessage(xhr, fallbackMessage) {

		if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
			return xhr.responseJSON.data.message;
		}

		return fallbackMessage;
	}

	 $(document).on('click', '.mojito-shipping-toggle-tracking', function(event) {
		 event.preventDefault();
		 $('.tracking-details').toggleClass('open');
	 });


	 /*
		Download PDF
	*/
	$(document).on('click', '.mojito-shipping-download-customer-pdf:not(.working)', function (event) {

		event.preventDefault();
		var $trigger = $(this);
		$trigger.addClass('working');

		var order_id = $trigger.data('order-id') || $trigger.attr('id');
		var action = $trigger.data('action');

		if (!action) {
			if ($trigger.closest('.mojito-ccr-download-pdf').length) {
				action = 'mojito_shipping_ccr_download_pdf_customer';
			} else if ($trigger.closest('.mojito-pymexpress-download-pdf').length) {
				action = 'mojito_shipping_pymexpress_download_pdf_customer';
			} else {
				action = 'mojito_shipping_pymexpress_download_pdf_customer';
			}
		}

		var data = {
			action: action,
			nonce: mojito_shipping_public.order_nonce,
			order_id: order_id,
		};

		$.post( mojito_shipping_public.ajax_url, data, function (response) {
			
			var data = JSON.parse(response);
			var guide_number = data.guide_number;
			var element = document.createElement('a');
			
			element.setAttribute('href', 'data:application/pdf;base64,' + data.content);
			element.setAttribute('download', guide_number + '.pdf' );
			element.style.display = 'none';
			document.body.appendChild(element);
			element.click();
			document.body.removeChild(element);

			$trigger.removeClass('working');

		}).fail(function (xhr) {
			alert( mojitoShippingGetAjaxErrorMessage(xhr, mojito_shipping_public.messages.order_action_error) );
			$trigger.removeClass('working');
		});

		return false;

	});

})( jQuery );
