function enableDataTablesAndRedrawSummaryTable() {

	//if previous search results in the DataTable enabled wrapper exist, clear them
	if ($('#pncsDtSearchResultsWrapper').size() > 0) {
		$('#pncsDtSearchResultsWrapper').remove();	}

	//Initialize the DataSet that will hold the input Data for the DataTables
	//We use a JS sourced DataSet rather than direct enablement on the DOM since
	//a direct enablement fails due to the presence of empty table rows added by
	//Orbeon's standard markup. The original result set DOM Table is hidden -
	//events on clicks of multiple rows in the modified/DataTable enabled rows
	//are passed on to the original result set DOM Table.
	var dataSet = [];
	$("[class*='fr-summary-row']").add("[class*='pncs-form-template-listing-row']").each(function() {
	//$("[class*='fr-summary-row']").each(function() {
				//For each summary result set row, extract the data and add to the dataSet
				var arrayRow = [];

				var currentRowClass = $(this).attr('class');

				//alert('Iteration over rows of data before enabling Datatable row data is'+$(this).html());


				if(currentRowClass.indexOf('pncs-form-template-listing-row')<0){
					//Create checkboxes in the DataTable enabled table that will have their click events
					//trigger clicks on the underlying original ResultSet. Note the data-reference-sel
					//attribute on the created checkboxes that hold a reference to the corresponding
					//underlying table's checkbox source.
					var formRowSelectorRef = $(this).find("input:checkbox").attr('name');
					if (formRowSelectorRef != undefined) {
						var referencerHtml = '<input type="checkbox" class="fsDocSelector" name="'+ formRowSelectorRef
								+ '_frowSelectorRef" data-reference-sel="'
								+ formRowSelectorRef + '" value="0"/>';
						arrayRow.push(referencerHtml);
					}
				}else{
					//For the MPN Form RUnner template library form, copy the checkbox over and delete the underlying DOM element
					//This is done to ensure that the Select and Operation menus continue to work on the same
					//UI elements bound to the instance/select nodes in the model

					if($(this).find("td.fr-home-select").size()==0){
						location.reload();
						return;
					}
					$(this).find("td.fr-home-select").each(function(){

						if($(this).find("span.xforms-disabled").size()==0){
							arrayRow.push($(this).html());
							$(this).remove();
						}


					});
				}

				//For all other non checkbox Tds in each row, find non disabled cells and
				//create an element with an anchor tag surround that will link back to the same
				//target as in the original table cell
				/*$(this).find("td").find("span.xforms-output-output").each(
						function() {
							var parentClass=$(this).parent().attr('class');
							if ((parentClass
									.indexOf('xforms-disabled')) == -1) {
								var linkRef = $(this).parent().parent().attr('href');
								var elementContent = $(this).html();

								//if this is a badge row, carry over styles of parent to the cell added to datatable
								if(((parentClass.indexOf('badge')) >-1)
											||((parentClass.indexOf('label')) >-1))
											{
										elementContent="<span class='"+parentClass+"' >"+elementContent+"</span>";
								}

								if (linkRef != undefined) {
									elementContent = "<a aria-label='Select to view Form ' href='" + linkRef+ "'>" + elementContent + "</a>";
								}

								arrayRow.push(elementContent);
							}
						});*/



				$(this).find("td").each(
						function() {
							var tdCell = $(this);
							var outputSpans = tdCell.find("span.xforms-output-output");
							var elementContent = "";

							outputSpans.each(function(){
								var parentClass=$(this).parent().attr('class');
								if ((parentClass
										.indexOf('xforms-disabled')) == -1) {
									var linkRef = $(this).parent().parent().attr('href');
									var spanContent = $(this).html();
									var spanText = $(this).text();

									//if this is a badge row, carry over styles of parent to the cell added to datatable
									if(((parentClass.indexOf('badge')) >-1)
												||((parentClass.indexOf('label')) >-1))
												{
										spanContent="<span class='"+parentClass+"' >"+spanContent+"</span>";
									}

									if (linkRef != undefined) {

										if(linkRef == "#"){
											spanContent= "<a aria-label='"+spanText+". No Link available to view Form since it is Unavailable.' href='" + linkRef+ "'>" + spanContent + "</a>";
										}else{
											spanContent= "<a aria-label='"+spanText+". Link. Select to view form.' href='" + linkRef+ "'>" + spanContent + "</a>";
										}

									}
									elementContent=elementContent+spanContent;

								}
							});

							if(elementContent.length>0){
								arrayRow.push(elementContent);
							}
						});



				//Push back the reconstructed arrayRow into the dataSet
				if(currentRowClass.indexOf('xforms-repeat-template')<0){
					dataSet.push(arrayRow);
				}

			});



	if($('div.fr-summary-table-div').size()>0){
		//Construct the wrapper div and reconstructed dataset holder table which will hold the reconstructed dataset. Add it to a span immediately below the Filter criteria form
		$('span.fr-summary-search')
				.append('<div id="pncsDtSearchResultsWrapper"> <table class=" table table-bordered table-condensed" id="pncsDtSearchResults"></table></div>');

	}

	if($('table.pncs-form-template-listing').size()>0){
		//Construct the wrapper div and reconstructed dataset holder table which will hold the reconstructed dataset. Add it to a span immediately below the Filter criteria form
		$('table.pncs-form-template-listing').parent().parent().
		append('<div id="pncsDtSearchResultsWrapper"> <table class=" table table-bordered table-condensed" id="pncsDtSearchResults"></table></div>');

	}


	//Setting the Datatable enablement defaults for the summary list on Form Builder page
	 var colsArr = [ {	"title" : " "},
		              {	"title" : "Created"	},
		              {	"title" : "Modified"},
		              {	"title" : "Current <br/>Version"},
		              { "title" : "Organization"},
		              { "title" : "VA Form ID" },
		              {	"title" : "Display Title"},
		              {	"title" : "Form Description"} //,
		              //{	"title" : "Link to Document"}
		              ];
	var dateTimeColIndexes = [1,2];
	var defaultSortArr = [ [ 1, "desc" ] ];

	//Overriding the Datatable enablement defaults for the patient history form instances list in Form Runner or The template library summary
	 if($.inArray("builder", $(location).attr('pathname').split("/"))<0){

		 var firstColOrderingOffSwitch =	false;

		 if($('table.pncs-form-template-listing').size()>0){

			 if($("div.adminUserAccessIndicator.xforms-disabled").size()>0){
				 colsArr = [  {	"title" : "Modified","width":"10%"},
					              {	"title" : "Organization","width":"15%"},
					              {	"title" : "VA Form ID","width":"17%"},
					              {	"title" : "Display Title","width":"30%"},
					              { "title" : "Forms Started or Completed","width":"20%"}
					              ];
				  dateTimeColIndexes = [0];
				  defaultSortArr=[ [ 0, "desc" ] ];
				  firstColOrderingOffSwitch=true;



			 }else{

				 colsArr = [ {	"title" : " ","width":"2%"},
				              {	"title" : "Status","width":"8%"	},
				              {	"title" : "Modified","width":"10%"},
				              {	"title" : "Organization","width":"15%"},
				              {	"title" : "VA Form ID","width":"17%"},
				              {	"title" : "Display Title","width":"30%"},
				              { "title" : "Forms Started or Completed","width":"20%"}
				              ];
				  dateTimeColIndexes = [2];
				  defaultSortArr=[ [ 2, "desc" ] ];


			 }

		 }else{
			 colsArr = [ {	"title" : " ","width":"5%"},
			              {	"title" : "Status","width":"10%"	},
			              {	"title" : "Created","width":"35%"},
			              {	"title" : "Modified","width":"35%"},
			              { "title" : "Referenced Version","width":"15%"}
			              ];
			  dateTimeColIndexes = [2,3];
			  defaultSortArr=[ [ 3, "desc" ] ];
		 }

	 }


		//Enable the DataTable on the reconstructed dataSet and set the content on the reconstructed dataset holder table
		$('#pncsDtSearchResults').DataTable({
			"data" : dataSet,
			"columns" : colsArr,
			//Turn off Sort on first row which holds checkboxes for row selection
			"columnDefs" : [ {
				"orderable" : firstColOrderingOffSwitch,
				"targets" : 0
			},
			{
				"type":"pncs-dateTime-html",
				"targets":dateTimeColIndexes
			}

			],
			//Sort by Create Date Desc by default
			"order" : defaultSortArr,
			"drawCallback": afterDrawCallBack,
			//Remove the search filter - removed f - positioned info (showing x of ..) to Top Left, positioned
			// pagination to bottom right, positioned size selector to top right
		     "dom": '<"pncsDtInfo"i><"pncsDtSize"l><t><"pncsPagination"p>',
		     "language": {
		         "emptyTable": "No form data was found based on the criteria selected."
		     }
		});



		if(!firstColOrderingOffSwitch){
			//Workaround for DataTable issue wherein, if no default sort order is specified, the first row is still
			//used for sorts even if explicitly disabled for sorts
			$('#pncsDtSearchResults>thead>tr>th:first-child').removeClass('sorting_asc').addClass('sorting_disabled');
		}


	$("div.pncsDtSize").css('float','right');
	$("div.pncsPagination").css('float','left');


	//Bind the change events on the checkboxes in the reconstructed data set back to the
	//click events on the checkboxes in the underlying dataset.
	$("input[name*='_frowSelectorRef']").change(function() {
		var referedName = $(this).attr('data-reference-sel');
		$("input[name='" + referedName + "']").click();
	});




	//Rebind the checkboxes in the reconstructed data set back to the click events on
	//checkboxes in the underlying dataset. This is needed so on each redraw event such on
	//page changes, the events are rebound.
	$('#pncsDtSearchResults').on( 'draw.dt', function () {

		$("input[name*='_frowSelectorRef']").change(function() {
			var referedName = $(this).attr('data-reference-sel');
			$("input[name='" + referedName + "']").click();
		});


	} );


	//Hide the underlying dataset and pagination controls for the same
	$('span.xforms-update-full').hide();
	$('div.pagination').hide();


	//The server returns data pre sorted by Creation Date already. There is no need to re-sort once data gets
	//back to the client. This is an optimization that works around a major performance issue seen on first time
	//sorts on data table display with large result sets
	//$('#pncsDtSearchResults>thead>tr>th:nth-child(2)').removeClass('sorting').addClass('sorting_desc');

}

