
// Register service worker
if ( 'serviceWorker' in navigator ) {

	// Use the window load event to keep the page load performant
	window.addEventListener('load', function(){
			navigator.serviceWorker
				.register( '/sw.js' )
				.catch(function(err) { console.error('Failed to load service worker handler.', err); } );
	});
}


// Prevent animations kicking off immediately to initial positions
setTimeout(function(){
    $('body').addClass( 'loaded' ) ;
    // document.body.className="loaded";
},250);


// Remove any empty dashboard parts
$( function(){
	$('.dashboard, .headed_box').each( function() {
		if ( $.trim( $(this).text() ) == "" && $(this).find( 'img' ).length === 0 ) {
			$(this).remove();
		}
		//$( ".dashboard h2:only-child" ).parent().remove() ;
	});
});

// Turn boxes to alert when content contains alerts
$( '.headed_box .alert' ).parent().closest( '.headed_box' ).delay( 200 ).addClass( 'alert' ) ;


/*********************************************************/
/** Bring common functionality together onDocumentReady **/
/*********************************************************/

// Load ops_page_tooltip functionality
$( function() {
    /** Lock submit buttons on click **/
    $(':submit:not(.no-lock)').lockSubmit({
        //  submitText: "Please Wait...",
        onClickCSS: "locked"
    });

    /** Setup the live search functionality: **/
    ops_page_livesearch();
    
    /** Indicate to DOM if using a mobile & touch-based device **/
    
    document.body.classList.toggle('is-mobile-device', isMobileDevice());
	
	// Highlight error on form fields. Click field to dismiss highlight. 
	document.querySelectorAll('td.error :is(input, textarea, select, .ops_form_element_signature, .dropzone)').forEach(elem => {
		elem.classList.add('field-error');
		elem.addEventListener('click', () => {
			elem.closest('td.error').querySelectorAll('.field-error').forEach(fieldErr => {
				fieldErr.classList.remove('field-error');
			});
		});
	});
});

