PageSourceSearch

https://www.smct.org.au/crs-common.js?v1.0

js smct.org.au collected 2026-09-24 09:57:38 UTC 26,751 bytes, 888 lines download raw bytes

1const __errorMessage = 'An unexpected critical error has occurred. Please contact us for assistance.';
2const __applicationEventPortalCriticalError = '2618870d-d424-ec11-b6e6-0022481192d6';
3
4var CRS = window.CRS || {};
5
6CRS.Common = CRS.Common || (function ($, hb, moment) {
7	"use strict";
8
9	// ()
10	var _qs = parseQueryString();
11	registerHandlebarsHelpers();
12
13	// Private
14	function parseQueryString() {
15		var vars = window.location.search.substring(1).split("&");
16		var query_string = {};
17		for (var i = 0; i < vars.length; i++) {
18			var pair = vars[i].split("=");
19			var key = decodeURIComponent(pair[0]);
20			var value = decodeURIComponent(pair[1]);
21			if (typeof query_string[key] === "undefined") {
22				query_string[key] = decodeURIComponent(value);
23			} else if (typeof query_string[key] === "string") {
24				var arr = [query_string[key], decodeURIComponent(value)];
25				query_string[key] = arr;
26			} else {
27				query_string[key].push(decodeURIComponent(value));
28			}
29		}
30		return query_string;
31	}	
32	
33	// Public
34	return {
35		qs: _qs,
36		WhoAmI: whoAmI,
37		ParseQueryString : parseQueryString,
38		ClearDateTimeFieldValue : clearDateTimeFieldValue,
39		SetDateTimeFieldValue   : setDateTimeFieldValue,
40		HandleCriticalError: handleCriticalError,
41		ShowWait                : showWait,
42		HideWait                : hideWait,
43		LockForm: lockform,
44		GetSection              : getSection,
45		AddSectionRow           : addSectionRow,
46		AddSectionCol           : addSectionCol,
47		ToggleSection           : toggleSection,
48		ToggleTab               : toggleTab,
49		ToggleButton            : toggleButton,
50		ToggleField             : toggleField,
51		ToggleFieldDescription  : toggleFieldDescription,
52		ShowWait: showWait,
53		HideWait: hideWait,
54        HideTabTitle: hideTabTitle,
55        ShowTabTitle: showTabTitle,
56        DisplayErrorDialog: displayErrorDialog,
57		DisplayConfirmDialog: displayConfirmDialog,
58		AddPageValidator: addPageValidator,
59		DisplayErrorMessages: displayErrorMessages,
60        DisableGridButtons      : disableGridButtons,
61        DisableGridItemActions  : disableGridItemActions,
62        DisableSubmitButton     : disableSubmitButton,
63        EnableSubmitButton      : enableSubmitButton,
64		AddFormLinkButton: addFormLinkButton,
65		AddFormButton: addFormButton,
66		CallCustomApi: callCustomApi,
67		ProgressModalShow: progressModalShow,
68		ProgressModalRemove: progressModalRemove,
69		DownloadAnnotation: downloadAnnotation,
70		AppendNewRowToSection: appendNewRowToSection,
71		GetFormEntityRef: getFormEntityRef
72	};
73
74	function whoAmI() {
75		var me;
76		
77		$.ajax({
78			method: 'GET',
79			url: '/api/whoami',
80			data: {},
81			async: false,
82			fail: function(data) {
83				DisplayErrorDialog('Error!', __errorMessage);
84				console.log(data);
85			},
86			success: function(data) {
87				me = data.results;
88			}
89		});
90		
91		return me;
92	}
93	
94	function clearDateTimeFieldValue(fieldId) 
95	{
96		var $submitField = $("#" + fieldId);
97		var $displayField = $submitField.nextAll(".datetimepicker").children("input");
98
99		$submitField.val('');
100		$displayField.val('');
101	}
102  
103	function setDateTimeFieldValue(fieldId, dateValue) {
104		var $submitField = $("#" + fieldId);
105		var $displayField = $submitField.nextAll(".datetimepicker").children("input");
106		var dateFormat = $displayField.attr("data-date-format");
107
108		$submitField.val(moment.utc(dateValue).format("YYYY-MM-DDTHH:mm:ss.SSSSSSS"));
109		$displayField.val(moment(dateValue).format(dateFormat));
110	}
111
112	function showWait() 
113	{
114		$('div[data-name^="tab_wait"]').show();
115	}
116
117    function hideTabTitle(TabName)
118    {
119        let location = $("div[data-name^='" + TabName + "']");
120        $(location).prev("h2.tab-title").hide();
121    }
122
123    function showTabTitle(TabName)
124    {
125        let location = $("div[data-name^='" + TabName + "']");
126        $(location).prev("h2.tab-title").show();
127    }
128
129
130	function hideWait() 
131	{
132        alert("Hiding Wait");
133        hideTabTitle("tab_wait");
134		$('div[data-name^="tab_wait"]').hide();
135	}
136
137	function lockform() 
138	{
139        //alert('In Lock Form');
140        // NOTE: Disabled fields are excluded from submitted Form Data, so use read-only instead
141		$("#EntityFormPanel").find("input").attr("readonly", true);
142		$("#EntityFormPanel").find("textarea").attr("readonly", true);
143
144        // Select controls don't have a read-only state; however bootstrap applies styling
145		$("#EntityFormPanel").find("select").attr("readonly", true);
146        $("#EntityFormPanel").find("option:not([selected])").attr("disabled", true);
147
148        // Radio buttons don't have a read-only state; fake by disabling non-selected radio buttons
149        $("#EntityFormPanel").find("input:radio:not(:checked)").attr("disabled", true);
150
151        // Checkboxes must be disabled
152        $("#EntityFormPanel").find("input[type='checkbox']").attr("disabled", true);
153
154        // Disable all buttons
155		$("#EntityFormPanel").find("button:not([aria-label='Close'])").attr("disabled", true);
156
157        // Hide Update Button
158        $("#UpdateButton").attr("disabled", true);
159
160        // Disable datetime pickers
161        $(".datetimepicker span[role='button']").attr("disabled",true);
162	}
163
164    function disableGridButtons() {
165        $('.subgrid').on("loaded",function() {
166            // Disable buttons
167            $("a.btn").addClass("disabled").attr("disabled", "disabled");
168        });
169    }
170
171    function disableGridItemActions(titles) {
172        $('.subgrid').on("loaded",function() {
173            $(".subgrid .dropdown-menu a").filter((i, e) => {
174                return titles.includes(e.title);
175            })
176            .attr("disabled", "disabled")
177            .addClass("disabled");
178        });
179    }
180
181    function disableSubmitButton() {
182        $("input.submit-btn[type='button']").addClass("disabled");
183        $("input.submit-btn[type='button']").prop("disabled", true);
184    }
185
186    function enableSubmitButton() {
187        $("input.submit-btn[type='button']").removeClass("disabled");
188        $("input.submit-btn[type='button']").prop("disabled",fal
188se);
189    }
190
191
192	function getSection(SectionName)
193	{
194		let field = $("table[data-name='" + SectionName + "']");
195		if (field.length === 0) { console.warn("Element '" + SectionName + "' not found"); return; }
196		let fieldset = field.parent("fieldset");
197		if (fieldset.length === 0) { console.warn("Element Parent not found"); return; }
198
199		return fieldset;
200	}
201
202	function addSectionRow($section)
203	{
204		if ($section)
205		{
206			$section.find("tbody").append("<tr></tr>");
207			return $section.find("tr").last();
208		}
209	}
210
211	function addSectionCol($row, colSpan)
212	{
213		if ($row)
214		{
215			$row.append("<td colspan='" + colSpan + "' rowspan='1' class='clearfix cell picklist-cell'></td>")
216			return $row.find("td").last();
217		}
218	}
219
220	function toggleSection ({ SectionName="", Visible=true, Animation=null }) 
221	{
222		var section = getSection(SectionName);
223		if (section) 
224		{
225			if (Visible) { section.show(Animation); }
226			else { section.hide(); }
227		}
228	}
229
230	function toggleTab ({ TabName="", Visible=true })
231	{
232		let tab = $("div[data-name^='" + TabName + "']");
233		let tabTitle = tab.prev("h2");
234
235		if (Visible) 
236		{
237			tab.show();
238			tabTitle.show();
239		}
240		else 
241		{
242			tab.hide();
243			tabTitle.hide();
244		}
245	}
246
247	function toggleButton({ButtonName="", Visible=true}) 
248	{
249		var buttons = $("button").filter(function() { return  $(this).text() === ButtonName });
250
251		if (Visible) {
252			buttons.show();
253		}
254		else {
255			buttons.hide();
256		}
257	}
258
259	function toggleField({FieldName="", Visible=true}) 
260	{
261		var elements = $("#" + FieldName).closest("td").children();
262
263		if (Visible) {
264			elements.show();
265		}
266		else {
267			elements.hide()
268		}         
269	}
270
271	function toggleFieldDescription({FieldName="", Visible=true}) 
272	{
273		var elements = $("#" + FieldName).closest("td").children(".description");
274
275		if (Visible) {
276			elements.show();
277		}
278		else {
279			elements.hide()
280		} 
281	}
282
283	function handleCriticalError(err) {
284		if (!err) throw new Error('Error parameter not provided.'); 
285		
286		var errorMessage = err.message + (err.stack ? '\n\n' + err.stack : '');
287		var me = whoAmI();
288		if (me && me.webroles.length > 0) {
289			var entity = {};
290			entity["[email protected]"] = "/cpc_applicationevents(" + __applicationEventPortalCriticalError + ")";
291			entity.cpc_raisedon = new Date().toISOString();
292			entity["[email protected]"] = "/contacts(" + me.id + ")";
293			entity.cpc_summary = "JavaScript Critical Error";
294			entity.cpc_eventtext = errorMessage;
295
296			/*
297			webapi.safeAjax({
298				type: "POST",
299				url: "/_api/cpc_applicationeventlogs",
300				contentType:"application/json",
301				data: JSON.stringify(entity),
302				success: function(res, status, xhr) {
303					console.log("entityID: " + xhr.getResponseHeader("entityid"))
304				}
305			});
306			*/
307		}
308		debugger;
309		console.log(errorMessage);
310		alert(__errorMessage);
311		window.location.href = '/';
312	}
313
314	function registerHandlebarsHelpers() {
315		hb.registerHelper('newlineToBr', function(txt) {
316			txt = txt.replace(/\\r/g, "<br/>");
317			txt = txt.replace(/\\n/g, "<br/>");
318			return new hb.SafeString(txt);
319		});
320		
321		hb.registerHelper('ifEquals', function(arg1, arg2, options) {
322			return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
323		});
324
325		hb.registerHelper('ifNotEquals', function(arg1, arg2, options) {
326			return (arg1 != arg2) ? options.fn(this) : options.inverse(this);
327		});
328
329		hb.registerHelper('makeCssClass', function(txt) {
330			txt = txt.toLowerCase();
331			txt = txt.replace(/ /g, '-');
332			txt = txt.replace(/\(/g, '');
333			txt = txt.replace(/\)/g, '');
334			return new hb.SafeString(txt);
335		});
336		
337		Handlebars.registerHelper('switch', function(value, options) {
338		  this.switch_value = value;
339		  return options.fn(this);
340		});
341
342		Handlebars.registerHelper('case', function(value, options) {
343		  if (value == this.switch_value) {
344			return options.fn(this);
345		  }
346		});
347
348		Handlebars.registerHelper('default', function(value, options) {
349			return true; ///We can add condition if needs
350		});		
351	}
352
353	function showWait() {
354		$('div[data-name^="tab_wait"]').show();
355	}
356
357	function hideWait() {
358		$('div[data-name^="tab_wait"]').hide();
359	}
360
361	function displayErrorDialog(title, message) {
362		if (!title) throw new Error('Title parameter not provided.'); 
363		if (!message) throw new Error('Message parameter not provided.'); 
364
365		var modalError = $('#ModalError');
366		var templateSource = $("#modal-error-template").html();
367		var template = hb.compile(templateSource);
368		var templateData = {
369				"title": title,
370				"message": message
371			};
372		modalError.html(template(templateData));
373		modalError.modal({
374				backdrop: 'static',
375				keyboard: false
376			});
377	}
378
379	function displayConfirmDialog(title, message, confirmFn, cancelFn) {
380		if (!title) throw new Error('Title parameter not provided.'); 
381		if (!message) throw new Error('Message parameter not provided.'); 
382		if (!confirmFn) throw new Error('Confirmation function parameter not provided.'); 
383		if (!cancelFn) throw new Error('Cancel function parameter not provided.'); 
384
385		var modalConfirm = $('#ModalConfirm');
386		var templateSource = $("#modal-confirm-template").html();
387		var template = hb.compile(templateSource);
388		var templateData = {
389				"title": title,
390				"message": message
391			};
392		modalConfirm.html(template(templateData));
393		modalConfirm.modal({
394			backdrop: 'static',
395			keyboard: false
396		})
397		$("#modal-confirm-yes").on('click', confirmFn);
398		$("#modal-confirm-no").on('click', cancelFn);			
399	}
400	
401	function addPageValidator(newValidator) {		
402		if (typeof (Page_Validators) != 'undefined') {
403			
404			if (!newValidator) throw new Error('Validator parameter not provided.'); 
405			if (!newValidator.id) throw 'Validator ID parameter not provided.';
406			if (!newValidator.controltovalidate) throw 'Control to validate for ' + newValidator.id + ' parameter not provided.';
407			if (!newValidator.errormessage) throw 'Error message for ' + newValidator.id + ' parameter not provided.';
408			if (!newValidator.evaluationfunction) throw 'Evaluation function for ' + newValidator.id + ' parameter not provided.';
409
410			var newPageValidator = document.createElement('span');
411			newPageValidator.style.display = "none";
412			newPageValidator.id = newValidator.id;
413			newPageValidator.controltovalidate = newValidator.controltovalidate;
414			newPageValidator.errormessage = "<a href='#" + newValidator.controltovalidate + "_label'>" + newValidator.errormessage + "</a>";
415			newPageValidator.evaluationfunction = newValidator.evaluationfunction;
416			Page_Validators.push(newPageValidator);
417		 
418			$("a[href='#" + newValidator.controltovalidate + "_label']").on("click", function () { 
419				scrollToAndFocus(newValidator.controltovalidate + '_label', newValidator.controltovalidate);
420			});			
421		}
422	}
423	
424	function displayErrorMessages(messageJSON) {
425		if (!messageJSON) throw new Error('messageJSON parameter not provided.'); 
426
427		var messages = JSON.parse(messageJSON);
428		if (messages) {
429			try {
430				var templateSource = $("#validation-errors-template").html();
431				var template = hb.compile(templateSource);
432				var templateData = {
433					"messages": messages
434				};
435				$('.validation-summary').html(template(templateData));
436				$('.validation-summary').show();
437				$('html, body').animate({
438						scrollTop: $("#ValidationSummaryEntityFormView").offset().top
439					});
440			} catch(err) {
441				alert(err);
442			}
443		}
444	}
445	
446	function addFormLinkButton(options) {
447		var actionContainer = $(`.form-action-container-${options.position}`);
448		if (actionContainer.length > 0) {
449			var button = $(`<a class="btn btn-lightgreen" href="${options.url}" target="${options.target ?? ''}">${options.label}</a> `);
450            actionContainer.append(button);
451			button.before(" ");
452			button.after(" ");
453			return;
454		}
455
456		actionContainer = $(`.actions > div`);
457		if (actionContainer.length > 0) {
458			var button = $(`<div role="group" class="btn-group entity-action-button"><a class="btn btn-lightgreen" href="${options.url}" target="${options.target ?? ''}">${options.label}</a></div>`);
459			actionContainer.append(button);
460			return;
461		}
462	}
463
464	function addFormButton(options) {
465		var actionContainer = $(`.form-action-container-${options.position}`);
466        if (actionContainer.length == 0) {
467            var actionBar = $(`<div class="row crs-custom-actions">
468                <div class="col-sm-6 clearfix">
469                    <div class="form-action-container-left">
470                    </div>
471                </div>
472                <div class="col-sm-6 clearfix">
473                    <div class="form-action-container-right">
474                    </div>
475                </div>
476            </div>`);
477            $("#EntityFormPanel").append(actionBar);
478            actionContainer = $(`.form-action-container-${options.position}`);
479        }
480
481		var button = $(`<a class="btn btn-lightgreen" href="#">${options.label}</a> `);
482		button.on('click', options.onClick);
483		actionContainer.append(button);
484		button.before(" ");
485		button.after(" ");
486	}
487
488	function callCustomApi(apiName, apiParameters, cbSuccess, cbError) {
489
490		var params = JSON.stringify(apiParameters)
491		var url = `/_api/crs_advancedqueries?$select=crs_apiresponse&$filter=(crs_api eq '${apiName}' and crs_requestparameters eq '${encodeURIComponent(params)}')`;
492
493		$.ajax({
494			method: "GET",
495			url: url,
496			async: true
497		})
498		.success(function(data) {
499			if (cbSuccess && data) {
500				cbSuccess(JSON.parse(data.value[0].crs_apiresponse));
501			}
502		})
503		.error(function(data, status, error) {
504			console.log(data.response);
505			if (cbError) {
506				cbError(data,status,error);
507			}
508		});
509	}
510
511	function appendNewRowToSection(sectionName, rowId, columns) {
512
513		var tds = "";
514		for (var i = 0; i < columns; i++) {
515		tds += `<td colspan="1" rowspan="1" class="clearfix cell form-control-cell">`;
516		}
517		let row = $(`<tr id=${rowId}>${tds}<td  class="clearfix cell form-control-cell"></td></tr>`)
518
519		$(`table[data-name="${sectionName}"] > tbody`).append(row);
520	}
521
522	function progressModalShow(name) {
523		$("body").append(`<div class="wait wait-progress"><div class="center-block">${name}</div><div><figure class="c-loader"><span class="c-loader__label">Loading …</span></figure></div></div>`);
524	}
525
526	function progressModalRemove(id) {
527		$(`.wait-progress`).remove();
528	}
529
530	function downloadAnnotation(id, fileName) {
531		const downloadLink = document.createElement('a');
532		downloadLink.href = `/_entity/annotation/${id}`;
533		downloadLink.download = `${fileName}`;
534		document.body.appendChild(downloadLink);
535		downloadLink.click();
536	}
537
538	function getFormEntityRef() {
539      return {
540            table: $(`input[id$='EntityFormView_EntityName']`).val(),
541            id: $(`input[id$='EntityFormView_EntityID']`).val()
542        };
543    }
544	
545})($, Handlebars, moment);
546
547/*
548** Annotation
549*/
550
551CRS.Common.Wizard = CRS.Common.Wizard || (function (c, $, hb) {
552	"use strict";
553	
554	var _isRedirecting = false;
555
556	// Events
557	function onClickWizardStep (event) {
558		var record = $(this).data("record");
559
560		if ($('.dirty').length > 0) {
561			c.DisplayConfirmDialog('Unsaved changes', 'Are you sure you want to continue?', () => goToWizardStep(record), undefined);
562		} else {
563			goToWizardStep(record);
564		}
565		event.preventDefault();
566	}
567
568	function saveAndExitButton(event) {
569		startSaveTimer();
570		if (typeof(Storage) !== "undefined") sessionStorage.gohome = 'true';
571		$('#UpdateButton').click();
572		event.preventDefault();
573	}
574
575	function saveButton(event) {
576		startSaveTimer();
577		$('#UpdateButton').click();
578		event.preventDefault();
579	}
580	
581	function previousButton(event) {
582		startSaveTimer();
583		let currentIndex = $('#wizard li').index($('#wizard a.current').parent());
584		let previousRecord = $(`#wizard > ul > li:nth-child(${currentIndex}) > a`).data('record');
585		if (previousRecord) {
586			$("#cg_currentwizardstep").val(previousRecord.stepid ?? '');
587			$("#cg_currentwizardstep_name").val(previousRecord.stepid ?? '');
588			$("#cg_currentwizardstep_entityname").val('cg_wizardpagedefinition');
589		}
590
591		$('#UpdateButton').click();
592		event.preventDefault();
593	}	
594
595	function nextButton(event) {
596		startSaveTimer();
597		let currentIndex = $('#wizard li').index($('#wizard a.current').parent());
598		let nextRecord = $(`#wizard > ul > li:nth-child(${currentIndex + 2}) > a`).data('record');
599
600		$("#cg_currentwizardstep").val(nextRecord ? nextRecord.stepid : '');
601		$("#cg_currentwizardstep_name").val(nextRecord ? nextRecord.stepid : '');
602		$("#cg_currentwizardstep_entityname").val('cg_wizardpagedefinition');
603
604		$('#UpdateButton').click();
605		event.preventDefault();
606	}	
607
608	function submitAsFinalButton(event) {
609		startSaveTimer();
610
611		$("#cg_currentwizardstep").val('0f126a06-14cf-ef11-8ee9-002248982116');
612		$("#cg_currentwizardstep_name").val('0f126a06-14cf-ef11-8ee9-002248982116');
613		$("#cg_currentwizardstep_entityname").val('cg_wizardpagedefinition');
614
615		$('#UpdateButton').click();
616		event.preventDefault();
617	}	
618	
619	function close(event) {
620		c.DisplayConfirmDialog("Are you sure?", "Are you sure you want to quit? \nAll unsaved changes will be lost.", confirmClose, cancelClose);
621	}	
622		
623	// Private
624	function goToWizardStep(record) {
625
626		if (!record) throw 'Record parameter not provided.'; 
627		if (!record.entityplural) throw 'Record entity plural parameter not provided.';
628		if (!record.id) throw 'Record id parameter not provided.';
629		if (!record.stepid) throw 'Record step id parameter not provided.';
630
631		c.ShowWait();
632
633		let wpdColumn = "cg_CurrentWizardStep";
634
635		webapi.safeAjax({
636			type: "PATCH",
637			contentType: "application/json",
638			url: `/_api/${record.entityplural}(${record.id})`,
639			data: `{"${wpdColumn}@odata.bind":"/cg_wizardpagedefinitions(${record.stepid})"}`,
640			success: function (data, textStatus, xhr) {
641				console.log("Record updated");
642				location.reload();
643			},
644			error: function (xhr, textStatus, errorThrown) {
645				console.log(xhr);
646				c.HideWait();
647			}
648		});
649
650	}
651
652	function startSaveTimer() {
653
654        // Start timer
655        var timer = setInterval(function() {
656           
657			c.ShowWait();
658            if ($('.validation-summary, .modal').is(':visible')) {
659                
660                // Stop timer
661                c.HideWait();
662                clearInterval(timer);
663                
664            }
665            
666        }, __validationPollMilliseconds);	
667		
668	}
669	
670	function confirmClose() {
671		window.location.href = '/';
672	}
673	
674	function cancelClose() {
675	}
676	
677	function configureFormActions() {
678		let currentIndex = $('#wizard li').index($('#wizard a.current').parent());
679		let maxStep = $('#wizard li').length;
680		
681		if (currentIndex <= 0) $('#PreviousButton').hide();
682		if (currentIndex >= (maxStep - 1)) {
683            $('#NextButton').hide();
684            $('#SubmitFinalButton').show();
685        } else {
686            $('#NextButton').show();
687            $('#SubmitFinalButton').hide();
688        }
689	}
690	
691	function initialise() {
692		
693        alert("Initialising Wizard");
694		// Check for gohome 
695		//if (typeof(Storage) !== "undefined") {
696		//	if (sessionStorage.gohome == 'true') {
697		//		sessionStorage.gohome = undefined;
698		//		_isRedirecting = true;
699		//		window.location.href = '/';
700		//	}
701		//}
702
703		if ($('#EntityFormPanel').length > 0) {
704
705            // Configure wizard
706            $('#wizard a').click(onClickWizardStep);
707			
708			// Configure buttons
709			configureFormActions();
710			$('#SaveButton').click(saveButton);
711			$('#SaveAndExitButton').click(saveAndExitButton);
712			$('#PreviousButton').click(previousButton);
713			$('#NextButton').click(nextButton);
714            $('#SubmitFinalButton').click(submitAsFinalButton);
715			
716            // Configure form actions
717			$('#FormActions').css('visibility', 'visible');
718
719            // Hide wait
720            CRS.Common.HideWait();
721		}
722	}
723
724	/* PUBLIC FUNCTIONS 
725	**************************************************************************/
726	return {
727		IsRedirecting : () => _isRedirecting,
728		Initialise : initialise,
729		OnClickWizardStep : onClickWizardStep,
730		GoToWizardStep : goToWizardStep
731	};
732
733})(CRS.Common, $, Handlebars);	
734
735
736CRS.Common.Profile = (function (c, $, hb, moment) {
737  "use strict";
738
739  return {
740	Initialise: initialise
741  };
742  
743  function initialise() {
744    showHideSubmit();
745    $("#crs_hasagreedtoportaltandcs_1").on("change", showHideSubmit);
746    $("#crs_hasagreedtoportaltandcs_0").on("change", showHideSubmit);
747  }
748
749  function showHideSubmit() {
750    console.log(crs_hasagreedtoportaltandcs_1.checked);
751	if(!crs_hasagreedtoportaltandcs_1.checked)
752    {
753        c.DisableSubmitButton();
754    }
755    else
756    {
757        c.EnableSubmitButton();
758    }
759  }
760
761})(CRS.Common, $, Handlebars, moment);  
762	
763
764CRS.Common.Annotation = (function (c, $, hb, moment) {
765  "use strict";
766  var _annotations;
767
768  hb.registerHelper('debug', function(row) {
769	return new row;
770  });
771  
772  return {
773	Initialise: initialise
774  };
775  
776  function initialise(objectid, subject) {
777	getData(objectid, subject);
778	displayAnnotations(objectid);
779  }
780  
781  function getData(objectid, subject) {
782	var data = { "objectid": objectid };
783	if (!!subject) {
784	  data["subject"] = subject;
785	}
786
787	$.ajax({
788	  method: "GET",
789	  url: "/api/annotation/",
790	  data: data,
791	  async: false
792	})
793	.fail(function(data) {
794     
795	  CRS.Common.DisplayErrorDialog("Error!", data);
796	  console.log(data);
797	})
798	.done(function(data) {
799	  _annotations = data.results;
800	});   
801  }
802  
803  function displayAnnotations(objectid) {
804	if (_annotations) {
805      // If #annotation-template doesn't exist its probably because we're in a modal so try grabbing from parent.
806	  var templateSource = $("#annotation-template").html() || parent.$("#annotation-template").html();
807	  var template = hb.compile(templateSource);
808	  var templateData = {
809		"objectid": objectid,
810		"annotation": _annotations
811	  };
812	  $('table[data-name="tab_section_annotations"]').html(template(templateData));
813	}
814  }
815  
816})(CRS.Common, $, Handlebars, moment);  
817
818/*
819** Stored Documents
820*/
821CRS.Common.StoredDocuments = (function (c, $, hb, moment) {
822  
823    "use strict";
824
825    var _storedDocumentTypes = [];
826
827    return {
828        InitialiseForm: initialiseForm
829    };
830    
831    function initialiseForm() 
832    {    
833        //console.log("Docs Debug #1009");
834        var queryString = c.ParseQueryString();
835        //console.log("Query String [refid]:" + queryString.refid);
836        getDocumentTypes(queryString.refid);
837        //console.log("Found " + _storedDocumentTypes.length + " document options.");
838
839        c.ToggleSection({ SectionName: "tab_document_section_other", Visible: false });
840        $("#cpc_storeddocumenttype option").each(function(index) 
841        {
842            //console.log("Checking " + index + "(" + this.value + ")");
843            if(this.value != '' && _storedDocumentTypes.indexOf(this.value) == -1) this.remove(index);
844        }); 
845
846        $("#cpc_storeddocumenttype" ).change(function() 
847        {
848            var documentType = this.selectedOptions[0].text;
849            if (documentType === "Other") 
850            {
851                c.ToggleSection({ SectionName: "tab_document_section_other", Visible: true });
852                $("#subject").val("");
853            } else 
854            {
855                c.ToggleSection({ SectionName: "tab_document_section_other", Visible: false });
856                $("#subject").val(documentType);
857            }
858        });
859
860        c.HideWait();
861    }
862   
863    function getDocumentTypes(id) 
864    {
865        if (id) 
866        {
867            $.ajax({
868              method   : "GET",
869              url      : "/api/crs_storeddocumenttype/",
870              data     : {"id" : id},
871              async    : false
872            })
873            .fail(function( data ) 
874            {
875                CRS.Common.DisplayErrorDialog("Error!", data);
876                console.log(data);
877            })
878            .done(function( data ) 
879            {
880                for (var i=0; i < data.results.length; i++) 
881                {
882                    _storedDocumentTypes.push(data.results[i].crs_storeddocumenttypeid);
883                }
884            });     
885        }
886    }
887  
888})(CRS.Common, $, Handlebars, moment);  

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.