/**
 * @copyright   Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

/**
 * Edit Associations javascript behavior
 *
 * Used for editing associations in the backend.
 *
 * @package  Joomla
 * @since    3.7.0
 */

window.hideAssociation = function(formControl, languageCode)
{
	jQuery('#associations .control-group').each(function()
	{
		// Current selected language. Hide it.
		if (jQuery(this).find('.control-label label').attr('for').replace(new RegExp('_id$'), '') == formControl + '_associations_' + languageCode.replace('-', '_'))
		{
			jQuery(this).hide();
		}
	});
}

window.showAssociationMessage = function()
{
	jQuery('#associations .control-group').hide();
	jQuery('#associations').prepend('<div id="associations-notice" class="alert alert-info">' + Joomla.JText._('JGLOBAL_ASSOC_NOT_POSSIBLE') + '</div>');
}

	/**
	 * Inject associations into other association fields
	 *
	 * This function is called whenever the Ajax request within propagateAssociation() completes successfully.
	 * Its purpose is to inject the associations which have been returned in the Ajax response into the other
	 * association fields in the form.
	 * It does this by invoking the various callback functions of those association fields (i.e. the function which
	 * gets called whenever the administrator selects an association via the modal), and passing the appropriate
	 * associated record details.
	 *
	 * @param   js object   result                  The response from the Ajax request.
	 *                                              Its structure is that generated by the JResponseJson class,
	 *                                              with the data field containing the associations
	 * @param   string      fieldPrefix             The stem of the html ids for the elements comprising the modal field
	 * @param   string      callbackFunctionPrefix  The name of the callback function which the modal window uses to set the
	 *                                              selected item as the association, but minus the language tag at the end
	 *
	 * @return  boolean
	 *
	 * @since   3.9.0
	 */
	Joomla.injectAssociations = function(result, callbackFunctionPrefix)
	{
		var functionName;

		if (result.success)
		{
			if (result.data.length !== 0)
			{
				for (var lang in result.data)
				{
					functionName = callbackFunctionPrefix + lang.replace("-","_");

					window[functionName](result.data[lang].id, result.data[lang].title, result.data[lang].catid, null, null, lang);
				}
			}

			if (result.message)
			{
				Joomla.renderMessages({"notice":[result.message]});
			}
		}
		else
		{
			Joomla.renderMessages({"warning":[(Joomla.JText._('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED'))]});
		}
	}

	/**
	 * Propagate associations from this field into other association fields
	 *
	 * This function is called whenever an administrator populates an association (in the association modal field)
	 * and then clicks on the Propagate button.
	 * The purpose of this function is to find what other records (if any) are associated with the one which the
	 * administrator has selected, and populate the other association fields with these records. (Otherwise, if the
	 * administrator just clicks on Save without clicking on Propagate, those other associations will be deleted).
	 * It does this by finding the id of the selected associated record (from a hidden field) and makes an Ajax call
	 * to the server to find the other associations, also passing up the language of the record currently being edited,
	 * as it should be excluded.
	 * Once it has received from the server the other associations it calls injectAssociations to inject them into
	 * the other association fields within the form.
	 *
	 * @param   string  fieldPrefix             The stem of the html ids for the elements comprising the modal field
	 * @param   string  callbackFunctionPrefix  The name of the callback function which the modal window uses to set the
	 *                                            selected item as the association, but minus the language tag at the end
	 *
	 * @return  boolean
	 *
	 * @since   3.9.0
	 */
	Joomla.propagateAssociation = function(fieldPrefix, callbackFunctionPrefix)
	{
		// Find the id of the record which has been set as an assocation
		var assocId = jQuery("#" + fieldPrefix + "_id").val();

		// Find the language of the record being edited
		var currentLang = jQuery('#jform_language').find(":selected").val();

		// Find the token so that it can be sent in the Ajax request as well
		var token = Joomla.getOptions('csrf.token', '');

		// Find the action url associated with the form - we need to add the token to this
		var url = jQuery("form[name='adminForm']").attr("action");
		url += '&' + token + '=1';

		jQuery.ajax(
		{
			url:  url,
			data: { task: "ajax.fetchAssociations", format: "json", assocId: assocId, excludeLang: currentLang },

			success: function(result, status, xhr) { Joomla.injectAssociations(result, callbackFunctionPrefix); },

			error: function() { Joomla.renderMessages({"warning":[(Joomla.JText._('JGLOBAL_ASSOCIATIONS_PROPAGATE_FAILED'))]}); },
		});

		return false;
	}

!(function()
{
	jQuery(document).ready(function($)
	{
		var associationsEditOptions = Joomla.getOptions('system.associations.edit'), formControl = associationsEditOptions.formControl || 'jform';

		// Hide the associations tab if needed.
		if (associationsEditOptions.hidden == 1)
		{
			window.showAssociationMessage();
		}
		// Hide only the associations for the current language.
		else
		{
			window.hideAssociation(formControl, $('#' + formControl + '_language').val());
		}

		// When changing the language.
		$('#' + formControl + '_language').on('change', function(event)
		{
			// Remove message if any.
			Joomla.removeMessages();
			$('#associations-notice').remove();

			var existsAssociations = false;

			// For each language, remove the associations, ie, empty the associations fields and reset the buttons to Select/Create.
			$('#associations .control-group').each(function()
			{
				var languageCode = $(this).find('.control-label label').attr('for').replace('_id', '').replace('jform_associations_', '');

				// Show the association fields.
				$(this).show();

				// Check if there was an association selected for this language.
				if (!existsAssociations && $('#' + formControl + '_associations_' + languageCode + '_id').val() !== '')
				{
					existsAssociations = true;
				}

				// Call the modal clear button.
				$('#' + formControl + '_associations_' + languageCode + '_clear').click();
			});

			// If associations existed, send a warning to the user.
			if (existsAssociations)
			{
				Joomla.renderMessages({warning: [Joomla.JText._('JGLOBAL_ASSOCIATIONS_RESET_WARNING')]});
			}

			var selectedLanguage = $(this).val();

			// If the selected language is All hide the fields and add a message.
			if (selectedLanguage == '*')
			{
				window.showAssociationMessage();
			}
			// Else show the associations fields/buttons and hide the current selected language.
			else
			{
				window.hideAssociation(formControl, selectedLanguage);
			}
		});
	});
})(window, document, Joomla);