// Smoothly scroll to an anchor on the same page.  Automatically applies to any anchor tag.
$(function() {
    $('a[href*="#"]:not([href="#"], [href="#content"])').click(function() {
        if (location.pathname.replace(/^\//,'') === this.pathname.replace(/^\//,'') && location.hostname === this.hostname) {
            var target = $(this.hash);
            target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
            if (target.length) {
                $('html, body').animate({
                    scrollTop: target.offset().top
                }, 1200, 'easeInOutCubic');
                return false;
            }
        }
    });
});

// Sliding reveal bars functionality
$( function() {
    $( ".reveal_bars > div" ).click( function(){
        $(this).children().eq(0).slideToggle() ;
    });
}) ;

// Automatically cancel unfinished ajax requests
// when the user navigates elsewhere.
// http://stackoverflow.com/questions/1802936/stop-all-active-ajax-requests-in-jquery
(function($) {
	var xhrPool = [];
	
	$(document).ajaxSend(function(e, jqXHR, options){
		xhrPool.push(jqXHR);
	});
	
	$(document).ajaxComplete(function(e, jqXHR, options) {
		xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
	});
	
	var abort = function() {
		$.each(xhrPool, function(idx, jqXHR) {
			jqXHR.abort();
		});
	};

	var oldbeforeunload = window.onbeforeunload;
	window.onbeforeunload = function() {
		var r = oldbeforeunload ? oldbeforeunload() : undefined;
		if (r == undefined) {
			// only cancel requests if there is no prompt to stay on the page
			// if there is a prompt, it will likely give the requests enough time to finish
			abort();
		}
		return r;
	} ;
})(jQuery) ;

// Tooltips
function initializeTooltips() {
	// Select all elements with data-tippy-content attribute
	document.querySelectorAll('[data-tippy-content]').forEach(element => {
		// Check if the element already has a Tippy instance
		if (!Object.hasOwn(element, '_tippy')) {
			// Initialize tooltip if it doesn't have one
			tippy(element);
		}
	});
}

$(function () {
	initializeTooltips();
	
	//Fade-out information
	$('.ops_page_info').fadeTo( 3000 , 0 ).slideUp( 500 );
	$('.message.autohide').fadeTo( 2200 , 0 ).slideUp( 500 );

	// Shows a confirm dialogue from '.ops_page_jsify_dialogue_confirm' link
	$('.ops_page_jsify_dialogue_confirm').click(function (event) {
		if ($(this).is(':not(option)')) {
			event.preventDefault();
			createDialogue($(this).attr('href'));
			setDialogueConfirm($(this).attr('title'));
		}
	});

	// Moves dialogue box on scroll
	$(window).scroll(function () {
		positionModalBackground();
	});
    $(window).resize(function () {
        positionModal( $('div.ops_page_modal_instance').length -1);});
                    
	// Replaces blank threadview with message
	$('.ops_threadView_thread').each(function () {
		var rows = $(this).find('tbody > tr');
		if ($(rows).find('.ops_threadView_deleted_description').length == $(rows).length) {
			$(this).replaceWith(
				"<div class='ops_threadView_thread ops_threadView_thread_inactive'>This thread is inactive</div>"
			);
		}
	});

	// Hovering on a form element help icon will highlight the whole element row
	$('.ops_form_table_cell_helpicon, .form .help').hover( function(){
		$(this).closest('tr').addClass( 'ops_form_table_row_helpHighlight' ).addClass( 'help-highlight' );
	}, function(){
		$(this).closest('tr').removeClass( 'ops_form_table_row_helpHighlight' ).removeClass( 'help-highlight' );
	});
	
	// Bind modal triggers
	bindModalTrigger($('body'));

	$('.Datagrid_AddRow').on('click', function() {
		let dgCon = $(this).closest('div.datagrid-container').find('> .table-container > table:first-of-type tbody');
		// find last row and clone
		let template = $(this).data('template');
		let formName = $(this).data('id');
		let dgLastRow = dgCon.find('tr:last-child').first();

		if (!template) {
			template = dgCon.find('tr:last-child').first().html();
			$(this).data('template', template);
		}

		let hasDate = $(template).find('.ops_form_element_date');
		if (hasDate) {
			$('.ops_form_element_date').removeClass('hasDatepicker').datepicker('destroy');
		}

		let cell = 0;
		let lastRowId = parseInt(dgLastRow.attr('id'));
		let idRow =  lastRowId+ 1;

		let dgCCC = $(template);
		dgCCC.attr('id', idRow);
		dgCCC.attr('data-db-id', '');
		dgCCC.append(dgCCC);

		// set new IDs
		$(dgCCC).attr('id', idRow);
		$(dgCCC).children('td').attr('data-row', idRow);
		$(dgCCC).find('select option:selected').removeAttr('selected');
		$(dgCCC).find('input[type="text"]:not(.ops_form_element_date),textarea').val('');
		$(dgCCC).find('input[type="checkbox"]:not(.defaultChecked)').removeAttr('checked');
		$(dgCCC).find('input,textarea,select').removeAttr('disabled');
		$(dgCCC).find('input[type=hidden]').each(function(){
			let name = $(this).attr("name");
			name = name.replace(/(\d)_(\d)/, '$1_' + idRow);
			$(this).attr("name", name);
			$(this).attr("id", name + (name.match(/_hidden$/) ? '' : '_hidden'));
			$(this).val("");
		});
		$(dgCCC).find('input:not([type=hidden]),textarea,select').each(function () {
			let ele = $(this);
			let eleName;
			let field = '';

			let tagName = ele.prop("tagName");
			let tagType = ele.prop("type");

			// TODO handle time fields
			switch (true) {
				case tagName === 'TEXTAREA':
				case tagName === 'SELECT':
					field = ele.prop('localName');
					break;
				case tagType === 'hidden':
				case tagType === 'radio':
					field = tagType;
					break;
				default:
					break;
			}

			
			if (field === '') {
				eleName =  formName + '_' + cell + '_' + idRow;
			} else {
				eleName = formName + '_' + cell + '_' + idRow + '_' + field;
			}

			ele.prop('id', 'ops_Form__' + eleName);
			ele.prop('name', 'ops_Form__' + eleName);
			cell += 1;
		});

		dgCon.append(dgCCC);

		// updates the row count so DataGrid will actually process it!
		let table = $(this).closest('form').find('table.datagrid');
		let currentRowcount = table.find('>tbody >tr').length;
		let field = '#' + 'ops_Form__' + formName + '_sd';
		let hidden = $(field).val().split(':');
		hidden[0] = currentRowcount;
		$(field).val( hidden.join(':') );

		if (hasDate) {
			$('input.ops_form_element_date').datepicker('destroy');
			initializeDatePicker();
		}

		let clickFn = 'AddRowClick' + formName;
		if (typeof window[clickFn] === 'function') {
			window[clickFn]();
		}
	});
}) ;

// Offline Warning Message
function checkConnection(){
	//console.log( notifications ) ;

	if( !notificationPanel ) {
		return ;
    }

    if( !navigator ) {
    	return ;
	}

	var nameBroken = "connectionFailed" ;
	var nameLive = "connectionLive" ;

	// Notify connection status
    if( navigator.onLine ) {
    	// If the borked connection alert is present, delete it from the panel collection and notify the user
		// we are back up and running
    	if ( notificationPanel.find( nameBroken ) ) {
    		var message = "You are back online." ;
            notificationPanel.destroy( nameBroken );
            notificationPanel.new( NOTIFICATION_DEFAULT, message, nameLive,
				"/Static/Icons/ui/ux2/appbar-connection-quality-veryhigh.png" ) ;

            $( 'form input[type="submit"][data-temp-disabled="true"]' )
				.removeAttr( 'disabled' )
				.removeAttr( 'data-temp-disabled' )
				.removeAttr( 'title' ) ;
        }
    } else {
    	// The connection is broken or very slow/intermittent
        var message = "You are offline, or on a slow connection. You may not be seeing the most up" +
            "-to-date information, and some pages may be unavailable.  Submitting form data is disabled " +
			"to prevent loss of your work." ;
        notificationPanel.destroy( nameLive );
        notificationPanel.new( NOTIFICATION_ALERT, message, nameBroken,
			"/Static/Icons/ui/ux2/appbar-network-disconnect.png" ) ;

        $( 'form input[type="submit"]:not([temp-disabled="true"])' )
			.attr( 'data-temp-disabled', 'true' )
			.attr( 'disabled', 'disabled' )
			.attr( 'title', 'Disabled when offline' ) ;
    }
}

function initializeDatePicker() {
	// Attach datepicker jQuery UI features to all date elements, including dynamically created
	$('body').on('focus', ".ops_form_element_date", function () {
		$(this).datepicker({
			dateFormat: 'dd-M-yy'
			, gotoCurrent: true
			, changeMonth: true
			, changeYear: true
			, firstDay: 1
			, yearRange: "-100:+10"
		});
	});
}

$(function(){
	if( typeof notificationPanel !== 'undefined' && notificationPanel
		&& typeof navigator !== 'undefined' && navigator
		&& typeof navigator.onLine !== 'undefined' ) {
        setInterval(checkConnection, 1500);
    }

	initializeDatePicker();	
}) ;

document.addEventListener('DOMContentLoaded', () => {
  document.body.addEventListener('change', (e) => {
    const target = e.target;
    if (
      target.matches('input[type="checkbox"][name$="_tegIncluded"]') ||
      target.matches('input[type="checkbox"][name$="_tegIncludedOne"]')
    ) {
      if (target.checked) {
        document.querySelectorAll('input[type="checkbox"][name$="_tegIncluded"], input[type="checkbox"][name$="_tegIncludedOne"]')
          .forEach(cb => {
            if (cb !== target) cb.checked = false;
          });
      }
    }
  });
});