function afterDrawCallBack(){
	//Add role of button to pagination controls to fix a 508 issue
	$('div.pncsPagination .paginate_button').attr('role','button');
}

function ajaxFindRequestDone() {

	// An attempt to poll the Orbeon Global indicators for ajax event queues
	// The done callback on the Deferred occurs when we are sure that the event
	// queue has been completed. At this point, the effect of the caller (in our
	// case just the refetching of the results from the server on change of
	// org/filtering ) is completed

	var future = $.Deferred();

	function areWeDoneYet() {
		var requestPending = ORBEON.xforms.Globals.requestInProgress
				|| ORBEON.xforms.Globals.eventQueue.length > 0;
		if (requestPending)
			setTimeout(areWeDoneYet, 100);
		else
			future.resolve();
	}

	setTimeout(areWeDoneYet, 100);
	return future;
}

function onOrgFilterChange() {

	// We always wait for the ajaxian search to complete before we
	// attempt to extract the result set and enable DataTables on the resultset
	ajaxFindRequestDone().done(function() {
		enableDataTablesAndRedrawSummaryTable();
	});



}

function bindOnOrgFilterChangeToControls() {

	// Bind to onChange of select query options
	$('div.fr-search-options').find('select').each(function() {
		if (($(this).parent().attr('class').indexOf('xforms-disabled')) == -1) {
			$(this).on('change', function() {
				onOrgFilterChange();
			});
		}
	});

	// Bind to form submit of filter options
	$('div.fr-search-buttons').find(':button').on('click', function() {
		onOrgFilterChange();
	});


	// Bind to form submit of Delete
	$('body').on('click', 'div[id*="delete-confirmation-dialog"] button:contains("Yes")', function() {
		onOrgFilterChange();
	});

	// Bind to form submit of Copy
	$('span.fr-buttons button:contains("Copy")').on('click', function() {
		onOrgFilterChange();
	});

	//Confirmation Commit dialog confirm button event handler registration
	$('body').on('click', 'div[id*="copy-confirmation-dialog"] button:contains("Yes")', function() {
		onOrgFilterChange();
	});

	//Bind to onClick on Confirmation that the form needs to be published or unpublished on the Form Runner Template lib page
	$('body').on('click', 'div[id*="publish-confirmation-dialog"] div.xbl-fr-alert-dialog-buttons button:contains("Yes")', function() {
		onOrgFilterChange();
	});



}

