/**
* File Name: fumctions.php
* Date Created: 12/08
*
*/
/*
* Message box to display errors for a given Ext object
* protecting actual Javascript errors from throwing
*
* @param obj The Ext object to attempt to extract errors from
* @param type string value of the Ext type
*/
function displayErrors(obj, type) {
try {
switch (type) {
case 'store':
generateErrorWarning(obj.reader.jsonData.errors);
break;
case 'action':
if (typeof(obj.responseText) != 'undefined') {
var responseText = Ext.decode(obj.responseText);
if (typeof(responseText.errors) != 'undefined') {
generateErrorWarning(responseText.errors);
}
else if (typeof(responseText.session) != 'undefined') {
// Prompt for user data and process the result using a callback:
var prompt = Ext.ComponentMgr.get('loginWindow');
if (prompt == null) {
prompt = new EnertechXchange.CMS.Login({});
}
prompt.show();
}
}
else if (typeof(obj.result) != 'undefined') {
if (typeof(obj.result.errors) != 'undefined') {
generateErrorWarning(obj.result.errors);
}
}
break;
default:
throw 'Type passed to displayErrors is not known.';
}
}
catch(e) {
generateErrorWarning(e);
}
}
/*
* Display the error to the user
*
*/
function generateErrorWarning(oError) {
if (false) {
var error = "";
if (typeof(oError) == 'string') {
error = oError;
}
if ((typeof(oError) === 'object') || (typeof(oError) === 'array')) {
for (var i in oError) {
error += oError[i] + "
";
}
}
else {
// handle other types
}
Ext.create('widget.uxNotification', {
title: 'Errors!',
position: 't',
autoCloseDelay: 3000,
iconCls: 'iconError',
html: error.substring(0, error.length-2)
}).show();
}
else {
Ext.create('widget.uxNotification', {
title: 'Errors!',
position: 't',
autoCloseDelay: 3000,
iconCls: 'iconError',
html: 'An error occurred while processing the requested task.'
}).show();
}
}
/**
* Function to compare passed value to minimum and maximum values and
* set it accordingly
*
* @param {integer} value
* @param {integer} minimum
* @param {integer} maximum
* @return {integer}
*/
function setCorrectDimesionValue(value, minimum, maximum) {
var result = 0;
if (value > minimum && value < maximum) {
result = value;
} else if (value <= minimum) {
result = minimum;
} else if (value >= maximum) {
result = maximum;
}
return result;
}
/**
* Function to popup image in a window
* @param integer windowId
* @param string imageUrl
* @param string imageName
*/
function openImageWindow(windowId, imageUrl, imageName, imageWidth, imageHeight) {
/**
* compare image dimensions with default width and height and configure window accordingly
*/
var windowItemWidth = setCorrectDimesionValue(imageWidth, 450, 1000);
var windowItemHeight = setCorrectDimesionValue(imageHeight, 450, 600);
/**
* If not exists -> create closable/expandable window popup with image item inside
* If exists -> show
*/
if (!Ext.getCmp(windowId)) {
win = new Ext.Window({
closable: true,
closeAction: 'close',
width: windowItemWidth,
height: windowItemHeight,
constrain: true,
id: windowId,
layout: 'fit',
maximizable: true,
maximized: false,
plain: true,
title: imageName,
items: [{
autoScroll: true,
height: windowItemHeight,
html: '
',
width: windowItemWidth
}]
});
win.show();
} else {
Ext.getCmp(windowId).show();
}
}
/**
* Function to popup a preview
* @param integer windowId
* @param string imageUrl
* @param string imageName
*/
function openPreviewWindow(windowId, content, contentTitle) {
/**
* If not exists -> create closable/expandable window popup with image item inside
* If exists -> show
*/
if (!Ext.getCmp(windowId)) {
win = new Ext.Window({
closable: true,
closeAction: 'close',
height: 620,
constrain: true,
id: windowId,
layout: 'fit',
maximizable: true,
maximized: false,
plain: true,
title: contentTitle,
width: 800,
items: [{
id: 'previewItem',
autoScroll: true,
height: 620,
html : content,
width : 800
}]
});
win.show();
} else {
/*var win = Ext.getCmp(windowId);
var windowItem = Ext.getCmp(windowId).items.item('previewItem').el.dom;
var wrapDiv = Ext.DomQuery.selectNode("div", el);
*/
/**
* check if html is different and set content to newly passed value
*/
/*
if (wrap.innerHTML != content) {
wrap.innerHTML = content;
}
Ext.getCmp(windowId).doLayout();*/
win.show();
}
}
/*
* hash table simulation for javascript
*/
function javascriptHash(){
this.length = 0;
this.items = new Array();
for (var i = 0; i < arguments.length; i += 2) {
if (typeof(arguments[i + 1]) != 'undefined') {
this.items[arguments[i]] = arguments[i + 1];
this.length++;
}
}
this.removeItem = function(in_key)
{
var tmp_previous;
if (typeof(this.items[in_key]) != 'undefined') {
this.length--;
var tmp_previous = this.items[in_key];
delete this.items[in_key];
}
return tmp_previous;
}
this.getItem = function(in_key) {
return this.items[in_key];
}
this.setItem = function(in_key, in_value)
{
var tmp_previous;
if (typeof(in_value) != 'undefined') {
if (typeof(this.items[in_key]) == 'undefined') {
this.length++;
}
else {
tmp_previous = this.items[in_key];
}
this.items[in_key] = in_value;
}
return tmp_previous;
}
this.hasItem = function(in_key)
{
return typeof(this.items[in_key]) != 'undefined';
}
}
/**
* Unflag selected record
* passing record id and grid id to refresh
* after response is received
*
* @param {integer} recordId
* @param {integer} gridId
*/
function unflagRecord(recordId, gridId) {
Ext.Msg.show({
scope: this,
title: 'Unflag record',
msg: 'Are you sure you want to unflag this record?',
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.WARNING,
fn: function(response) {
if (response !== 'yes') {
return;
}
Ext.Ajax.request({
loadMask: true,
method: 'post',
scope: this,
url: 'ajax/flag_ajax.php',
waitMsg: 'Loading ...',
failure: function(form,action){
displayErrors(action, 'action');
},
params: {
'a': 'd',
'id': recordId
},
success: function(action, response) {
/**
* reload grid
*/
Ext.getCmp(gridId).store.reload();
}
});
}
});
}
/**
* Popup a form to enter reason for flagging a record
* @param {string} windowIdParam
* @param {string} table
* @param {string} windowTitle
* @param {integer} recordId
* @param {integer} gridId
*/
function showFlagPopup(windowIdParam, table, windowTitle, recordId, gridId) {
/**
* create popup
*/
var flagForm = new EnertechXchange.CMS.NotesPopupFormControl({
textareaLabel: 'Reason',
textareaName: 'reason_flagged',
textareaWidth: 247 + (247/2),
textareaHeight: 100,
clearBtnText: 'Clear',
clearBtnIconCls: 'iconReset',
saveBtnText: 'Save',
saveBtnIconCls: 'iconSave',
saveWithAjax: true,
textareaInvalidText: 'Please enter reason for flagging this record',
windowId: windowIdParam
});
if (!Ext.getCmp(windowIdParam)) {
/**
* create save button handler for save button of the popup
*/
flagForm.saveBtn.on('click', function(){
if (flagForm.textarea.getValue() != '') {
Ext.Ajax.request({
loadMask: true,
method: 'post',
scope: this,
url:'ajax/flag_ajax.php',
waitMsg: 'Loading ...',
failure: function(form,action){
displayErrors(action, 'action');
},
params: {
'a': 'save',
'id': recordId,
'rf': flagForm.textarea.getValue(),
'tn': table
},
success: function(action, response) {
/**
* reload grid here
*/
//Ext.Msg.alert('Success!', 'Record has been flagged successfully.');
Ext.getCmp(gridId).store.reload();
win.destroy();
}
});
} else { flagForm.textarea.markInvalid('Please enter reason for flagging this record');}
});
/**
* create popup window
*/
win = new Ext.Window({
closable: true,
closeAction: 'close',
height: 250,
constrain: true,
id: windowIdParam,
layout: 'fit',
maximizable: true,
maximized: false,
plain: true,
title: windowTitle,
width: 435,
items: [ flagForm ]
});
win.show();
} else {
win.show();
}
}
/**
* function to check if value exists in array
*/
function isValueInArray(myArray, myValue) {
var result = false;
var arrayLength = myArray.length;
for (var i = 0; i < arrayLength; i++) {
if (myArray[i] == myValue) {
result = true;
break;
} else { continue; }
}
return result;
}
/**
* Add new help content tab
* inside the Help Popup Tab Panel
* @param {string} passedUrl
* @param {integer} panelId
* @param {string} passedTitle
* @param {string} idLayout
* @param {string} passedIconCls
*/
function addHelp(passedUrl, panelId, passedTitle, idLayout, passedIconCls) {
var helpPanel = Ext.getCmp(panelId);
if (!Ext.getCmp(idLayout)) {
helpPanel.add(new Ext.Panel({
autoScroll: true,
iconCls: passedIconCls,
id: idLayout,
autoLoad: passedUrl,
border: false,
frame: false,
title: passedTitle,
closable: true
}));
helpPanel.doLayout();
helpPanel.setActiveTab(helpPanel.items.item(helpPanel.items.length-1));
} else {
Ext.getCmp(idLayout).show();
helpPanel.activate(helpPanel.getItem(idLayout));
}
}
/**
* Reload side panel help content
* @param {object} tab
*/
function reloadTabHelpContent(tab) {
if (tab.id != 'welcomeTab' && tab.id != 'mapPanel') {
/**
* check if active tab is the first tab -> if so, show grid help, otherwise show form help
*
* also check if content loaded is the import items form or reports form ->
* if so, do not need to reload help, it will be replaced in the activate event
* handler of both forms
*
*/
if (tab.items.item(0).getXType() != 'importItemsForm' && tab.items.item(0).getXType() != 'reportForm' && tab.items.item(0).getXType() != 'vumapReportForm' && tab.items.item(0).getXType() != 'vumapSubscriptions') {
if (tab.getActiveTab().id != tab.items.item(0).id) {
showHelp(tab.items.item(0).helpFormFile);
} else {
showHelp(tab.items.item(0).helpGridFile);
}
}
} else {
/**
* if only welcome tab is opened -> clear help panel
*/
if (tab.ownerCt.items.length == 1) {
var viewport = tab.ownerCt.ownerCt.ownerCt;
var helpPanel = viewport.items.item(1);
helpPanel.load({
url: 'help/Enertech_Xchange_User_Manual_October_2023.pdf'
});
}
}
}
/**
* Load file into side panel
* @param {string} passedUrl
*/
function showHelp(passedUrl) {
var helpPanel = mainPanel.items.item(0).items.item(1);
helpPanel.load({url: passedUrl});
}
/**
* Clear side help panel
*/
function clearHelpPanel() {
var helpPanel = mainPanel.items.item(0).items.item(1);
var helpText = helpPanel.items.item(0);
if (typeof(helpText) != 'undefined') {
helpPanel.remove(Ext.getCmp(helpText.getId()));
}
}
/**
* Show popup help
*/
function showHelpWindow() {
if (!Ext.getCmp('genericHelp')) {
win = new Ext.Window({
closable: true,
closeAction: 'close',
constrain: true,
id: 'genericHelp',
iconCls: 'iconHelp',
layout: 'fit',
maximizable: true,
maximized: false,
plain: true,
layout: 'fit',
title: 'Application Help',
width: '70%',
height: 500,
items: [ { html: '' }
/* new Ext.Panel({
autoScroll: true,
width: '65%',
autoLoad: {
url: 'help/Enertech_Xchange_User_Manual_October_2023.pdf',
scripts: true
}
}) */
]
});
win.show();
} else { win.show(); }
}
/**
* Compare start and end date
* to check whether start date is
* greater than end date
*
* @param {date} startDate
* @param {date} endDate
* @return {boolean}
*/
function compareDates(startDate, endDate) {
var result = true;
var start_date = startDate.parseDate(startDate.getValue()).format('m/d/Y');
var end_date = startDate.parseDate(endDate.getValue()).format('m/d/Y');
/**
* parse strings to get values for days, months, years
*/
var start_day = start_date.substring(start_date.indexOf('/') + 1, start_date.lastIndexOf('/'));
if (start_day.substring(0,1) == 0) {
start_day = start_day.substring(1);
}
var startDay = parseInt(start_day);
var end_day = end_date.substring(end_date.indexOf('/') + 1, end_date.lastIndexOf('/'));
if (end_day.substring(0,1) == 0) {
end_day = end_day.substring(1);
}
var endDay = parseInt(end_day);
var startMonth = parseInt(start_date.substring(0, start_date.indexOf('/')));
var endMonth = parseInt(end_date.substring(0, end_date.indexOf('/')));
var startYear = parseInt(start_date.substring(start_date.lastIndexOf('/') + 1));
var endYear = parseInt(end_date.substring(end_date.lastIndexOf('/') + 1));
if (startYear > endYear) {
result = false;
startDate.isValid(false);
startDate.markInvalid('Start date is greater than end date');
} else if (startMonth > endMonth) {
result = false;
startDate.markInvalid('Start date is greater than end date');
} else if (startDay > endDay) {
result = false;
startDate.markInvalid('Start date is greater than end date');
}
return result;
}
/**
* function to get grid data for csv creation
* and convert it to JSON format
*/
function getGridData(grid, table_name) {
var filters = grid.filters.getFilterData();
var search = grid.searchField.getValue();
var dataIndexes = new Array();
var headers = new Array();
/**
* get only visible columns, hidden are ignored;
* substruct one because of the details column
*/
for (var i = 0; i 0) {
sort = grid.store.sorters.getAt(0).property;
dir = grid.store.sorters.getAt(0).direction;
}
/**
* do it twice for layers because of
* the order column
*/
if (table_name != 'lasq_documents') {
// headers.shift();
// dataIndexes.shift();
}
/**
* popup confirmation,
* if ok -> submit with ajax
*/
Ext.Msg.show({
title: 'Export to CSV',
msg: 'Some of the data is not displayed in the grid because of limited space. It will be included in the export.',
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.WARNING,
scope: this,
fn: function(response) {
if (response !== 'yes') {
return;
}
grid.ownerCt.getEl().mask('Processing ...');
var request = Ext.Ajax.request({
scope: this,
method: 'post',
url: 'ajax/export_csv_ajax.php',
params: {
'a': 'save',
table: table_name,
sort: sort,
dir: dir,
'value': search,
filter: Ext.encode(filters),
columns: Ext.encode(headers),
indexes: Ext.encode(dataIndexes)
},
waitMsg: this.addBtnAjaxWaitMsg,
loadMask: this.addBtnLoadMask,
success: function(response) {
/**
* process success -> redirect to page that produces csv file
*/
grid.ownerCt.getEl().unmask();
var obj = Ext.JSON.decode(response.responseText);
window.location = 'export_csv.php?i=' + obj.identifier;
},
failure: function(action) {
/**
* process failure
*/
}
});
}
});
}
function getGridDataForReports(grid, table_name, type) {
var header = grid.columns[0];
var isChecked = header.el.hasCls(Ext.baseCSSPrefix + 'grid-hd-checker-on');
var dataIndexes = new Array();
var headers = new Array();
/**
* get only visible columns, hidden are ignored;
* substruct one because of the details column
*/
for (var i = 0; i < grid.columns.length; i++) {
if (!grid.columns[i].hidden) {
if (grid.columns[i].dataIndex != 'flagged') {
headers.push(grid.columns[i].text);
dataIndexes.push(grid.columns[i].dataIndex);
}
}
}
var sort = '', dir = '';
if (grid.store.sorters != null && grid.store.sorters.length > 0) {
sort = grid.store.sorters.getAt(0).property;
dir = grid.store.sorters.getAt(0).direction;
}
var items = [];
if (!isChecked) {
var selection= grid.getSelectionModel();
for(var i=0;i < grid.store.getCount();i++){
if(selection.isSelected(i)){
items.push(grid.store.getAt(i).data.rec_id);
}
}
}
/**
* do it twice for layers because of
* the order column
*/
if (table_name != 'lasq_documents') {
headers.shift();
dataIndexes.shift();
}
/**
* popup confirmation,
* if ok -> submit with ajax
*/
Ext.Msg.show({
title: 'Export to CSV',
msg: 'Some of the data is not displayed in the grid because of limited space. It will be included in the export.',
buttons: Ext.Msg.YESNO,
icon: Ext.MessageBox.WARNING,
scope: this,
fn: function(response) {
if (response !== 'yes') {
return;
}
grid.ownerCt.getEl().mask('Processing ...');
//var sort = '', dir = '';
//if (grid.store.sorters != null && grid.store.length > 0) {
// sort = grid.store.getAt(0).property;
// dir = grid.store.getAt(0).direction;
//}
var request = Ext.Ajax.request({
scope: this,
method: 'post',
url: 'ajax/export_csv_ajax.php',
params: {
'a': 'save',
table: table_name,
sort: sort,
dir: dir,
columns: Ext.encode(headers),
ids: items.join(','),
indexes: Ext.encode(dataIndexes),
thetype: type
},
waitMsg: this.addBtnAjaxWaitMsg,
loadMask: this.addBtnLoadMask,
success: function(response) {
/**
* process success -> redirect to page that produces csv file
*/
grid.ownerCt.getEl().unmask();
var obj = Ext.JSON.decode(response.responseText);
//alert('report.php?i=' + obj.identifier + '&mytype=' + type)
window.location = 'report.php?i=' + obj.identifier + '&mytype=' + type;
},
failure: function(action) {
/**
* process failure
*/
}
});
}
});
}
function getFTSGridDataForReports(grid, table_name, type) {
var header = grid.columns[0];
var isChecked = header.el.hasCls(Ext.baseCSSPrefix + 'grid-hd-checker-on');
var dataIndexes = new Array();
var headers = new Array();
/**
* get only visible columns, hidden are ignored;
* substruct one because of the details column
*/
for (var i = 0; i < grid.columns.length; i++) {
if (!grid.columns[i].hidden) {
if (grid.columns[i].dataIndex != 'flagged') {
headers.push(grid.columns[i].text);
dataIndexes.push(grid.columns[i].dataIndex);
}
}
}
var sort = '', dir = '';
if (grid.store.sorters != null && grid.store.sorters.length > 0) {
sort = grid.store.sorters.getAt(0).property;
dir = grid.store.sorters.getAt(0).direction;
}
var items = [];
if (!isChecked) {
var selection= grid.getSelectionModel();
for(var i=0;i < grid.store.getCount();i++){
if(selection.isSelected(i)){
items.push(grid.store.getAt(i).data.rec_id);
}
}
}
/**
* do it twice for layers because of
* the order column
*/
if (table_name != 'lasq_documents') {
headers.shift();
dataIndexes.shift();
}
/**
* popup confirmation,
* if ok -> submit with ajax
*/
Ext.Msg.show({
title: 'Export to CSV',
msg: 'Some of the data is not displayed in the grid because of limited space. It will be included in the export.',
buttons: Ext.Msg.OK,
icon: Ext.MessageBox.WARNING,
scope: this,
fn: function(btn) {
if (btn !== 'ok') {
return;
}
//grid.ownerCt.getEl().mask('Processing ...');
var inputForm = new Ext.FormPanel({
id: 'inputForm',
method: "POST",
items: [{
xtype: 'hiddenfield',
name: 'query',
value: Ext.getCmp('fullTextSearchField').getValue()
}, {
xtype: 'hiddenfield',
name: 'program_id',
value: mainPanel.programId
}, {
xtype: 'hiddenfield',
name: 'sort',
value: sort
}, {
xtype: 'hiddenfield',
name: 'dir',
value: dir
}, {
xtype: 'hiddenfield',
name: 'start',
value: 0
}, {
xtype: 'hiddenfield',
name: 'limit',
value: 0
}, {
xtype: 'hiddenfield',
name: 'csvreport',
value: 1
}
]
,standardSubmit: true
});
console.log(inputForm);
inputForm.submit({
target: '_blank',
url: "search.php"
});
setTimeout(function () {
inputForm.destroy();
}, 200);
}
});
}
function showFlaggedReasonOnAForm(panel, value) {
var flagged_reason = '' +
'
' +
' | ' +
' | ' +
'' + value + ' | ' +
'
' +
'
';
panel.add({
border: false,
frame: false,
html: flagged_reason
});
panel.doLayout();
}
function refreshGrid(grid) {
grid.store.reload();
}
function removeTabEvent(tabpanel, tab) {
Ext.Msg.show({
title:'Remove tab?',
msg: 'Are you sure?',
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION,
fn: function(btn, text) {
if(btn == 'yes') {
tabpanel.un('beforeremove', removeTabEvent);
tabpanel.remove(tab);
tabpanel.addListener('beforeremove', removeTabEvent, tabpanel); /* I add only this line */
}
}
});
return false;
}
function unmaskObj(objId) {
Ext.getCmp('mapSearchPanelExtJS').getEl().unmask();
if (!Ext.isIE && !Ext.isOpera) {
window.stop();
} else if (Ext.isIE || Ext.isOpera) {
document.execCommand('Stop');
//window.document.execCommand('Stop');
}
}
function handlePossibleSessionTimeout(errorText) {
if (typeof(errorText) != 'Object') {
throw 'Not a session timeout';
}
else if (typeof(errorText) != 'String') {
if (errorText.indexOf('session') >= 0) {
// Prompt for user data and process the result using a callback:
var prompt = Ext.ComponentMgr.get('loginWindow');
if (prompt == null) {
prompt = new EnertechXchange.CMS.Login({});
}
prompt.show();
}
}
}
// function to dynamically add layers trees and content
// loads the whole map tree at once
function appendTreeChildren(store) {
/* var hasChildren = node.childNodes.length;
if (hasChildren > 0) {
if (node.data.depth == 0) {
node.removeAll();
node.set('loaded', false);
}
}*/
//node.data.name = 'Program Layers';
//node.expand();
store.setRootNode('test');
var rootNode = store.getRootNode();
//console.log('from functions: ' + rootNode)
//return;
var contents = myLayers.returnValue;
var contentsLength = myLayers.returnValue.length;
for (var i = 0; i < contentsLength; i++) {
var child = new Object();
child.id = contents[i].id;
child.layer_id = contents[i].layer_id;
child.display_name = contents[i].display_name;
child.subscription_id = contents[i].subscription_id;
child.start_date = contents[i].start_date;
child.end_date = contents[i].end_date;
child.svis = contents[i].svis;
child.visibility = contents[i].visibility;
child.min_zoom = contents[i].min_zoom;
child.max_zoom = contents[i].max_zoom;
child.wms_name = contents[i].wms_name;
child.opacity = contents[i].opacity;
child.dorder = contents[i].dorder;
child.color = contents[i].color;
child.isGoogle = contents[i].isGoogle;
child.layer_type = contents[i].layer_type;
child.table_name = contents[i].table_name;
child.leaf = true;
child.expanded = false;
rootNode.appendChild(child);
} // end of for
rootNode.expand();
}