// Turn radios into btn-group
jQuery(function($) {
	/**
	 * Turn radios into btn-group
	 */
	var container = document.querySelectorAll('.btn-group');
	for (var i = 0; i < container.length; i++) {
		var labels = container[i].querySelectorAll('label');
		for (var j = 0; j < labels.length; j++) {
			labels[j].classList.add('btn');
			var inputValue = $('input[type=radio]', labels[j]).val(); 
			if ((j % 2) == 1 && inputValue !== '') {
				labels[j].classList.add('btn-outline-danger');
			} if ((j % 2) == 1 && inputValue === '') {
				labels[j].classList.add('btn-outline-primary');
			} else {
				labels[j].classList.add('btn-outline-success');
			}
		}
	}

	var btsGrouped = document.querySelectorAll('.btn-group input[checked=checked]');
	for (var i = 0, l = btsGrouped.length; l>i; i++) {
		var self   = btsGrouped[i],
		    attrId = self.id,
		    label = document.querySelector('label[for=' + attrId + ']');
		if (self.parentNode.parentNode.classList.contains('btn-group-reversed')) {
			if (self.value === 0) {
				label.classList.add('active');
				label.classList.add('btn');
				label.classList.add('btn-outline-success');
			} else {
				label.classList.add('active');
				label.classList.add('btn');
				label.classList.add('btn-outline-danger');
			}
		} else {
			if (self.value === 0) {
				label.classList.add('active');
				label.classList.add('btn');
				label.classList.add('btn-outline-danger');
			} else {
				if (self.value === '') {
					label.classList.add('active');
					label.classList.add('btn');
					label.classList.add('btn-outline-primary');
				} else {
					label.classList.add('active');
					label.classList.add('btn');
					label.classList.add('btn-outline-success');
				}
			}
		}
	}
	
	// Perform columns ordering
	$('a[data-ordering-form]').on('click', function(jqEvent){
		let orderingOrder = $(jqEvent.target).attr('data-ordering-order');
		let orderingDirection = $(jqEvent.target).attr('data-ordering-direction');
		let orderingTask = $(jqEvent.target).attr('data-ordering-task');
		Joomla.tableOrdering(orderingOrder, orderingDirection, orderingTask);
		return false;
	});
	
	// Always ensure to reset the other switcher button
	$(document).on('click', "fieldset[data-bs-toggle=buttons] label.btn", function(jqEvent) {
		if(jqEvent.target.nodeName.toUpperCase() == 'INPUT' || $(jqEvent.target).attr('disabled')) {
			return true;
		}
		
		var label = $(jqEvent.target).addClass('active');
		var input = $('input[type=radio]', label);

		var otherLabel = label.parents('fieldset').find("label").not(label);
		if (otherLabel.hasClass('active')) {
			otherLabel.removeClass('active btn-success btn-danger btn-primary');
		}
	});

	// Override the default switcher button colors/class for multiple selection switcher buttons
	var multipleSwitchers = $("div.controls > label:nth-child(3), div.controls > fieldset > label:nth-child(3)");
	multipleSwitchers.each(function(index, elem){
		var parentContainer = $(elem).parent();
		$('label', parentContainer).removeClass('btn-outline-success btn-outline-danger')
		// We are not in the configuration view
		if(parentContainer.prop("tagName").toLowerCase() != 'fieldset') {
			$('label:first-child', parentContainer).addClass('btn-outline-primary');
			$('label:not(:first-child)', parentContainer).addClass('btn-outline-success');
		} else {
			$('label', parentContainer).addClass('btn-outline-success');
		}
	});
	
	// Ensure that only input labels with 'No' value will be dangered 
	var doubledSwitchers = $("div.controls > label:nth-child(2), div.controls > fieldset > label:nth-child(2)");
	doubledSwitchers.each(function(index, elem){
		var inputValue = $('input', elem).val();
		if(inputValue != 0 && inputValue != '' && inputValue != '') {
			$(elem).removeClass('btn-outline-danger').addClass('btn-outline-success');
		}
	});
	
	/**
	 * Enables bootstrap popover
	 */
	[].slice.call(document.querySelectorAll('#updatestatus label.hasPopover')).map(function (popoverEl) {
		let popoverInstance = new bootstrap.Popover(popoverEl,{
			template : '<div class="popover"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>',
			trigger : 'hover',
			placement : 'right',
			html : true
		});
		return popoverInstance;
	});
	[].slice.call(document.querySelectorAll('label.hasPopover, button.hasPopover, div.hasPopover, span.hasPopover, img.hasPopover')).map(function (popoverEl) {
		let popoverInstance = new bootstrap.Popover(popoverEl,{
			template : '<div class="popover"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>',
			trigger : 'hover',
			placement : 'top',
			html : true
		});
		return popoverInstance;
	});
	[].slice.call(document.querySelectorAll('a.hasPopover.google')).map(function (popoverEl) {
		let popoverInstance = new bootstrap.Popover(popoverEl,{
			template : '<div class="popover"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>',
			trigger : 'hover',
			placement : 'bottom',
			html : true
		});
		return popoverInstance;
	});
	[].slice.call(document.querySelectorAll('thead a.hasPopover')).map(function (popoverEl) {
		return new bootstrap.Popover(popoverEl,{
			template : '<div class="popover"><div class="popover-arrow"></div><h3 class="popover-header"></h3><div class="popover-body"></div></div>',
			trigger : 'hover',
			placement : 'top',
			html : true
		});
	});
	
	/**
	 * Enables bootstrap tooltip
	 */
	[].slice.call(document.querySelectorAll('label.hasTooltip, img.hasTooltip, a.hasTooltip, span.hasTooltip, a.hasTip, *[rel=tooltip], a.page-link')).map(function (tooltipEl) {
		let tooltipInstance = new bootstrap.Tooltip(tooltipEl,{
			trigger : 'hover',
			placement : 'top',
			html : true
		});
		return tooltipInstance;
	});

	/**
	 * Remove empty ordering spans
	 */
	$('.order > span').filter(function() {
		var hasChild = !$('a', this).length;
		return hasChild;
	}).remove();
	
	$('div.sortable-handler').filter(function() {
		var isMovable = !$(this).nextAll('.moveup,.movedown').length;
		return isMovable;
	}).remove();
	
	// Recover the legacy save order button in async way on the next cycle
	setTimeout(function() {
		$('a.saveorder').removeAttr('onclick').removeAttr('style');
	}, 1);

	/**
	 * Remove custom select
	 */
	$('table.headerlist select').removeClass('form-select');
	
	if('fancybox' in $) {
		$('a.fancybox-graph-image').fancybox({
			autoScale : true,
			transitionOut : 'none',
			type : 'image' 
		});
	}
	
	// Remove configuration spacer empty div
	$('span.spacer').parent('div.control-label').next('div.controls').remove();
	
	/**
	 * Accordion panels local storage memoize and set open
	 */
	var defaultAccordionObject = {
		'jrealtime_accordion_cpanel' : 'jrealtime_stats',
		'jrealtime_accordion_help' : 'jrealtime_functionalities_frontend',
		'jrealtime_realstats_accordion' : [ 'jrealtime_realstats_byuser', 'jrealtime_realstats_bypage' ],
		'jrealtime_serverstats_accordion' : [ 'jrealtime_serverstats_pages', 
		                                      'jrealtime_serverstats_visitors', 
		                                      'jrealtime_serverstats_ipaddress', 
		                                      'jrealtime_serverstats_referral',
		                                      'jrealtime_serverstats_searches' ],
		'jrealtime_googlegraph_accordion' : [ 'jrealtime_googlestats_graph' ],
		'jrealtime_googlegeo_accordion' : ['jrealtime_googlestats_map'],
		'jrealtime_googletraffic_accordion' : ['jrealtime_googlestats_traffic'],
		'jrealtime_googlereferrer_accordion' : ['jrealtime_googlestats_referrers'],
		'jrealtime_googlesearches_accordion' : ['jrealtime_googlestats_searches'],
		'jrealtime_googlepages_accordion' : ['jrealtime_googlestats_pages'],
		'jrealtime_googleconsole_accordion' : [ 'jrealtime_google_query' ],
		'jrealtime_googleconsole_query_accordion' : [ 'jrealtime_google_pages' ]
	};

	// To store the last clicked dropdown-toggle button
	let lastClickedDropdown = null;

	// Listen for Bootstrap's dropdown events and exclude Joomla dropdown-toggle
	document.querySelectorAll('button.dropdown-toggle').forEach(function (element) {
	    element.addEventListener('show.bs.dropdown', function (targetElement) {
	    	// Set the clicked dropdown button before it triggers collapse
	    	lastClickedDropdown = this;
	    });
	    element.addEventListener('hide.bs.dropdown', function (targetElement) {
	    	// Set the clicked dropdown button before it triggers collapse
	        lastClickedDropdown = this;
	    });
	});
	
	[].slice.call(document.querySelectorAll('div.accordion')).map(function (accordionEl) {
		accordionEl.addEventListener('shown.bs.collapse', function(event) {
			if (!$(event.target).hasClass('accordion-body') && !$(event.target).hasClass('card-block')) {
				return;
			}
	
			// Trigger window resize to repaint the chart
			if ($(event.target).hasClass('accordion-chart')) {
				$(window).trigger('resize');
			}
	
			event.stopPropagation();
			$('div.accordion-heading').removeClass('opened');
			var localStorageAccordion = $.jStorage.get('jrealtimeAccordionOpened', defaultAccordionObject);
			// Check if stored accordions are managed as array of opened slides or
			// mutex exclusions
			if (!Array.isArray(localStorageAccordion[this.id])) {
				localStorageAccordion[this.id] = event.target.id;
			} else {
				localStorageAccordion[this.id].push(event.target.id);
			}
			$.jStorage.set('jrealtimeAccordionOpened', localStorageAccordion);
	
			// Scroll to accordion header if needed
			if (document.body.scrollHeight > window.innerHeight) {
				$('html, body').animate({
					scrollTop : parseInt($("#" + event.target.id).prev().offset().top) - 185
				}, 500);
			}
	
			// Manage fixed height if set for current accordion body
			var fixedHeight = $(event.target).data('height');
			if (fixedHeight) {
				$(event.target).animate({
					'height' : fixedHeight
				}, 200);
			}
	
			// Add open state
			$(event.target).prev().addClass('opened');
		});
		
		accordionEl.addEventListener('hidden.bs.collapse', function(event) {
			// Check if stored accordions are managed as array of opened slides or
			// mutex exclusions
			var localStorageAccordion = $.jStorage.get('jrealtimeAccordionOpened', defaultAccordionObject);
			if (Array.isArray(localStorageAccordion[this.id])) {
				var index = localStorageAccordion[this.id].indexOf(event.target.id);
				if (index > -1) {
					localStorageAccordion[this.id].splice(index, 1);
				}
			}
			$.jStorage.set('jrealtimeAccordionOpened', localStorageAccordion);
			$(event.target).prev().removeClass('opened');
		});
		
		accordionEl.addEventListener('hide.bs.collapse', function(event) {
			// Check if the Joomla dropdown-toggle has been clicked and prevent collapsing 
			if(lastClickedDropdown) {
				lastClickedDropdown = null;
				event.stopPropagation();
				event.preventDefault();
				return false;
			}
		});
	});

	$.each($.jStorage.get('jrealtimeAccordionOpened', defaultAccordionObject), function(namespace, element) {
		if (!Array.isArray(element)) {
			if ($('#' + element, '#' + namespace).length) {
				$('#' + element, '#' + namespace).addClass('show').prev().addClass('opened');
			}
		} else {
			$.each(element, function(k, element) {
				if ($('#' + element, '#' + namespace).length) {
					$('#' + element, '#' + namespace).addClass('show').prev().addClass('opened');
				}
				// Manage fixed height if set for current accordion body
				var fixedHeight = $('#' + element, '#' + namespace).data('height');
				if (fixedHeight) {
					// Set max height for this accordion panel
					$('#' + element, '#' + namespace).css('max-height', fixedHeight);
					$('#' + element, '#' + namespace).animate({
						'height' : fixedHeight
					}, 200);
				}
			});
		}
	});

	/**
	 * Prevent default scrolling hover main accordion body and scroll
	 * programmatically the document
	 */
	$('div.accordion-body').on('wheel', function(jqEvent) {
		if (jqEvent.originalEvent && jqEvent.originalEvent.wheelDelta) {
			if (jqEvent.originalEvent.wheelDelta)
				jqEvent.delta = jqEvent.originalEvent.wheelDelta;

			var newBodyScroll = $(document).scrollTop() - jqEvent.delta;
			$(document).scrollTop(newBodyScroll);
			jqEvent.preventDefault();
			return false;
		}
	});

	/**
	 * Tab panels local storage memoize and set open
	 */
	var defaultTabObject = {
		'tab_configuration' : 'preferences'
	};
	[].slice.call(document.querySelectorAll('#adminForm .nav.nav-tabs')).map(function (tabEl) {
		tabEl.addEventListener('shown.bs.tab', function(event) {
			var localStorageTab = $.jStorage.get('jrealtimeTabOpened', defaultTabObject);
			var assignedID = this.id ? this.id : $(this).parents('div.row').attr('id');
			var assignedValue = $(event.target).data('element') ? $(event.target).data('element') : $(event.target).attr('href').substr(1)
			localStorageTab[assignedID] = assignedValue;
			$.jStorage.set('jrealtimeTabOpened', localStorageTab);
			
			// Add accessibility ARIA
			$('li.nav-item', this).removeAttr('aria-selected').attr('aria-selected', 'false');
			$('li.nav-item', this).removeAttr('tabindex').attr('tabindex', -1);
			$(event.target).parent('li').attr({'aria-selected':'true', 'tabindex':0});
			
			// Ensure that the label input checked will be active
			$("fieldset[data-bs-toggle=buttons] > label.btn > input:checked").each(function(i, element) {
				var parentLabel = $(element).parent('label.btn');
				if (!parentLabel.hasClass('active')) {
					parentLabel.addClass('active');
				}
			});
		});
	});

	$.each($.jStorage.get('jrealtimeTabOpened', defaultTabObject), function(namespace, element) {
		var nodeElement = $('a[data-element=' + element + ']', '#' + namespace).get(0);
		if(nodeElement) {
			var tabInstance = new bootstrap.Tab(nodeElement);
			tabInstance.show();
		}
	});
		
	$(document).on('click', 'joomla-field-permissions ul[role=tablist] li', function(jqEvent){
		var tabTargetId = $('a', this).attr('id');
		$.jStorage.set('jrealtimeFieldPermissions', tabTargetId);
	});
	if($.jStorage.get('jrealtimeFieldPermissions')) {
		setTimeout(function(){
			var memoizedTabId = $.jStorage.get('jrealtimeFieldPermissions');
			if($('#' + memoizedTabId).length) {
				$('#' + memoizedTabId).get(0).click();
			}
		}, 150);
	}

	// Check for a specific tab trigger using url hash
	var licensePreferenceRequest = window.location.hash.substr(2);
	if (licensePreferenceRequest == 'licensepreferences') {
		var nodeElement = $('a[data-element=preferences]').get(0);
		if(nodeElement) {
			var tabInstance = new bootstrap.Tab(nodeElement);
			tabInstance.show();
		}
		$('#params_registration_email-lbl').css('color', 'red');
		$('#params_registration_email').css('border', '2px solid red');
		$('html, body').animate({
            scrollTop: $('#params_registration_email').offset().top - 120
        }, 800);
	}
	if(licensePreferenceRequest == 'google_analytics_ga4property') {
		var nodeElement = $('a[data-element=google_analytics]').get(0);
		if(nodeElement) {
			var tabInstance = new bootstrap.Tab(nodeElement);
			tabInstance.show();
		}
		$('#params_ga_property_id-lbl').css('color', 'red');
		$('#params_ga_property_id').css('border', '2px solid red');
		$('html, body').animate({
            scrollTop: $('#params_ga_property_id').offset().top - 120
        }, 800);
	}

	// Go to bottom button
	$('#gobottom').on('click', function() {
		$('html, body').animate({
			scrollTop : document.body.scrollHeight || document.documentElement.scrollHeight,
		}, 1000);
	});

	// Back to top button
	$('#backtop').on('click', function() {
		$('html, body').animate({
			scrollTop : 0,
		}, 1000);
	});

	// Show generic waiter
	var showGenericWaiter = function(mainContainerID) {
		// Get div popover container width to center waiter
		$('body').prepend('<img/>').children('img').attr('src', jrealtimeBaseURI + 'administrator/components/com_jrealtimeanalytics/images/loading.gif').css({
			'position' : 'absolute',
			'left' : '50%',
			'top' : '50%',
			'margin-left' : '-64px',
			'width' : '128px',
			'z-index' : '99999'
		});
	};
	$('#ga-dash button, *.waiter').on('click', function(jqEvent) {
		showGenericWaiter();
	});
	
	// Manage the hide/show of subcontrols for device switcher handler
	var templateSwitcher = $('select[name*=devicedectection_mode]').val();
	if(templateSwitcher == 'useragent') {
		$('input[name*=devicedectection_mode]').parents('div.control-group').hide();
	} else {
		$('input[name*=devicedectection_mode]').parents('div.control-group').show();
	}
	$('select[name*=devicedectection_mode]').on('change', function(){
		if($(this).val() == 'useragent') {
			$('input[name*=devicedectection_mode]').parents('div.control-group').slideUp();
		} else {
			$('input[name*=devicedectection_mode]').parents('div.control-group').slideDown();
		}
	});
	
	// Manage the hide/show of subcontrols for Analytics API Property ID
	var analyticsApiValue = $('select[name=params\\[analytics_api\\]]').val();
	if(analyticsApiValue != 'data') {
		$('*.analytics_api').parents('div.control-group').hide();
		$('*.no_analytics_api').parents('div.control-group').show();
	} else {
		$('*.no_analytics_api').parents('div.control-group').hide();
	}
	$('select[name=params\\[analytics_api\\]]').on('change', function(){
		if($(this).val() == 'data') {
			$('*.analytics_api').parents('div.control-group').slideDown();
			$('*.no_analytics_api').parents('div.control-group').slideUp();
		} else {
			$('*.analytics_api').parents('div.control-group').slideUp();
			$('*.no_analytics_api').parents('div.control-group').slideDown();
		}
	});

	// Manage the hide/show of subcontrols for Analytics service switcher
	var analyticsServiceValue = $('select[name=params\\[analytics_service\\]]').val();
	if(analyticsServiceValue == 'matomo') {
		$('*.google_analytics_api').parents('div.control-group').hide();
		$('*.matomo_api').parents('div.control-group').show();
	} else {
		$('*.matomo_api').parents('div.control-group').hide();
		$('*.google_analytics_api').parents('div.control-group').show();
	}
	$('select[name=params\\[analytics_service\\]]').on('change', function(){
		if($(this).val() == 'matomo') {
			$('*.google_analytics_api').parents('div.control-group').slideUp();
			$('*.matomo_api').parents('div.control-group').slideDown();
		} else {
			$('*.matomo_api').parents('div.control-group').slideUp();
			$('*.google_analytics_api').parents('div.control-group').slideDown();
		}
	});

	// Manage the hide/show of subcontrols for AI provider switcher
	var aiAnalysisFields = $('*.ai_analysis').parents('div.control-group');
	var aiGeminiFields = $('*.ai_provider_gemini').parents('div.control-group');
	var aiOpenAIFields = $('*.ai_provider_openai').parents('div.control-group');
	var aiEnabledField = $('input[name=params\\[ai_analysis_enabled\\]]');
	var aiProviderField = $('select[name=params\\[ai_provider\\]]');

	function toggleAIProviderFields(providerValue, animate) {
		if(providerValue == 'openai') {
			if(animate) {
				aiGeminiFields.slideUp();
				aiOpenAIFields.slideDown();
			} else {
				aiGeminiFields.hide();
				aiOpenAIFields.show();
			}
		} else {
			if(animate) {
				aiOpenAIFields.slideUp();
				aiGeminiFields.slideDown();
			} else {
				aiOpenAIFields.hide();
				aiGeminiFields.show();
			}
		}
	}

	function refreshAIFields(animate) {
		var aiEnabledValue = $('input[name=params\\[ai_analysis_enabled\\]]:checked').val();
		var aiProviderValue = aiProviderField.val() || 'gemini';
		if(aiEnabledValue == '1') {
			if(animate) {
				aiAnalysisFields.slideDown();
			} else {
				aiAnalysisFields.show();
			}
			toggleAIProviderFields(aiProviderValue, animate);
		} else {
			if(animate) {
				aiAnalysisFields.slideUp();
			} else {
				aiAnalysisFields.hide();
			}
		}
	}

	refreshAIFields(false);
	aiEnabledField.on('change', function(){
		refreshAIFields(true);
	});
	aiProviderField.on('change', function(){
		toggleAIProviderFields($(this).val(), true);
	});

	$('input.field-media-input').each(function(index, elem){
	    $(elem).css('visibility','hidden');
	});
	// Observe media field image selection change
	$('div.field-media-preview').each(function(index, elem){
		// Create an observer instance for each element to observe
		var observer = new MutationObserver(function(mutations) {
			var image = $('img', elem);
			if(image.length) {
				let relatedInputField = $(elem).next('div').find('input.field-media-input');
				relatedInputField.val(relatedInputField.val().split('#')[0]);
			}
		});
		observer.observe(elem, { childList: true });
	});
	setTimeout(function(){
	    $('input.field-media-input').each(function(index, elem){
    		elem.value = elem.value.split('#')[0];
    		$(elem).css('visibility','visible');
	    }); 
	}, 300);
	
	// Override permissions tab retrieve ACL
	$('#permissions select[data-onchange-task]').removeAttr('data-onchange-task').on('change', function(jqEvent) {
	    const {
	    	target
	    } = jqEvent;

	    const icon = document.getElementById(`icon_${target.id}`);
	    icon.removeAttribute('class');
	    icon.setAttribute('class', 'joomla-icon joomla-field-permissions__spinner');

	    const {
	    	value
	    } = target;

	    const id = target.id.replace('params_rules_', '');
	    const lastUnderscoreIndex = id.lastIndexOf('_');
	    const permissionData = {
	    		comp: 'com_jrealtimeanalytics',
	    		action: id.substring(0, lastUnderscoreIndex),
	    		rule: id.substring(lastUnderscoreIndex + 1),
	    		value,
	    		title: 'com_jrealtimeanalytics'
	    };

	    Joomla.removeMessages();

	    Joomla.request({
	    	url: document.querySelector('joomla-field-permissions').getAttribute('data-uri'),
	    	method: 'POST',
	    	data: JSON.stringify(permissionData),
	    	perform: true,
	    	headers: {
	    		'Content-Type': 'application/json'
	    	},
	    	onSuccess: data => {
	    		let response;

		        try {
		          response = JSON.parse(data);
		        } catch (e) {
		          console.log(e);
		        }

		        icon.removeAttribute('class');

		        if (response.data && response.data.result) {
		        	icon.setAttribute('class', 'joomla-icon joomla-field-permissions__allowed');
		        	const badgeSpan = target.parentNode.parentNode.nextElementSibling.querySelector('span');
		        	badgeSpan.removeAttribute('class');
		        	badgeSpan.setAttribute('class', response.data.class);
		        	badgeSpan.innerHTML = response.data.text;
		        }

		        if (typeof response.messages === 'object' && response.messages !== null) {
		        	Joomla.renderMessages(response.messages);
	        		if (response.data && response.data.result) {
		        	  	icon.setAttribute('class', 'joomla-icon joomla-field-permissions__allowed');
		          	} else {
		        	  	icon.setAttribute('class', 'joomla-icon joomla-field-permissions__denied');
		          	}
		        }
	    	},
	    	onError: xhr => {
	    		// Remove the spinning icon.
	    		icon.removeAttribute('style');
	    		Joomla.renderMessages(Joomla.ajaxErrorsMessages(xhr, xhr.statusText));
	    		icon.setAttribute('class', 'joomla-icon joomla-field-permissions__denied');
	    	}
	    });
	});
});

// Polyfill
if (!Array.isArray) {
	Array.isArray = function(arg) {
		return Object.prototype.toString.call(arg) === '[object Array]';
	};
}

/**
 * Compatibility functions for classical save ordering
 */
JRealtimeSaveOrder = function ( n, task ) {
	JRealtimeCheckAllCheckbox( n, task );
};

JRealtimeCheckAllCheckbox = function ( n, task ) {
	task = task ? task : 'saveorder';

	var j, box;

	for ( j = 0; j <= n; j++ ) {
		box = document.adminForm[ 'cb' + j ];

		if ( box ) {
			box.checked = true;
		} else {
			alert( "You cannot change the order of items, as an item in the list is `Checked Out`" );
			return;
		}
	}

	Joomla.submitform( task );
};