//Binding an aria-label on the accordion control icons to allow screen readers a friendly text
function bindAriaLabelsToToggleControls($elems){
	$elems.each(function(){
		var headerDivRef = $(this);
		var targetDivHref = $(this).find("accordion-toggle").attr("href");
		$(targetDivHref).each(function(headerDivRef){
			if($(this).hasClass('in')){
				headerDivRef.attr('aria-label','Click or Use the Enter/Space bar keys to Collapse the Section');
			}else{
				headerDivRef.attr('aria-label','Click or Use the Enter/Space bar keys to Expand the Section');
			}
		});
	});
}



$(document)
		.ready(function() {

						if(($('div.fr-summary-table-div').size()>0)||($('table.pncs-form-template-listing').size()>0)){
						//if(($('div.fr-summary-table-div').size()>0)){
							// on first display of the summary form, call the function
							// that will enable the DataTable plugin on the search results.
							onOrgFilterChange();

							// The current search results are cleared on selection of
							// org/submission of filter criteria. On completion of ajax calls to refetch results, the
							// onOrgFilterChange needs to be called again. The call below ensures that for the change event of the
							// organization select and for the click event of the find button the Datatable plugin is
							// re-enabled on the returned result set in the DOM
							bindOnOrgFilterChangeToControls();
						}

					//Binding the enter keypress or spacebar keypress on each section heading to the toggle div click
					$('.accordion-heading').keypress(function(e){
						if((e.which==13)||(e.which==32)){
							$(this).find(".accordion-toggle").click();
						}
					});

					//Apply initial tabindex to buttons.
					$('#accordion').find('.accordion-body.collapse')
						.find(':button')
						.attr('tabindex', '-1');
					$('#accordion').find('.accordion-body.collapse.in')
						.find(':button')
						.attr('tabindex', '0');

					//Setting focus and blur events on the accordion heading div to allow a visual cue to a
					//user who is not visually impaired but who uses the keyboard for navigation due to motor impairment
					 $('#accordion .accordion-heading').focus(function(){
						 //Setting and removing classes not effective due to overrides from other classes on the
						 //bgcolor for the heading. Element style has to be set to override.
						 //$(this).removeClass('toolbarSectionHeadNoFocus');
						 //$(this).addClass('toolbarSectionHeadFocus');
						  $(this).css('background-color','#BDBDBD');
					  });
					  $('#accordion .accordion-heading').blur(function(){
						  $(this).css('background-color','#e4e4e4');
					  });
					  //Ensuring that focus on span/i elements that are within the div, have the same effect as the parent accordion heading element
					  $('#accordion .accordion-heading span').add('#accordion .accordion-heading i').focus(function(){
						  $(this).parents('#accordion .accordion-heading').css('background-color','#BDBDBD');
					  });
					  $('#accordion .accordion-heading span').add('#accordion .accordion-heading i').blur(function(){
						  $(this).parents('#accordion .accordion-heading').css('background-color','#e4e4e4');
					  });

					//Expand all and collapse all function implementation
					$('#toolboxExpandBtn').on('click',	function() {
							if ($(this).text() == 'Expand All') {
								$(this).text('Collapse All');
								$('#accordion .accordion-body').removeAttr('style').removeClass('in').addClass('in');
								//$('#accordion .accordion-heading .accordion-toggle i').removeClass().addClass('accordionToggleIcon icon-chevron-up').attr('aria-label','Click or Use the Enter/Space bar keys to Collapse the Section');
								$('#accordion .accordion-heading .accordion-toggle i').removeClass().addClass('accordionToggleIcon icon-chevron-up');
								//$('#accordion .accordion-heading').attr('aria-label','Click or Use the Enter/Space bar keys to Collapse the Section');

								$('#accordion').find(".fb-tool").each(function(){
								    $(this).find(":button").each(function(){
								    	$(this).attr('tabIndex', 0);
								    });
								});
							} else {
								$(this).text('Expand All');
								$('#accordion .accordion-body')	.removeClass('in');
								//$('#accordion .accordion-heading .accordion-toggle i').removeClass().addClass('accordionToggleIcon icon-chevron-down').attr('aria-label','Click or Use the Enter/Space bar keys to Expand the Section');
								$('#accordion .accordion-heading .accordion-toggle i').removeClass().addClass('accordionToggleIcon icon-chevron-down');
								//$('#accordion .accordion-heading').attr('aria-label','Click or Use the Enter/Space bar keys to Expand the Section');

								$('#accordion').find(".fb-tool").each(function(){
								    $(this).find(":button").each(function(){
								    	$(this).attr('tabIndex', -1);
								    });
								});
							}
							return false;
						});

					//Binding aria-expanded state on divs that are hidden or shown for screen readers using bootstrap events for accordion
					//Also setting tabIdex of 0 or -1 to allow navigation via tabs or suppress depending on state of the accordion
					$('#accordion').on('shown.bs.collapse', function(event) {
						//event.target = accordion-body element.
						$(event.target).parent('.accordion-group')
							.find('.accordion-toggle')
							.attr("aria-expanded", "true");
						$(event.target)
							.find('.fb-tool')
							.attr("aria-hidden", "false");
						$(event.target)
							.find(':button')
							.attr("tabindex", "0");
						$(event.target).parent('.accordion-group')
							.find('.screen-reader-only')
							.text("Activate to Collapse");
						$(event.target).prev()
							.find('i')
							.removeClass()
							.addClass('accordionToggleIcon icon-chevron-up');
					});


					$('#accordion').on('hidden.bs.collapse', function(event) {
						//event.target = accordion-body element.
						$(event.target).parent('.accordion-group')
							.find('.accordion-toggle')
							.attr("aria-expanded", "false");
						$(event.target)
							.find('.fb-tool')
							.attr("aria-hidden", "true");
						$(event.target)
							.find(':button')
							.attr("tabindex", "-1");
						$(event.target).parent('.accordion-group')
							.find('.screen-reader-only')
							.text("Activate to Expand");
						$(event.target).prev()
							.find('i')
							.removeClass()
							.addClass('accordionToggleIcon icon-chevron-down');
					});


				$("li[id*='dialog-control-details'] a[id*='dialog-control-details']").on('shown.bs.tab', function (e) {

					//Binding aria- attributes to the tabs for bootstrap navs
					//The each is called on first tab activation- Todo: Move to dialog activation for control settings dialog
					$("li[id*='dialog-control-details'] a[id*='dialog-control-details']").each(function(){

						  var controlledDivId = $(this).attr('href');
						  if((controlledDivId.length>0)&&(controlledDivId.indexOf("#")==0)){
							  $(this).attr('aria-controls',controlledDivId.substring(1));
							  $(''+controlledDivId).attr('aria-labelledby',$(this).attr('id'));
						  }

					});

				  if(e.target){
				      var eventTarget = $(e.target);
				      eventTarget.attr('aria-selected','true');
				      var titleTxt = eventTarget.find('span.xforms-output-output').text();
				      if(titleTxt.length>0){
				    	  eventTarget.attr('title',titleTxt+' Selected ');
				      }
				       var controlledDivId = eventTarget.attr('href');
				       if((controlledDivId.length>0)&&(controlledDivId.indexOf("#")==0)){
				    	   $(''+controlledDivId).attr('aria-hidden','false');
				    	   $(''+controlledDivId+' *:enabled').first().focus();
				    	   //$(''+controlledDivId+' .screen-reader-only').focus();

				       }
				  }
				  if(e.relatedTarget){
				     var eventRelatedTarget = $(e.relatedTarget);
				      eventRelatedTarget.attr('aria-selected','false');
				      var titleTxt = eventRelatedTarget.find('span.xforms-output-output').text();
				      if(titleTxt.length>0){
				    	  eventRelatedTarget.attr('title',titleTxt);
				      }
				     var controlledDivId = eventRelatedTarget.attr('href');
				     if((controlledDivId.length>0)&&(controlledDivId.indexOf("#")==0)){
				    	 $(''+controlledDivId).attr('aria-hidden','true');
				     }
				  }



				});
				});