Fixes for PHM dataTables issues
jQuery.namespace('lexisnexis.component');
//DE543 - Default template sort order in Home page is not based on Last Run column Starts
jQuery.extend( jQuery.fn.dataTableExt.oSort,
{
"add-template-asc" : function(a,b) {
b = b.match('<a href="#"') ? "~" : b.toLowerCase();
a = a.match('<a href="#"') ? "~" : a.toLowerCase();
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"add-template-desc" : function(a,b) {
b = b.match('<a href="#"') ? "!" : b.toLowerCase();
a = a.match('<a href="#"') ? "!" : a.toLowerCase();
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
jQuery.extend( jQuery.fn.dataTableExt.oSort,
{
"date-sort-asc" : function(a,b) {
var maxDate = "December 31, 9999 11:59 PM";
var minDate = "January 01, 1753 11:59 PM";
var $b = $(b).text();
var $a = $(a).text();
if($a == "0"){
$a = minDate;
} else if($b == "0"){
$b = minDate;
}
if($a == "1"){
$a = maxDate;
} else if($b == "1"){
$b = maxDate;
}
b = Date.parse($b);
a = Date.parse($a);
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"date-sort-desc" : function(a,b) {
var minDate = "January 01, 1753 11:59 PM";
var $b = $(b).text();
var $a = $(a).text();
if($a == "0" || $a == "1"){
$a = minDate;
}
if($b == "0" || $b == "1"){
$b = minDate;
}
b = Date.parse($b);
a = Date.parse($a);
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
//DE888 - Templates are not sorted properly when they are run at the same minute of the hour
jQuery.extend( jQuery.fn.dataTableExt.oSort,
{
"mytempdate-sort-asc" : function(a,b) {
var minDate = "January 01, 1753 11:59 PM";
var $b = $(b).text();
var $a = $(a).text();
b = Date.parse(($b!="0") ? $b : minDate);
a = Date.parse(($a!="0") ? $a : minDate);
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"mytempdate-sort-desc" : function(a,b) {
var minDate = "January 01, 1753 11:59 PM";
var $b = $(b).text();
var $a = $(a).text();
b = Date.parse(($b!="0") ? $b : minDate);
a = Date.parse(($a!="0") ? $a : minDate);
return ((a < b ) ? 1 : ((a > b ) ? -1 : 0));
}
});
//DE1583 - topics are not sorted properly when have + or - symbols in front of the topic name; see myresearch.ks sType of "myresearch-sort"
jQuery.extend( jQuery.fn.dataTableExt.oSort,
{
"myresearch-sort-asc" : function(a,b) {
var $b_html = $('<div>' + b + '</div>');
var $a_html = $('<div>' + a + '</div>');
b = $b_html.find('#spanTopicName').text().toUpperCase();
a = $a_html.find('#spanTopicName').text().toUpperCase();
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"myresearch-sort-desc" : function(a,b) {
var $b_html = $('<div>' + b + '</div>');
var $a_html = $('<div>' + a + '</div>');
b = $b_html.find('#spanTopicName').text().toUpperCase();
a = $a_html.find('#spanTopicName').text().toUpperCase();
return ((a < b ) ? 1 : ((a > b ) ? -1 : 0));
}
});
//DE543 - Default template sort order in Home page is not based on Last Run column Ends
/**
* This object will handle data table related functionality
* @class lexisnexis.component.Table
*/
lexisnexis.component.Table = lexisnexis.component.Component.extend({
data : {
splitBy : ",",
manualsort:false
},
/**
* handlePreDrawCallback
*/
handlePreDrawCallback : function(oSettings, cs) {
try {
/* fix for datatable bug in chrome which sets the browser scrollbar left to true */
oSettings.oBrowser.bScrollbarLeft = false;
/**
* If a manual reload is called then return true
*/
if(cs.data.ajaxreload===true) {
return true;
}
if (cs.data.tableSettings) {
// aaSorting[0][1] contains the sort order
// if only the table order has changed then it is a
// reorder request. Check if the request is for the same page
if( cs.data.tableSettings.aaSorting!==oSettings.aaSorting.join('.')) {
cs.data.manualsort=true;
return true;
}
if( cs.data.tableSettings._iDisplayStart!==oSettings._iDisplayStart) {
return true;
}
return false;
} // end of tableSettings
} catch (err) {
LN.debug("Error in handlePreDrawCallback" + err);
}
},
/**
* Displays the ajax indicator in the parent container of the table
* @method handleBeforeAjax
*/
handleBeforeAjax: function(cs) {
LN.showAjaxIndicator($(cs.data.tableId).parent().parent());
//When data tables fixed columns are there this should be invoked to hide the wrapper DIV
$("div.DTFC_LeftWrapper" ).css("visibility", "hidden");
/** handling unauthorized access or session expired */
$(cs.data.tableId).on('xhr.dt', function(e){
var status = arguments[1].jqXHR.status;
if(status==401){
document.location.href = LN.getContextPath() + '/j_spring_security_logout';
}
});
},
/**
* Hides the ajax indicator in the parent container of the table
* @method handleAfterComplete
*/
handleAfterComplete: function(cs) {
LN.hideAjaxIndicator($(cs.data.tableId).parent().parent());
//this.resizeDataTableHeight(cs);
},
/**
*
* @method resizeDataTableHeight
*/
resizeDataTableHeight: function(cs){
var parentDiv = $(cs.data.tableId).parent();
var rows = parentDiv.find("tbody >tr");
var ht = 0;
var $table = $(cs.data.tableId);
if ($table.length <= 0) {
return;
}
parentDiv.css('height', $table.DataTable().settings()[0].oScroll.sY);
if(rows.length<10){
rows.each(function() {
ht = ht + $(this).height();
});
if(parentDiv.height() - ht > 15){
ht = ht + 15;
/*DE1419 - Changed the height to auto rather than setting px. As different browser interpret px in different measures*/
/* PHM 512 - Filters - Patients Link - Patients Section. - Changed from auto to 200px */
// Cannot set this to 200px and expect other tables within PHM to behave properly. On the Patient Profile Overview page
// there are two tables that sit side-by-side and are restricted to showing only 5 visible rows but allows the table to
// shrink if anything below this limit. These tables are not filter related tables and does not have the complicated logic
// that builds these tables. The filter related tables need to stand at a designated height of 200px regardless of how
// many rows return, especially under 10 which would invoke much of the logic within this method. For all other tables
// that are not filter related, allow the table height to be set to "auto" as originally defined, however, allow the
// height to remain as what was originally set and seen by the setting sY (seen above).
if (!$table.hasClass('ln-filter-tables')) {
parentDiv.css('height', 'auto')
}
}
}
},
/**
* @method handleDrawCallback
*/
handleDrawCallback : function(oSettings, cs) {
try {
this.resizeDataTableHeight(cs);
/* fix for dataTable bug in Chrome which sets the browser scrollbar left to true */
oSettings.oBrowser.bScrollbarLeft = false;
cs.data.tableSettings = {
'_iDisplayStart' : oSettings._iDisplayStart,
'aaSorting' : oSettings.aaSorting.join('.')
};
var curSortColIndex = "";
var curSortOrder = "";
var lenSortingArray = typeof oSettings.aaSorting != 'undefined' ? oSettings.aaSorting.length : 0;
if (lenSortingArray > 0) {
if(typeof(oSettings.aaSorting[0][0])!='undefined'){
curSortColIndex=oSettings.aaSorting[0][0];
curSortOrder=oSettings.aaSorting[0][1];
}else{
curSortColIndex=oSettings.aaSorting[0];
curSortOrder=oSettings.aaSorting[1];
}
}
var $table = $(cs.data.tableId);
var scrollHeadEle = $table.closest('div.dataTables_scroll').find('div.dataTables_scrollHead');
/* Removing highlighting of secondary column */
try {
if (lenSortingArray > 0) {
// The class "sort_2nd" will only be added whenever there exists more than one sorting column.
// When the user clicks on any of the columns that are in the initial aaSorting array,
// "oSettings.aaSorting" array will only contain one element. You, must remove this class if
// the sorting array has one element in order for the column to highlight correctly.
if(oSettings.aaSorting.length>1){
for(var i=1; i<oSettings.aaSorting.length; i++) {
//need to ONLY change the background-color, .attr would wipe out other values, ex: width.
var element = scrollHeadEle.find('th:eq('+oSettings.aaSorting[i][0]+')');
if (!element.hasClass('sort_2nd')) {
element.addClass("sort_2nd");
}
}
}else{
scrollHeadEle.find('th:eq('+oSettings.aaSorting[0][0]+')').css("background-color","");
var element = scrollHeadEle.find('th:eq('+oSettings.aaSorting[0][0]+')');
element.removeClass("sort_2nd");
}
}
} catch (err1) {
LN.debug("Error in handleDrawCallback" + err1);
}
if(typeof lexisnexis.component.stratification != "undefined"){
var groupType = $("#groupBy").val();
var groupTableId = null;
switch(groupType){
case 'PRIMARY_CONDITION':
groupTableId = "primaryConditionTableId";
break;
case 'PATIENT_NAME':
groupTableId = "stratificationTableId";
break;
case 'GROUPS':
groupTableId = "groupsTableId";
break;
case 'ANY_CONDITION':
groupTableId = "anyConditionTableId";
break;
case 'PCP' :
groupTableId = 'pcpTableId';
break;
case 'RISK_DRIVER' :
groupTableId = 'riskDriverTableId';
break;
}
if($("#sessionSortCol").length && $("#sessionSortCol").val()){
if(groupTableId === $table.attr("id")){
scrollHeadEle.find('th').removeClass("sorting_desc");
scrollHeadEle.find('th').removeClass("sorting_asc");
var colName = $("#sessionSortCol").val();
if(colName==="IPED Visit Risk") {
colName="IP/ED Visit Risk";
}
curSortColIndex = cs.getHeaderColumnIndex(colName);
scrollHeadEle.find("th:eq('"+curSortColIndex+"')").css("background-color","").addClass("sorting_"+$("#sessionSortOrder").val());
$("#sessionSortCol").val("");
}
}
}
//Store the original settings
cs.data.oSettings=oSettings;
cs.data.ajaxreload = false;
//Adjust the body to match header position if user tabs through the table header.
$('.dataTables_scrollHead th').off('keyup');
$('.dataTables_scrollHead th').on('keyup', function(e) {
if(e.keyCode == 9) {
var $thead = $(this).closest('.dataTables_scrollHead');
var scrollLeft = $thead.scrollLeft();
$thead.closest('.dataTables_scroll').find('.dataTables_scrollBody').scrollLeft(scrollLeft);
}
});
} catch (err) {
LN.debug("Error in handleDrawCallback" + err);
}
},
/**
* Adjusts alignment between the cloned table and the default table when using the fixed column plugin.
* @method adjustFixedColumnRowHeights
*/
adjustFixedColumnRowHeights : function(cs) {
if (typeof cs.data.table != 'undefined') {
var $scrollWrapper = null;
var tableWrapper = cs.data.table.closest('#'+cs.data.table.attr('id')+'_wrapper');
if (tableWrapper.length > 0) {
$scrollWrapper = $(tableWrapper).find('div.DTFC_ScrollWrapper');
}
if ($scrollWrapper != null) {
var lHeight = "0px";
// Fix the rows heights on the body of the fixedColumn.
cs.data.table.find('tbody tr').each(function(i, r) {
var $l = $($scrollWrapper.find('div.DTFC_LeftBodyLiner table tbody tr')[i]);
var $r = $(r);
$r.css('height','');
lHeight = $r.height()+1+'px';
$l.css('height',lHeight);
$r.css('height',lHeight);
});
// Fix the rows heights on the head of the fixedColumn.
cs.data.table.closest('div.dataTables_scroll').find('div.dataTables_scrollHead thead tr').each(function(i, r) {
var $l = $($scrollWrapper.find('div.DTFC_LeftHeadWrapper table thead tr')[i]);
lHeight = $(r).height()+'px';
$l.css('height',lHeight);
});
}
}
var sTop = $('.DTFC_LeftBodyLiner').scrollTop();
if (sTop == null) {
sTop = 0;
}
$('.dataTables_scrollBody').scrollTop(sTop);
},
/**
* DOM Manipulation. Check if vertical scroll bar is needed. If the parent div height is greater than table height, set overflow-y to hidden.
* @method verticalScrollBarCheck
* @param tableID {string}
* @returns {void}
*/
verticalScrollBarCheck : function(tableID) {
var cs = this;
if (typeof tableID != 'undefined') {
//LN.debug("isVerticalScrollBarNeeded called");
console.log( $(tableID).parent() );
var scrollbodyH = $(tableID).parent().outerHeight();
var scrollbodyTableH = $(tableID).height();
if (scrollbodyTableH <= scrollbodyH) {
$( $(tableID).parent() ).css("overflow-y","hidden");
}
}
},
/**
* Adjusts alignment between the cloned table and the default table when using the fixed column plugin.
* @method alignFixedColumnElements
*/
alignFixedColumnElements : function(cs) {
$('.ln-table-style').css('margin','0px 0px');
var $lbLiner = $('.DTFC_LeftBodyLiner').css('left','1px');
$lbLiner.find('table.dataTable tbody td').css("border-right-width","2px");
$lbLiner.find('table').css('margin-bottom','3px');
/* defect PHM-485 This is no longer needed and actually breaks height alignment on IE9 and IE10
if (cs.isIE()) {
$('.DTFC_LeftBodyLiner .ln-table-style').css('margin','2px 0px 3px');
var $r = cs.data.table.find('tbody tr:nth(0)')
var $l = $($('div.DTFC_LeftBodyLiner table tbody tr')[0]);
var lHeight = $r.css('height','').height();
$l.css('height',lHeight+2+'px');
$r.css('height',lHeight+1+'px');
}
*/
},
/**
* @method getColumnNameByIndex
*/
getColumnNameByIndex : function(index) {
var cs = this;
var columnArray = cs.convertColumnStringToArray();
return columnArray[index].trim();
},
/** Adjusts row height for tables with one row that have text wrapped to a 2nd line because
* dataTables in Chrome does not adjust for the 2nd line.
* */
adjustRowHeight: function (cs){
if (!cs.isIE()) {
var rowHeight = $('.dataTables_scrollBody tbody tr').eq(0).height();
$('.dataTables_scrollBody').css('height',rowHeight);
}
$('.dataTables_scrollBody').css('overflow','hidden');
$('.dataTables_scrollHeadInner').css('padding-right','');
},
/**
*
* @method handleInitComplete
*/
handleInitComplete : function(oSettings, cs) {
// store the settings to compare when doing col reorder
cs.data.tableSettings = {
'_iDisplayStart' : oSettings._iDisplayStart,
'aaSorting' : oSettings.aaSorting.join('.')
};
//Store the original settings
cs.data.oSettings=oSettings;
//Reset the ajax
cs.data.ajaxreload = false;
//DE267 Default columns are being displayed on Patient List page while page gets load
$(".tableHeader").show();
if(cs.data.table) {
cs.data.table.fnAdjustColumnSizing(false);
}
},
/**
* Identifies the index of the column based on the id
* @method getColumnIndex
*/
getColumnIndex : function(name) {
name = name.replace(/[ /]/g, '_').replace(/"/g, '');
return $(name).index();
},
/**
* Get the index based on header data-idval.
* @method getHeaderColumnIndex
* @param name {string}
*/
getHeaderColumnIndex: function(name) {
var cs = this;
return $(cs.data.tableId +" th[data-idval='"+name+"']").index();
},
/**
* set the default column preferences on the table
* @method setDefaultColumnsPref
*/
setDefaultColumnsPref : function() {
LN.debug("Entering setDefaultColumnsPref");
var cs = this;
var defaultTablePrefArr = cs.convertColumnStringToArray();
cs.data.defaultTablePrefArr = [];
for (var i = 0; i < defaultTablePrefArr.length; i++) {
var val = defaultTablePrefArr[i].replace(/ /g, '');
cs.data.defaultTablePrefArr.push(val);
}
LN.debug("defaultTablePrefArr=" + cs.data.defaultTablePrefArr);
LN.debug("Exiting setDefaultColumnsPref");
},
/**
* @method convertColumnStringToArray
*/
convertColumnStringToArray : function(){
var cs = this;
var defaultTablePref = cs.data.defaultTablePreferences;
var splitBy = (cs.data.splitBy) ? cs.data.splitBy : ",";
LN.debug("splitBy=" + splitBy);
return defaultTablePref.substring(1)
.substring(0, defaultTablePref.length - 2)
.split(splitBy);
},
/**
* save the column ordering to the database
* @method setSaveColumns
*/
setSaveColumns : function(formData, flag, params) {
var cs = this;
$.ajax({
'url' : cs.data.USER_PREF_URL,
'contentType' : 'application/json',
'dataType' : 'json',
'method' : 'POST',
'data' : formData,
'success' : function() {
if (flag) {
$.growl({
title : "",
message : "The table preferences have been saved"
});
} // flag is to differentiate that the call is
// from save button or reset button
else {
// reload the page
LN.debug("datatable ref=" + cs.data.table);
}
// update the table preferences
},
'error' : function() {
}
}); // end of ajax
},
/**
* looks up the index of the column in the default preferences array.
* @method getIndex
*/
getIndex : function(name) {
var cs = this;
name = name.replace(/ /g, '').replace(/"/g, '');
return $.inArray(name, cs.data.defaultTablePrefArr);
},
/**
* function to save the column ordering based on the UI into the
* database
* @method saveColumnOrdering
*/
saveColumnOrdering : function(params) {
var cs = this;
var uniqArr =[];
var columnNames = "[";
$(cs.data.tableId + ' .tab-th-cellspacing').each(function(index, value) {
var val = $(this).attr('data-idVal');
// NOTE: Datatable does maintain two lists
if ($.inArray(val, uniqArr) === -1) {
columnNames += "\"" + val.replace(",", "_")+ "\",";
uniqArr.push(val);
}
});
// Remove the last comma
columnNames = columnNames.substring(0, columnNames.length - 1);
columnNames += "]";
var formData = "{\"tableId\":\"" + cs.data.tablePreferencesId
+ "\",\"columnNames\":" + columnNames + "}";
LN.debug(formData);
cs.setSaveColumns(formData, true, params);
},
/**
* stores the default order of the table according to what is stored
* in database
* @method setTableColumnOrder
*/
setTableColumnOrder : function() {
LN.debug("setTableColumnOrder entering");
var cs = this;
var defaultOrder =[];
LN.debug("table preferences=" + cs.data.tablePreferences);
var tablePref = cs.data.tablePreferences;
var splitBy = (cs.data.splitBy) ? cs.data.splitBy : ",";
LN.debug("splitBy =" + splitBy);
var tablePrefArr = tablePref.substring(1).substring(0,
tablePref.length - 2).split(splitBy);
LN.debug("tablePrefarr length=" + tablePrefArr.length);
// NOTE: THIS CONDITION SETS THE DEFAULT PREFERENCES TO SET
if (tablePrefArr.length <= 1) {
cs.data.tableOrder = cs.data.defaultOrder;
return;
}
for (var i = 0; i < tablePrefArr.length - 1; i++) {
defaultOrder[i] = cs.getIndex(tablePrefArr[i]);
}
defaultOrder[tablePrefArr.length - 1] = cs.getIndex(tablePrefArr[tablePrefArr.length - 1]);
cs.data.tableOrder = defaultOrder;
LN.debug("setting table order=" + cs.data.tableOrder);
},
/**
* resets the column ordering to the default
* @method resetColReorder
*/
resetColReorder : function(params) {
LN.debug("resetColReorder entering");
var cs = this;
$(cs.data.resetId).click(function(e) {
e.preventDefault();
try {
LN.debug("resetting colreorder");
var columnNames = "[";
for (var i = 0; i < cs.data.defaultTablePrefArr.length - 1; i++) {
columnNames += "\""
+ cs.data.defaultTablePrefArr[i]
+ "\",";
}
columnNames += "\""
+ cs.data.defaultTablePrefArr[cs.data.defaultTablePrefArr.length - 1]
+ "\"";
columnNames += "]";
LN.debug("columnNames =" + columnNames);
var formData = "{\"tableId\":\""
+ cs.data.tablePreferencesId
+ "\",\"columnNames\":"
+ columnNames + "}";
LN.debug("formData=" + formData);
var table = $(cs.data.tableId).DataTable();
table.colReorder.reset();
cs.setSaveColumns(formData, false,params);
cs.data.tableSettings = {
'_iDisplayStart' : cs.data.oSettings._iDisplayStart,
'aaSorting' : cs.data.oSettings.aaSorting.join('.')
};
LN.debug("reset");
} catch (err) {
LN.debug("error in reset" + err);
}
});
LN.debug("resetColReorder exiting");
},
/**
* stores the default order of the table
* @method setDefaultOrder
*/
setDefaultOrder : function() {
var cs = this;
var defaultOrder = [];
var tablePref = cs.data.tablePreferences;
var splitBy = (cs.data.splitBy) ? cs.data.splitBy : ",";
LN.debug("splitBy=" + splitBy);
var tablePrefArr = tablePref.substring(1)
.substring(0, tablePref.length - 2).split(splitBy);
for (var i = 0; i < tablePrefArr.length - 1; i++) {
defaultOrder[i] = cs.getIndex(tablePrefArr[i]);
}
defaultOrder[tablePrefArr.length - 1] = cs.getIndex(tablePrefArr[tablePrefArr.length - 1]);
cs.data.tableOrder = defaultOrder;
},
/**
* function to set the column ordering based on the UI
* @method setColumnOrdering
*/
setColumnOrdering : function() {
var cs = this;
$(cs.data.tableId).on('draw.dt', function() {
event.preventDefault();
var uniqArr = [];
var columnNames = "[";
$('.ln-patientDetailsTable-heading').each(function(index, value) {
var val = $(value).text();
// NOTE: Datatable does
// maintain two lists
if ($.inArray(val,
uniqArr) === -1) {
columnNames += "\"" + val + "\",";
uniqArr.push(val);
}
});
// Remove the last comma
columnNames = columnNames.substring(0, columnNames.length - 1);
columnNames += "]";
var formData = "{\"tableId\": \"patientListTablePreferences\",\"columnNames\":"
+ columnNames + "}";
$.ajax({
'url' : cs.data.USER_PREF_URL,
'contentType' : 'application/json',
'dataType' : 'json',
'method' : 'POST',
'data' : formData,
'success' : function(data, textStatus) {
// update the table
// preferences
cs.data.tablePreferences = columnNames;
cs.setDefaultOrder();
},
'error' : function(jqXHR, textStatus, errorThrown) {
LN.debug(errorThrown);
}
}); // end of ajax
});
},
/**
* Helper function to get URL based on context path.
* @method getURL
*/
getURL : function() {
var pattern = ["/.*\\", LN.getContextPath(), "/"].join('');
var url = location.href.replace(pattern, LN.getContextPath());
LN.debug("getURL=" + url);
return url;
},
/**
* Function to get the column ordering based on the UI.
* @method getCurrentColumnNamesArray
*/
getCurrentColumnNamesArray : function() {
var cs = this;
LN.debug("Entering getCurrentColumnNamesArray");
var uniqArr =[];
$(cs.data.tableId + ' .tab-th-cellspacing').each(
function(index, value) {
var val = $(this).attr('data-idVal');
// NOTE: Datatable does maintain two lists
if ($.inArray(val, uniqArr) === -1) {
// Change to support comma
uniqArr.push(val.replace(",", "_"));
}
});
// Remove the last comma
LN.debug("Exiting getCurrentColumnNamesArray");
return uniqArr;
}, // end of getCurrentColumnNamesArray
/**
* Appends params to window location and redirects.
* @method redirectToPage
* @param params
*/
redirectToPage : function(params) {
var protocol = location.protocol;
var host = location.host;
var pathname = location.pathname;
if (pathname[pathname.length - 1] === "/") {
pathname = pathname.substring(0, (pathname.length - 1));
}
var match = RegExp('[?&]' + 'id' + '=([^&]*)').exec(window.location.search);
var id = match && decodeURIComponent(match[1].replace(/\+/g, ' '));
var url = protocol + '//' + host + pathname + '?id=' + id;
if (params) {
var isQuestionMarkPresent = url && url.indexOf('?') !== -1,
separator = isQuestionMarkPresent ? '&' : '?';
url += separator + params;
LN.debug("getURLWithParams :: " + url);
location.href = url;
} else {
LN.debug("getURLWithParams :: " + url);
location.href = url;
}
},
/**
* Appends params to the URL and redirects
* @method redirectToPageWithParam
* @param url {string}
* @param params {string}
*/
redirectToPageWithParam : function(url, params) {
if (params) {
var isQuestionMarkPresent = url && url.indexOf('?') !== -1,
separator = isQuestionMarkPresent ? '&' : '?';
url += separator + params;
LN.debug("getURLWithParams inside if :: " + url);
} else {
LN.debug("getURLWithParams else :: " + url);
}
return url;
},
/**
* Get parameter from URL by parameter name
* @method getParameterByName
* @param name {string}
*/
getParameterByName : function(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
},
/**
* @method getPathFromUrl
*/
getPathFromUrl : function() {
var protocol = location.protocol;
var host = location.host;
var pathname = location.pathname;
if (pathname[pathname.length - 1] === "/") {
pathname = pathname.substring(0, (pathname.length - 1));
}
var match = RegExp('[?&]' + 'id' + '=([^&]*)').exec(window.location.search);
var id = match && decodeURIComponent(match[1].replace(/\+/g, ' '));
var url = protocol + '//' + host + pathname + '?id=' + id;
return url;
},
/**
* Event fires on data set change on Run Template pop up
* @method onDataSetChange
* */
onDataSetChange : function() {
var cs = this;
$('#runDataSet').on('change', function(e) {
$('#dlgTemplateName').html(cs.data.templateName);
$('#Run').attr('disabled', 'disabled');
var pCount= cs.getPatientCount(cs.data.templateId, cs.data.templateName);
if(pCount == 0){
LN.debug("inside pcount =0 condition");
$('#error').css("display", "block");
}else{
$('#error').css("display", "none");
}
});
} ,
/**
* Fetches the patient count based on the template name.
* @method getPatientCount
* */
getPatientCount : function(tempId, tempName){
var cs=this;
var dataset= $('#runDataSet').val();
$.ajax({
'url': "mytemplates/"+tempId+"/count/"+dataset,
'contentType': 'application/json',
'dataType': 'json',
'method': 'post',
'success': function(data, textStatus, jqXHR) {
$('#createTemplateIdHid').html(data.templateid);
$('#templateVersionHid').html(data.templateversion);
$('#createTemplateNameHid').html(tempName);
/**
* Commenting the below line of code because,
* the template name got reflected on the Home page Template Name
* when running the templates on home page.
*/
/**
* $('#ln_renameLbl').html(template);
*/
if(data.pcount <= 0){
$('#error').css("display", "block");
$('#Run').attr("class","btn btn-xs").attr('disabled','disabled');
}else{
$('#error').css("display", "none");
$('#Run').attr("class","btn btn-xs").removeAttr('disabled');
}
},
'error': function(jqXHR, textStatus, errorThrown) {
return true;
}
});
},
/**
* Run/execute a template from Mytemplates and Home page
* @method runTemplate
* */
runTemplate : function(){
var cs=this;
var dataset= $('#runDataSet').val();
$.ajax({
'url': "mytemplates/"+cs.data.templateId+"/run/"+dataset,
'contentType': 'application/json',
'dataType': 'json',
'method': 'post',
'success': function(data, textStatus, jqXHR) {
LN.debug("Inserted History Record") ;
},
'error': function(jqXHR, textStatus, errorThrown) {
LN.debug("History Record Insertion Failed");
}
});
location.href= LN.getContextPath()+'/overallrisk';
},
/**
* Copies template on My templates page.
* @method copyTemplate
* */
copyTemplate : function(){
var cs=this;
var dataset= $('#runDataSet').val();
var url = "copyTemplate/"+cs.data.templateId+"/run/"+dataset+"?templateName="+
btoa($('#copyTemplateName').val());
$.ajax({
'url': url,
'contentType': 'application/json',
'dataType': 'json',
'method': 'post',
'success': function(data, textStatus, jqXHR) {
LN.debug("Inserted History Record");
if(data == '0'){
$('.ln-errorMsgSaveTemp').html("Error: Template name already exists.");
} else {
$("div#copyTemplateDialog").dialog("close");
$('#templateList').dataTable().fnDestroy();
$('#templateHistList').dataTable().fnDestroy();
cs.initializeTable();
}
},
'error': function(jqXHR, textStatus, errorThrown) {
LN.debug("History Record Insertion Failed");
}
});
},
/**
* Save a template from My templates to Template Library
* @method saveTemplateToLibrary
*/
saveTemplateToLibrary : function(){
var cs=this;
var dataset= $('#runDataSet').val();
var url = "saveTemplateToLibrary/"+cs.data.templateId+"/run/"+dataset+"?templateName="+btoa($('#libraryTemplateName').val())+"&templateDescription="+btoa($('#libraryTemplateDescription').val());
$.ajax({
'url': url,
'contentType': 'application/json',
'dataType': 'json',
'method': 'post',
'success': function(data, textStatus, jqXHR) {
LN.debug("Inserted Library Record");
if(jqXHR.responseText == "{}"){
$('.ln-errorMsgTemplateLibrary').html("Template name already exists.");
} else {
LN.showApplicationMessage("Confirmation: Your Template has been added to the Library.", "");
$("div#templateLibraryDialog").dialog("close");
$('#templateList').dataTable().fnDestroy();
$('#templateHistList').dataTable().fnDestroy();
cs.initializeTable();
}
},
'error': function(jqXHR, textStatus, errorThrown) {
LN.debug("Library Record Insertion Failed");
}
});
},
/**
* @method editTemplate
*/
editTemplate : function() {
var cs=this;
var dataset= $('#runDataSet').val();
$.ajax({
'url': "editMytemplates/"+cs.data.templateId+"/run/"+dataset,
'contentType': 'application/json',
'dataType': 'json',
'method': 'post',
'success': function(data, textStatus, jqXHR) {
LN.debug("Inserted History Record");
if(data.accessPrivilegesChanged == "true"){
$("div#editDialog").dialog ({
width: 500,
modal:true,
resizable : false,
closeOnEscape: false,
dialogClass: 'noclose ln-timeout',
open: function(event, ui) {
$('.noclose').find('.ui-dialog-titlebar-close').hide();
},
//To clear the filters after clickin on close button
close: function( event, ui ) {
cs.cancelTemplate();
/** DE1467 - Two different Template History window is displayed starts **/
if($('#templateHistList')){
$('#templateHistList').dataTable().fnDestroy();
}
/** DE1467 - Two different Template History window is displayed ends **/
$(this).dialog("close");
cs.data.table.fnAdjustColumnSizing(false);
},
buttons: {
Close: {
class:'btn btn-xs',
text: 'OK',
click : function (){
location.href= LN.getContextPath()+'/viewEditFiltersSummary';
}
}
}
});
$('#editDialog').css("display", "block");
$('#editDialogWarning').css("display", "block");
} else{
$('#editDialog').css("display", "none");
$('#editDialogWarning').css("display", "none");
location.href= LN.getContextPath()+'/viewEditFiltersSummary';
}
},
'error': function(jqXHR, textStatus, errorThrown) {
LN.debug("History Record Insertion Failed");
}
});
},
/**
* Method to cancel the Run Template
* @method cancelTemplate
* */
cancelTemplate : function(){
var cs=this;
$.ajax({
'url': "mytemplates/"+cs.data.templateId+"/cancel",
'contentType': 'application/json',
'dataType': 'json',
'method': 'post',
'success': function(data, textStatus, jqXHR) {
LN.debug("Template filters removed from session");
$('#createTemplateIdHid').html("");
$('#templateVersionHid').html("");
$('#createTemplateNameHid').html("");
$('#ln_renameLbl').html("Active Patients");
},
'error': function(jqXHR, textStatus, errorThrown) {
LN.debug("Ajax call to cancel template run failed");
}
});
},
/**
* Opens copy template dialog window.
* @method registerCopyTemplateAction
*/
registerCopyTemplateAction : function(cs) {
$('.copyTemplate').bind('click', function(e) {
e.preventDefault();
var $this = $(this);
cs.data.templateId=$this.attr('templateId');
cs.data.templateName=$this.find('span:first').text();
var tmpdisplayName = "Copy of "+ cs.data.templateName;
var trimmedDisplayName = tmpdisplayName.substring(0, Math.min(60,tmpdisplayName.length));
$('#copyTemplateName').val(trimmedDisplayName);
$("div#copyTemplateDialog").dialog({
width : 500,
height : 600,
modal : true,
resizable : false,
close: function( event, ui ) {
if($('#templateHistList')){
$('#templateHistList').dataTable().fnDestroy();
}
},
buttons : {
Close : {
class : 'cancelButton',
text : 'Cancel',
click : function() {
$(this).dialog("close");
//DE2523 - Incorrect pop up is displayed when user click on copy template icon and History icon Starts
if($('#templateHistList')){
$('#templateHistList').dataTable().fnDestroy();
}
//DE2523 - Incorrect pop up is displayed when user click on copy template icon and History icon Ends
}
},
Save : {
class : 'cancelButton',
text : 'Save',
click : function() {
if(cs.validateCopyTemplateSave()){
cs.copyTemplate();
$(".ln-errorMsgSaveTemp").html("");
}
}
}
}
});
});
},
/**
* Function added for DE 1592
* @method getPatientCountForRunTemplate
*/
getPatientCountForRunTemplate : function(tempId, tempName){
var cs=this;
var dataset= $('#runDataSet').val();
$.ajax({
'url': "mytemplates/"+tempId+"/count/"+dataset,
'contentType': 'application/json',
'dataType': 'json',
'method': 'post',
'beforeSend' : function(){
dlg.openLoadingDialog();
},
'success': function(data, textStatus, jqXHR) {
$('#createTemplateIdHid').html(data.templateid);
$('#templateVersionHid').html(data.templateversion);
$('#createTemplateNameHid').html(tempName);
//DE 1592 dialog open after the patient count call start
$('#dlgTemplateName').html(cs.data.templateName);
$("div#runDialog").dialog ({
width: 520,
height: 500,
modal:true,
resizable : false,
//To clear the filters after clicking on close button
close: function( event, ui ) {
cs.cancelTemplate();
/** DE1467 - Two different Template History window is displayed starts **/
if($('#templateHistList')){
$('#templateHistList').dataTable().fnDestroy();
}
/** DE1467 - Two different Template History window is displayed ends **/
$(this).dialog("close");
cs.data.table.fnAdjustColumnSizing(false);
if(data.accessPrivilegesChanged == "true"){
cs.reloadTable();
}
},
buttons: {
Close: {
class:'btn btn-xs',
text: 'Cancel',
click : function (){
cs.cancelTemplate();
$(this).dialog("close");
if(data.accessPrivilegesChanged == "true"){
cs.reloadTable();
}
}
},
"Run":{
id : 'Run',
class:'btn btn-xs',
text: 'Run',
click: function() {
cs.runTemplate();
}
}
}
});
/**
* DE 1592 dialog open after the patient count call end
* Commenting the below line of code because,
* the template name got reflected on the Home page Template Name
* when running the templates on home page.
*/
/**
* $('#ln_renameLbl').html(template);
*/
if(data.pcount <= 0){
$('#error').css("display", "block");
$('#Run').attr("class","btn btn-xs").attr('disabled','disabled');
}else{
$('#error').css("display", "none");
}
var elemType = data.accessPrivilegesChanged == "true" ? "block" : "none";
$('#runDialogWarning').css("display", elemType);
},
"complete" : function(){
$.unblockUI();
},
'error': function(jqXHR, textStatus, errorThrown) {
return true;
}
});
},
/**
* @method registerRunTemplateAction
*/
registerRunTemplateAction:function(cs){
$('.runTemplate, .editTemplate').on('click', function(e){
e.preventDefault();
var currentTarget = e.currentTarget.className;
var $this = $(this);
cs.data.templateId=$this.attr('templateId');
cs.data.templateName=$this.find('span:first').text();
$('#error').css("display", "none");
if(currentTarget.match('runTemplate')){
//DE 1592 changed the call flow from patient count to dialog
cs.getPatientCountForRunTemplate(cs.data.templateId, cs.data.templateName);
} else {
/* Edit Service Method to be called*/
cs.editTemplate();
}
});
},
/**
* @method registerDeleteTemplateAction
*/
registerDeleteTemplateAction:function(cs){
$('.deleteTemplate').bind('click', function(e){
e.preventDefault();
var $this = $(this);
var delTemplateId="";
var delTemplateVersionId="1";
var delFlag=true;
var templateDetails=$this.children().contents();
var templateName = templateDetails[0].textContent;
//templateName = templateName.toString();
$('#delTemplate').html(templateName+"?");
$('#delTemplate').show();
var tempId = $this.attr('usrTemplateId');
if(tempId){
delTemplateId=$this.attr('usrTemplateId');
delFlag=false;
}else{
delTemplateId=$this.attr('templateId');
delFlag=true;
}
if(templateDetails[1].textContent){
delTemplateVersionId=templateDetails[1].textContent;
//delTemplateVersionId=delTemplateVersionId.toString();
}
$("div#deleteDialog").dialog ({
open: function() {
// PHM-520 - Enter button functions as cancel on popup window
// start the focus on the Delete button
$(this).parent().find('.ui-dialog-buttonpane button:eq(1)').focus();
// prevent the X button from getting the focus
$(this).parent().find('.ui-dialog-titlebar-close').attr('tabindex', '-1').blur();
},
show : "slide",
hide : "puff",
width: 500,
height: 500,
modal:true,
resizable : false,
close: function( event, ui ) {
if($('#templateHistList')){
$('#templateHistList').dataTable().fnDestroy();
cs.data.table.fnAdjustColumnSizing(false);
}
},
buttons: {
Close: {
class:'cancelButton',
text: 'Cancel',
click : function (){
$(this).dialog("close");
}
},
Delete: {
text: 'Delete',
click : function() {
var deleteUrl = delFlag ? $("#deleteUrl").val() : LN.getContextPath() + '/deleteTemplate';
$.ajax({
url: deleteUrl,
type : "POST",
data: {
"templateName": templateName,
"templateId": delTemplateId,
"templateVersion": delTemplateVersionId
},
success: function(data){
$("div#deleteDialog").dialog("close");
if(data===0) {
//DE581 - Sprint 9 demo defect : Header of table in Add template pop up is not displayed
if ($.fn.dataTable.isDataTable( '#templateList' ) ) {
$('#templateList').dataTable().fnDestroy();
} else if ($.fn.dataTable.isDataTable( '#templateHistList' ) ) {
$('#templateHistList').dataTable().fnDestroy();
}else if ($.fn.dataTable.isDataTable( '#myTemplatelist' ) ) {
$('#myTemplatelist').dataTable().fnDestroy();
}
cs.initializeTable();
} else {
$.growl({
title : "",
message : "Error Occured! Template Not Deleted"
});
}
},
error: function(data){
$.growl({
title : "",
message : "Error Occured! Template Not Deleted"
});
}
});
}
}
}
});
});
},
/**
* Reload the data in the table using AJAX
* @method reloadTable
*/
reloadTable : function() {
var cs = this;
cs.data.ajaxreload = true;
cs.data.table.fnReloadAjax(cs.data.url);
},
/**
* below function added Goto page functionality for datatable.<br>
* Adds input text box and Goto button
* @method addGotoPageComponent
*/
addGotoPageComponent: function(datatableId,gotobtnId,gototxtId){
var cs=this;
if($("#"+gotobtnId).length==0){
var disableGoToTxtBox = $("#"+datatableId).DataTable().page.info().pages < 2;
if(cs.isIE()){
$("#"+datatableId+"_paginate").prepend("<div class=\"pull-left\"><span>Go To Page <input type='text' maxlength='4' size='3' class='form-control input-sm' " + (disableGoToTxtBox? "disabled='true' style='background-color:#E6E6E6;'":"") + " id='"+gototxtId+"' value='"+$(".paginate_active").text()+"'/> <button id='"+gotobtnId+"' class='btn btn-default btn-xs phm-btn' style=\"margin-bottom:6px;\">Go</button></span><div id='gotoError' class='row text-center error' ></div></div>");
}else{
$("#"+datatableId+"_paginate").prepend("<div class=\"pull-left\"><span>Go To Page <input type='text' maxlength='4' size='3' class='form-control input-sm' " + (disableGoToTxtBox? "disabled='true'":"") + "' id='"+gototxtId+"' value='"+$(".paginate_active").text()+"'/> <button id='"+gotobtnId+"' class='btn btn-default btn-xs phm-btn'>Go</button></span><div id='gotoError' class='row text-center error' ></div></div>");
}
$("#"+gotobtnId).attr('disabled', disableGoToTxtBox);
}
$("#"+gotobtnId).on('click',{tableobj : $("#"+datatableId), gotoObj : $("#"+gototxtId), errorObj : $("#gotoError")}, this.gotoPage);
$("#"+gototxtId).on('keyup',{tableobj : $("#"+datatableId), gotoObj : $("#"+gototxtId), errorObj : $("#gotoError")}, this.validatePageNumber);
/* DE476 - Enter button does not function when selected after entering the Page number in Go To Page Edit box */
$("#"+gototxtId).on('keyup',{tableobj : $("#"+datatableId), gotoObj : $("#"+gototxtId), errorObj : $("#gotoError")}, this.gotoPage);
/* DE476 - Enter button does not function when selected after entering the Page number in Go To Page Edit box */
$("#"+gototxtId).on('focusout',{tableobj : $("#"+datatableId), gotoObj : $("#"+gototxtId), errorObj : $("#gotoError")}, this.validatePageNumber);
/* DE378 - Go Button remain selected after click*/
$("#"+gotobtnId).on('mouseup',function(){
$(this).blur();
});
/* DE378 - Go Button remain selected after click*/
},
/* Goto page button click listener
* @method gotoPage
* param e {object}
*/
gotoPage: function(e){
/* DE476 - Enter button does not function when selected after entering the Page number in Go To Page Edit box */
if(e.which == $.ui.keyCode.ENTER || e.type == 'click') {
/* DE476 - Enter button does not function when selected after entering the Page number in Go To Page Edit box */
var data = e.data;
var pageNumber = data.gotoObj.val();
var oTable = data.tableobj.dataTable();
var maxPage = data.tableobj.DataTable().page.info().pages;
e.preventDefault();
/* DE2538 - Error message is displayed for Go To Page edit box when user selects Enter button by placing the cursor in any of the Last name or the first name search boxes starts */
/*if(pageNumber.trim().length==0){
data.errorObj.html("Please enter a number between 1 and "+maxPage).show();
return;
}*/
/* DE2538 - Error message is displayed for Go To Page edit box when user selects Enter button by placing the cursor in any of the Last name or the first name search boxes ends */
var reg = new RegExp('^[0-9]+$');
if(pageNumber.match(reg)){
if(pageNumber <1 || pageNumber>maxPage){
data.errorObj.html("Please enter a number between 1 and "+maxPage).show();
}else{
oTable.fnPageChange(pageNumber-1);
}
}
/* DE476 - Enter button does not function when selected after entering the Page number in Go To Page Edit box */
}
/* DE476 - Enter button does not function when selected after entering the Page number in Go To Page Edit box */
},
/**
* Called on key press event for goto input textbox and focus out event.
* @method validatePageNumber
*/
validatePageNumber: function(e) {
var data = e.data;
var maxPage = data.tableobj.DataTable().page.info().pages;
var pageNumber = data.gotoObj.val();
var reg = new RegExp('^[0-9]+$');
if(pageNumber.trim().length==0){
data.errorObj.hide();
return;
}
if(!pageNumber.match(reg)){
data.errorObj.html("Please enter a number between 1 and "+maxPage).show();
}else if(pageNumber <1 || pageNumber>maxPage){
data.errorObj.html("Please enter a number between 1 and "+maxPage).show();
}else{
data.errorObj.hide();
}
},
/**
* @method registerHistoryTemplateAction
*/
registerHistoryTemplateAction:function(cs){
$('.historyTemplate').bind('click', function(e){
var $this = $(this);
var templateId=$this.attr('templateId');
e.preventDefault();
$('#histTemplateName').html($this.find('span:first').text());
var historyURL=$("#historyUrl").val();
cs.data.historyTableObj.reload(historyURL, templateId);
$("div#historyDialog").dialog ({
width: 700,
height: 500,
modal:true,
resizable : false,
//History Dialog needs to be deleted
close: function( event, ui ) {$('#templateHistList').dataTable().fnDestroy();},
buttons: {
Close: {
class:'cancelButton',
text: 'Close',
click : function (){
$(this).dialog("close");
}
}
}
});
});
},
/**
* @method getPatrisklistURL
*/
getPatrisklistURL:function(patientName, patientId) {
var cs = this;
var id = cs.getParameterByName("id");
var riskprofileViewby = escape("Risk Group");
url = LN.getContextPath()+'/patientriskprofile?id='+id + "&patientName=" + escape(patientName)+"&patientId="+encodeURIComponent(patientId)+"&riskprofileViewby="+riskprofileViewby;
return url;
},
/**
* @method resetSortOrder
*/
resetSortOrder: function() {
//reset the sort order and populate
var cs=this;
var orderArray=[];
if(cs.data.defaultSortColumn) {
orderArray.push([$('th[data-idval="'+cs.data.defaultSortColumn+'"]').index(), cs.data.defaultSortOrder ]);
}
if(cs.data.secondarySortColumn) {
orderArray.push([$('th[data-idval="'+cs.data.secondarySortColumn+'"]').index(),cs.data.secondarySortOrder ]);
}
LN.debug('orderArray size :: '+orderArray.length);
cs.data.table.DataTable().order(
orderArray
);
},
/**
* @method getPredictionTrendArrow
*/
getPredictionTrendArrow: function(predictionTrend) {
var trendClass = '';
var trendIcon = '';
var predTrend=Number(predictionTrend,10);
if (predTrend < 0) {
trendClass = '<span class="glyphicon glyphicon-arrow-down"></span>';
trendIcon = '<span class="ln-colorBlack">'+ trendClass +'</span>';
} else if (predTrend == 0) {
trendClass = 'ln-table-spacer';
trendIcon = '<span class="'+ trendClass +'"></span>';
} else {
trendClass = '<span class="glyphicon glyphicon-arrow-up"></span>';
trendIcon = '<span class="ln-colorBlack">'+ trendClass +'</span>';
}
return trendIcon;
},
/**
* Formats date to Local time zone format
* @method formatDatebyTimeZone
*/
formatDatebyTimeZone: function(date){
var local = new Date(date+" GMT");
var hours = local.getHours();
var minutes = local.getMinutes();
var ampm = hours >= 12 ? 'PM' : 'AM';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
var month = (local.getMonth()+1 < 10)? "0"+(local.getMonth()+1):(local.getMonth()+1);
date = (local.getDate() < 10)? "0"+(local.getDate()):(local.getDate());
return month + "/" + date + "/" + local.getFullYear() + " " + strTime;
},
/**
* Searches the table by reloading the table with the ajax.<br>
* Currently, if validation is enabled then basic validation for name fields will be done.<br>
* Can be modified further to support almost all validations
* @method enableSearchOnTable
* @param obj - an array object
* [{id : 'patient_last_name',limit : 3,validate : true,table : cs.data.table},
* {id : 'patient_first_name',limit : 0,validate : true,table : cs.data.table}]
*/
enableSearchOnTable : function(obj) {
var cs = this;
var errorFlag = false;
cs.data.searchFields = obj;
if (typeof obj != 'undefined' && obj.length > 0) {
$("#"+obj[0].id).closest('form').validate( {
focusInvalid : true,
errorPlacement : function(error, element) {
// $(element).text('');
var $elem = $(element), targetElem = element,
errorId = $elem.attr('data-idVal');
if (typeof errorId != 'undefined') {
var $eElement = $('#'+errorId);
element = $eElement.length > 0 ? $eElement[0] : element;
}
error.insertAfter(element);
},
errorElement : 'div'
} );
}
$.validator.addMethod("nospecialchar", function(value, element) {
var pattern = /[+*.,!@#$%^&();/|\\?-]/g;
return !pattern.test(value);
}, "Please enter alphanumeric characters");
$.validator.addMethod("nospecialcharForName", function(value, element) {
var pattern = /[_+*.,!@#$%^&();/|\\?-]/g;
return !pattern.test(value);
}, "Please enter alpha characters");
$.validator.addMethod("nospecialcharallowhyphen", function(value, element) {
var pattern = /[_+*.,!@#$%^&();/|\\?]/g;
return !pattern.test(value);
}, "Please enter alpha characters");
$.validator.addMethod("nonumber", function(value, element) {
var pattern = /[0-9]/g;
return !pattern.test(value);
}, "Please enter alpha characters");
// Date specific validators.
$.validator.addMethod("dateValidator", function(value, element) {
var pattern = /^([0]?[1-9]|[1][0-2])[/]([0]?[1-9]|[1|2][0-9]|[3][0|1])[/]([0-9]{4})$/;
$("#errorMessage").text('');
return value === "" || pattern.test(value);
}, "Please enter date using the format MM/DD/YYYY.");
$.each(obj, function(index, searchBox) {
var that = searchBox;
var $that = $('#' + that.id);
if (typeof searchBox.type !== 'undefined') {
if (searchBox.type === 'dateRangeStart') {
$.validator.addMethod("dateRangeStartValidator", function(value, element) {
if(value == null){
return false;
} else if (value === "") {
return true;
}
var currentDate = new Date();
var enteredDate = cs.parseDate(value);
return(enteredDate <= currentDate);
}, "Please enter a date not to exceed today's date.");
if(that.validate) {
$that.rules( 'add', {
required : false,
maxlength : 10,
dateValidator : true,
dateRangeStartValidator : true
} );
}
} else if (searchBox.type === 'dateRangeEnd') {
var errorMsg = "The end date is before the start date.";
if (typeof searchBox.errorMsg !== 'undefined') {
errorMsg = searchBox.errorMsg;
}
$.validator.addMethod("dateRangeEndValidator", function(value, element) {
if(value == null){
return false;
} else if (value === "") {
return true;
}
var enteredDate = cs.parseDate(value);
var startDate = cs.parseDate($('#'+searchBox.startDateId).val());
return !(enteredDate < startDate);
}, errorMsg);
if(that.validate) {
$that.rules( 'add', {
required : false,
maxlength : 10,
dateValidator : true,
dateRangeEndValidator : true
} );
}
} else if (searchBox.type === 'nospecialcharForName') {
if(that.validate) {
$that.rules( 'add', {
required : false,
nospecialchar : true,
nonumber : true
} );
}
}
} else {
if(that.validate) {
$that.rules( 'add', {
required : false,
nospecialchar : true
} );
}
}
if($that.placeholder) {
$that.placeholder();
}
$that.on('keyup', function(e) {
//DE1988 - The Available box in the filter gets refreshed for key down events Starts
if(!LN.isFnKeyPressed(e)){
return false;
}
//DE1988 - The Available box in the filter gets refreshed for key down events Ends
cs.data.initialize = false;
var keycode = e.keyCode;
var enteredValue = this.value === $(this).attr('placeholder') ? '' : this.value;
if(that.validate) {
if(!$(this).closest('form').valid()) {
return false;
}
}
var $target = $("#"+e.currentTarget.id);
if ($target.hasClass('disableKeyUpEvent')) {
$target.removeClass('disableKeyUpEvent');
return false;
}
cs.data.searchDone = enteredValue.length == 0 ? false : true;
cs.data.ajaxreload = true;
if(typeof lexisnexis.component.stratification != "undefined"){
cs.data.tablechange = true;
cs.data.url = cs.getAjaxURL('filterWithDefaultSortOnGroupByChange');
if ( that.limit ) {
if ( enteredValue.length >= that.limit || ( (enteredValue.length == that.limit - 1 || enteredValue.length == 0) && ( keycode == 8 || keycode == 46 ) ) ) {
cs.delay.call( cs, function () {
cs.initializeTable(cs.data.url);
}, 1000 );
}
} else {
cs.delay.call( cs, function () {
cs.initializeTable(cs.data.url);
}, 1000 );
}
} else if ( that.limit ) {
if ( enteredValue.length >= that.limit || ( (enteredValue.length == that.limit - 1 || enteredValue.length == 0) && ( keycode == 8 || keycode == 46 ) ) ) {
cs.delay.call( cs, function () {
that.table.fnReloadAjax(cs.data.url);
}, 1000 );
}
} else {
cs.delay.call( cs, function () {
that.table.fnReloadAjax(cs.data.url);
}, 1000 );
}
});
});
},
/**
* @method searchTermsJSON
*/
searchTermsJSON : function() {
var cs = this;
var returnJSON = {};
if(cs.data.searchFields && cs.data.searchFields.length > 0) {
$.each(cs.data.searchFields, function(index, value){
var val = $("#"+value.id+":visible").val();
returnJSON[value.id] = typeof val === "undefined" ? "" : val.length < value.limit ? "" : val;
});
}
return returnJSON;
},
timeout : [],
delay : function ( callback, ms ) {
clearTimeout( this.timeout );
this.timeout = setTimeout( callback, ms );
},
handleError: function(xhr, exception){
if(xhr.status==401){
document.location.href = LN.getContextPath() + '/j_spring_security_logout'
}
}
});