/**
* print_form_record.js
* Process for printing form record in WebApps
*/
/**
* Assign events for print data (on WebApps)
* , include button [Print] and so on ...
*/
// The limit time for waiting download report file (default is 3 minute)
var WAITING_TIME_DOWNLOAD_FILE_REPORT = 30 * 1000;
// Global variable using for generating Group Index
var mapGroupCount4WA = new Object();
// Store current group index browsing
var currentGroupIndex4WA = '';
// Fix bug 0019175: Date:Time Settings - Print View - Value of Time/Cal display incorrectly in case Setting uncheck DST but User check DST(GMT-5)
// Store the current TimezoneOffset of Client Browser
var nowTimezoneOffset4WA = -(new Date()).getTimezoneOffset() * 60 * 1000;
function initAll4PrintDataWebApps() {
// Adjust URL server into HTTPS protocol in case of main version
var fullUrl = window.location.href;
// Process URL server based on current full URL
var domain = /:\/\/([^\/]+)/.exec(fullUrl)[1];
if (fullUrl.indexOf('https://') == 0) {
glbHashObject['url_server'] = 'https://' + domain;
} else {
// Default case
glbHashObject['url_server'] = 'http://' + domain;
}
writeToLogInfoRequired('the current url_server : ' + glbHashObject['url_server']);
$('.liFvPrintForm .fvPrintForm').on('click', function() {
// PCA-612 : Webclient & Web forms | Action Button - Addition, to add printing support for Web Client Only
var extraConfig = {
autoClickPrint : true
,autoCloseAfterPrint : true
};
var hideLogo = getQuerystring('hideLogo');
if(hideLogo == 'true'){
extraConfig.hideLogo = true;
}
processShowPrintScreen4WebApps(extraConfig);
});
}
/**
* Prepare data for showing PrintPreview for WebApps
*/
function processShowPrintScreen4WebApps(extraConfig) {
// Fix bug 0019175: Date:Time Settings - Print View - Value of Time/Cal display incorrectly in case Setting uncheck DST but User check DST(GMT-5)
// Update the value of nowTimezoneOffset4WA
nowTimezoneOffset4WA = -(new Date()).getTimezoneOffset() * 60 * 1000;
// Validate data
if (fvDataNS.inputData === undefined) {
return;
}
// Collect all current data into JSONObject
var jsonDataPrint = {};
// Save current data to server for using later
// Put current information (userKey, projectId, formId)
jsonDataPrint.userKey = authNS.currentUser.UserKey;
if(typeof jsonDataPrint.userKey == 'undefined' || jsonDataPrint.userKey == '') {
jsonDataPrint.userKey = authNScurrentUserUserKey;
}
jsonDataPrint.customerKey = fvDataNS.currentForm.customerKey;
jsonDataPrint.projectId = fvDataNS.inputData.attrs.projectid;
jsonDataPrint.formId = fvDataNS.inputData.attrs.id;
jsonDataPrint.formName = '';
if(extraConfig && extraConfig.printPreview){
jsonDataPrint.printPreview = true;
jsonDataPrint.formSetting = JSON.stringify(glbBuildFormSettingsWA);
jsonDataPrint.formStructure = JSON.stringify(fvDataNS.currentForm.controls);
jsonDataPrint.formXml = ' ';
}
// Create the data all in JSON string
var dataAll = processDataAllCurrentRecord4WA(jsonDataPrint);
jsonDataPrint.DataAll = dataAll;
// Fix bug 0026629: Hide in PDF and Print / Hide in View Data and Dispatch work incorrectly with choose One / Select Multiple in Questionnaire
writeToLogInfo('isWebClient : ' + isWebClient);
jsonDataPrint.isWebClient = isWebClient;
// 0026952: % Total score is wrong on email report in case uncheck Show decimal value
// Put the value of category score from WebApps GUI (from file formViewUtils.js)
jsonDataPrint['@mapCategoryScoresGUI_WebApp'] = mapCategoryScoresGUI4WebApp;
// Save current data into server
var requestDataInJSON = JSON.stringify(jsonDataPrint);
writeToLogInfo('requestDataInJSON.length :: ' + requestDataInJSON.length);
var processAjaxSuccess = function(response){
// Get the flag about using Backends
glbHashObject['isUsingBackends4PR'] = response.isUsingBackends4PR;
writeToLogInfoRequired('isUsingBackends4PR :: ' + response.isUsingBackends4PR);
// Check result getting from server
// + cacheId
// + DataBlobKey
// + DataBlobSize
if (response == null) {
jAlert(err_support_unknown);
return;
}
if (response.cacheId === undefined || response.cacheId === null
|| response.DataBlobKey === undefined || response.DataBlobKey === null) {
jAlert(err_support_unknown);
return;
}
var formNameSummary = formName;
if (formNameSummary.length > 20) {
formNameSummary = formNameSummary.substring(0,20);
}
// Because we are in version 1.3 later, we will use file PrintPreview2.html
var htmlParams = "?id=" + getRandomString()
+ "&cacheId=" + response.cacheId
+ "&name=" + formNameSummary;
// Put the taskInfoKey for using in Backends
if (response.taskInfoKey !== undefined) {
htmlParams += '&taskInfoKey=' + response.taskInfoKey;
}
var isProcessSilentMode = false;
// Check if we need auto click button [Print]
if (typeof extraConfig !== 'undefined' && extraConfig !== null) {
if (extraConfig.autoClickPrint === true) {
htmlParams += '&autoClickPrint=true';
isProcessSilentMode = true;
}
// Check if we need close the print GUI after click button Print
if (extraConfig.autoCloseAfterPrint === true) {
htmlParams += '&autoCloseAfterPrint=true';
}
if (extraConfig.hideLogo === true) {
htmlParams += '&hideLogo=true';
}
}
// // Put flag value for ExcelReport
// if (isExcelReport != undefined && isExcelReport != null && isExcelReport == true) {
// htmlParams = htmlParams + "&isExcelReport=true";
// }
// Check if we need process in silent mode
// (only apply on Firefox + Safari)
try {
if (isProcessSilentMode === true && browserNameGlobal !== 'ie' && browserNameGlobal !== 'chrome') {
// Process PrintPreviewWA in silent mode
processPrintViewWAInSilentMode(htmlParams);
return;
}
} catch (e) { }
window.open("/html/PrintPreview4WA.html" + htmlParams
,"","location=no,scrollbars=1,width=800,height=600,resizable=yes");
}
waitForDataLoading(true);
$.ajax({
url: '/Print4WAServlet' ,
dataType: 'json', //text/html
type: 'POST',
data: requestDataInJSON,
cache: false,
complete : function() {
waitForDataLoading(false);
},
success: function(response, status) {
processAjaxSuccess(response);
},
error: function(request, status, error) {
if(status == 'parsererror' && request.responseText){
processAjaxSuccess(JSON.parse(request.responseText));
return;
}
jAlert(err_support_unknown);
}
});
}
// Generate random string
function getRandomString(totalNumbers){
var sessionid = '';
if (totalNumbers === undefined) {
totalNumbers = 10;
}
var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZ";
for (var i=0; i < totalNumbers; i++) {
var rnum = Math.floor(Math.random() * chars.length);
sessionid += chars.substring(rnum,rnum+1);
}
return sessionid;
}
/**
* Process printing data
*/
function processPrintData4WebApps() {
// Apply print status for osm_map_region
$('#osm_map_region').removeClass('osm_map_region_print');
// Put the standard page size A4
if (browserNameGlobal == 'ie') {
// Control in CSS
} else if (browserNameGlobal == 'chrome') {
$('#PrintRegionData').addClass('PrintRegionData4Chrome');
} else if (browserNameGlobal == 'firefox') {
// Control in CSS
} else if (browserNameGlobal == 'safari') {
// Process browser of Chrome and Safari
$('#PrintRegionData').addClass('PrintRegionData4Safari');
}
// Hide all dash-line for breaking pages (previous hide for printing)
$('.dash_line_for_separating_between_pages').hide();
// Hide all [PageNumber] for printing
$('.page_number_for_printview_html').hide();
// Show map and markers in printing mode
showMapAndMarkers(true);
window.print();
// Make sure the print okie after restoring the GUI in normal print view (HTML)
setTimeout('restoreGUITimeout();', 1000);
}
/**
* Process HTML content for current print form record
*/
function processHTMLPrintFormRecord4WebApps() {
// Hide unused controls (Settings)
//$('.btnPrint_EmailPageSetting').hide();
var isExcelReport = getQuerystring('isExcelReport');
// / Hide all menu related to Excel Report feature in case of Print PDF screen
if (isExcelReport == undefined || isExcelReport == null || isExcelReport == CONST_VALUE_FALSE_STR) {
// Hide all menu related to Excel Report feature
//$('.btnPrint_ExcelTemplate, .btnPrint_EmailExcelTemplate').hide();
} else {
// Show all button related Pdf Report
$('.btnPrint_Submit,.btnPrint_Email,.btnPrint_Save,.btnPrint_EmailPageSetting,.btnPrint_Close')
.removeClass('hiddenMenuItem');
// Show the bottom menu items (main menu)
$('.menuItem4PrintPreview#bottomMenuId').removeClass('hiddenMenuItem');
// Process hide all menu items in case AutoClickPrint (View-Edit Record, WebApps)
var autoClickPrint = getQuerystring('autoClickPrint');
if (autoClickPrint == CONST_VALUE_TRUE_STR) {
// Hide all menu items
$('.print_preview_body .menuItem4PrintPreview').addClass('hiddenMenuItem');
// Hide the header lines
$('.print_preview_body #idLineFormatHeaderPrintPreview').hide();
}
}
// The cacheId from query string (from Address of Browser)
var cacheIdValue = getQuerystring('cacheId');
// Store cacheIdValue into global variable
glbHashObject['PrintDataObject_cacheId'] = cacheIdValue;
// Getting data from server (store in session)
waitForDataLoading(true);
// Reset the value of global variables (for Appearance)
// PCA-266 Print Preview/PDF support for color option in Grids, questionnaires and Tables
indexOfAppearanceShadingHeadings = 0;
builderAppearanceShadingHeadings = new Array();
// PCA-299: PDF/Print Preview support for Down/Across option for ChooseOne, SelectMultiple & Score
// Rest the list of Controls need refresh layout in PDF Preview
listSelectControlsNeedRefreshInPDF = new Array();
var processAjaxSuccess = function(response){
// Get the flag about using Backends
glbHashObject['isUsingBackends4PR'] = response.isUsingBackends4PR;
writeToLogInfoRequired('isUsingBackends4PR :: ' + response.isUsingBackends4PR);
// Update global variable for Shading in PDF (same as Shading in WebApps)
updateGlobalVariable4ShaddingAndButtonTextBuildFormsInPDF(response);
writeToLogInfo('Finish update global Shading in PDF (WA) ... ' + JSON.stringify(glbBuildFormSettingsWA));
// Checking the error status
if (response.error_status !== undefined && response.error_status == 'INVALID_PRINT_RECORD') {
jAlert(msg_print_record_item_invalid, null, function() {
window.close();
});
return;
}
// Fill data getting from server
if (response.result == false) {
jAlert(msg_unknown_error, null, function() {
window.close();
});
return;
}
var pageSetting = response.page_settings;
if (pageSetting == null) {
jAlert(msg_unknown_error, null, function() {
window.close();
});
return;
}
glbHashObject['print_page_settings'] = pageSetting;
glbHashObject['url_server'] = response.url_server;
glbHashObject['response_object'] = response;
glbHashObject['is_premier_google_account'] = response['google.is_premier_account'];
// Update list of Decimal fields
listAllDecimalFields = glbHashObject['response_object'].listAllDecimalFields;
// Assign privilege value (for checking ReadOnly user later)
if (response.userPrivilege !== undefined && response.userPrivilege !== null) {
glbHashObject['userPrivilege'] = response.userPrivilege;
} else {
glbHashObject['userPrivilege'] = '';
}
// Store current form id, form name
$('#form_id').val(response.formId);
$('#form_name').val(response.form_name);
// Hide all menu related to Excel Report feature
//$('.btnPrint_ExcelTemplate, .btnPrint_EmailExcelTemplate').hide();
// Clear all data of print view
$('#PrintRegionData').empty();
// Reset the global values
glbHashObject['put_block_left_status'] = true;
// Update the DOCUMENT_HEIGHT based on current browser
updateDocumentHeight();
// Process HTML data based on page_settings
var htmlData = new Array();
var dataAll = response.DataAll_Result;
if (dataAll == undefined || dataAll == null) {
//jAlert(msg_unknown_error);
jAlert(msg_unknown_error, null, function() {
window.close();
});
return;
}
// The list question after PageBreak question (based on Report Settings)
var listQuestionAfterPageBreak = response.listQuestionAfterPageBreak;
// The list question that is the first item inside Group (based on Report Settings)
var listFirstItemInsideGroup = response.listFirstItemInsideGroup;
// The mapping of field name/top group name, only using for page break
var topGroupMapping4PageBreak = response.topGroupMapping4PageBreak;
// PCA-406: Report Settings [] show buttons and check boxes in PDF same as PDF
// Extract questions inside TableScore into special zone for using later
//dataAll = processTableScoreDataAll(dataAll, response.TableScoreMappingData, pageSetting);
htmlData.push('
');
var hideLogo = getQuerystring('hideLogo');
if(hideLogo == 'true'){
hideLogo = true;
}else{
hideLogo = false;
}
// Adding logo, Form Title, Header Block (Record Name, Mobile Device Number, Date Created)
if (response.page_settings.display_logo == true && !hideLogo) {
var logoTemplate = '
';
htmlData.push(logoTemplate.replace('#logo_path#',
'
')
);
}
// Add title based on []Display form name setting
if (pageSetting.display_form_name === true) {
var formTitleTemplate = '
';
// Apply tag
into Print/PDF
//htmlData.push(formTitleTemplate.replace('#form_name#', replaceTagBR2LineFeed(response.form_name)));
htmlData.push(formTitleTemplate.replace('#form_name#', response.form_name));
}
// PCA-180: PDF support for Shading and Spacing
//htmlData.push(createHeaderBlock(response.header_block));
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
// PCA-406: Report Settings [] show buttons and check boxes in PDF same as PDF
//htmlData.push(createHeaderBlockSHADING(response.header_block, pageSetting.two_column_format));
} else {
htmlData.push(createHeaderBlock(response.header_block));
}
htmlData.push(' ');
// Put header data into print region
$('#PrintRegionData').append(htmlData.join(''));
var length = dataAll.length;
var tableLayout = new Object();
tableLayout.start = '';
tableLayout.center_separator_column = ' | ';
tableLayout.count = 0;
// The list of table in 1 column layout
var listTable = new Array();
// The list of blocks in 2 column layout
var listBlocks = new Array();
// Reset pageNumber4PrintPreviewCounter
pageNumber4PrintPreviewCounter = 1;
// The list of Markers
var printPageMarkers = new Array();
var hasExistMap = false;
for (var i = 0; i < length; i++) {
var data = dataAll[i];
// Fix error when not defined of name/value/hints/header
if (data['name'] === undefined) {
continue;
}
// Set default value in case of undefined
if (data['header'] === undefined) { data['header'] = ''; }
if (data['hints'] === undefined) { data['hints'] = ''; }
if (data[CONST_VALUE] === undefined) { data[CONST_VALUE] = ''; }
// Create block data based on it's type
// Apply tag
into Print/PDF
// var header = replaceTagBR2LineFeed(data['header']);
// var hints = replaceTagBR2LineFeed(data['hints']);
var header = data['header'];
var hints = data['hints'];
var value = data[CONST_VALUE];
var name = data['name'];
var orgName = name.replace(/\(.+/g, '');
// PCA-180: PDF support for Shading and Spacing
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
if (data['type'] === CONST_CTRL_TYPE_GROUP) {
// Do nothing because it's group
} else {
if (pageSetting.display_data_name === true) {
header = orgName;
} else {
var groupTailLength = name.length - orgName.length;
if (groupTailLength > 0) {
header = header.substring(0, header.length - groupTailLength);
}
}
}
// Ignore the question with header == '' + value == '' + hints == ''
if (header === '' && hints === '' && value === ''
&& data['type'] !== CONST_CTRL_TYPE_CTRLSCORETABLE
&& data['type'] !== 'inputLabel'
) {
continue;
}
}
var caption = getDisplayHeader(header, false);
switch (data['type']) {
case 'inputLabel' :
//block = createLabelBlock(data['header'], hints, value);
//block = createLabelBlock(data['header'], hints, value, data['alignment'], pageSetting.two_column_format, data);
// PCA-180: PDF support for Shading and Spacing
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
// CO-262: Blank Labels in PDF's
block = createLabelBlockSHADING(data['header'], hints, value, data['alignment'], pageSetting.two_column_format, data, pageSetting);
} else {
block = createLabelBlock(data['header'], hints, value, data['alignment'], pageSetting.two_column_format, data);
}
// PCA-190, PCA-214
if (block === '') { continue; }
break;
case CONST_CTRL_TYPE_INPUTACTION :
// Do nothing
break;
case CONST_CTRL_TYPE_INPUTPAYMENT :
// Do nothing
break;
case mdi_kind_inputImage :
case mdi_kind_image :
case mdi_kind_inputSketch :
case mdi_kind_sketch :
// PCA-180: PDF support for Shading and Spacing
//block = createImageBlock(caption, hints, value);
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
var url_server = response.url_server;
block = createImageBlockSHADING(header, hints, value, data, pageSetting, url_server);
} else {
block = createImageBlock(caption, hints, value);
}
break;
case mdi_kind_inputSignature :
case mdi_kind_signature :
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createSignatureBlockSHADING(header, hints, value, data);
} else {
block = createImageBlock(caption, hints, value);
}
break;
case mdi_kind_audio :
case mdi_kind_inputAudio :
// PCA-180: PDF support for Shading and Spacing
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createAudioBlockSHADING(header, hints, value, data);
break;
}
// With old version, we will create general block
case mdi_kind_video :
case mdi_kind_inputVideo :
// PCA-180: PDF support for Shading and Spacing
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createVideoBlockSHADING(header, hints, value, data);
break;
}
// With old version, we will create general block
case CONST_CTRL_TYPE_INPUTLOCATION :
hasExistMap = true;
caption = getDisplayHeader(header, true);
// PCA-245: Embed static maps into PDF/Excel Template
//block = createLocationBlock(caption, hints, value);
if (isVersion(VERSION_EMBBED_STATIC_MAP_PDF_EXCEL)) {
//block = createLocationBlock4EmbbedGPSImage(caption, hints, value, data, pageSetting);
block = createLocationBlockSHADING(header, hints, value, data, pageSetting);
} else {
block = createLocationBlock(caption, hints, value);
}
// Process for adding new marker
var lat = value.lat;
var lng = value.lng;
if (lat != null && lat != undefined && lat != '' && lat != 'no-gps'
&& lng != null && lng != undefined && lng != '' && lng != 'no-gps') {
printPageMarkers.push(value);
}
break;
case CONST_CTRL_TYPE_INPUTSELECTMANY :
// PCA-180: PDF support for Shading and Spacing
//block = createSelectMultipleBlock1(caption, hints, value, data, response.SelectionsDataMappingInCaptions);
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createSelectGeneralBlockSHADING(header, hints, value, data
, response.SelectionsDataMappingInCaptions
, response.SelectionsDataMappingInUnderlineValue
, pageSetting
);
} else {
block = createSelectMultipleBlock1(caption, hints, value, data, response.SelectionsDataMappingInCaptions);
}
break;
case CONST_CTRL_TYPE_INPUTSELECTONE :
case CONST_CTRL_TYPE_INPUTSCOREONE :
// PCA-180: PDF support for Shading and Spacing
//block = createSelectMultipleBlock1(caption, hints, value, data, response.SelectionsDataMappingInCaptions);
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
var isShowAsSlider = false;
if(isVersion(VERSION_CHOOSE_ONE_SLIDER)){
if(data.optionKind == CONST_CHOOSE_ONE_SWITCH){
isShowAsSlider = true;
}
}
if(isShowAsSlider){
block = createSelectSliderBlockSHADING(header, hints, value, data
, response.SelectionsDataMappingInCaptions
, response.SelectionsDataMappingInUnderlineValue
, pageSetting
);
}else{
if ((data.type === CONST_CTRL_TYPE_INPUTSELECTONE || data.type === CONST_CTRL_TYPE_INPUTSCOREONE) && data.displayType === CONST_DROPDOWN) {
block = createTextBlockSHADING(header, hints, replaceTagBR2LineFeed(value), data);
} else {
block = createSelectGeneralBlockSHADING(header, hints, value, data
, response.SelectionsDataMappingInCaptions
, response.SelectionsDataMappingInUnderlineValue
, pageSetting);
}
}
break;
}
case CONST_CTRL_TYPE_CTRLTABLE :
// PCA-212 : Print Preview/PDF support for Text Calculations
//block = createInvoiceTableBlock(caption, hints, value, data['fixedTableTypes'], data['fixedTableKinds'], data['fixedTableCurrency'], pageSetting.two_column_format, data['fixedTableDataNameHeader'], data);
// PCA-180: PDF support for Shading and Spacing
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
// Apply Hide > []Non-selected radio buttons and checkboxes
block = createInvoiceTableBlockSHADING(header, hints, value, data['fixedTableTypes'], data['fixedTableKinds'], data['fixedTableCurrency'], pageSetting.two_column_format, data['fixedTableDataNameHeader'], data
, response.SelectionsDataMappingInCaptions
, response.SelectionsDataMappingInUnderlineValue
, pageSetting
);
} else {
// Old method
block = createInvoiceTableBlock(caption, hints, value, data['fixedTableTypes'], data['fixedTableKinds'], data['fixedTableCurrency'], pageSetting.two_column_format, data['fixedTableDataNameHeader'], data);
}
break;
case CONST_CTRL_TYPE_CTRLPOD :
// Apply control POD (same as fixed table)
var mapPODTable = response['@MapPODTable'][orgName];
block = createPODBlockSHADINGHelper(header, hints, data
, POD_TOP_TABLE
, response.SelectionsDataMappingInCaptions
, response.SelectionsDataMappingInUnderlineValue
, pageSetting
, mapPODTable
);
break;
case CONST_CTRL_TYPE_CTRLGRID :
// PCA-174 (PDF/Excel Reports support for New Grid Type)
//block = createGridBlock(caption, hints, value, data['number_of_column_in_grid'],pageSetting.two_column_format, pageSetting, data);
// PCA-180: PDF support for Shading and Spacing
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createGridBlockSHADING(header, hints, value, data['number_of_column_in_grid'],pageSetting.two_column_format, pageSetting, data
, response.SelectionsDataMappingInCaptions
, response.SelectionsDataMappingInUnderlineValue
);
} else {
// Old method
block = createGridBlock(caption, hints, value, data['number_of_column_in_grid'],pageSetting.two_column_format, pageSetting, data);
}
break;
case CONST_CTRL_TYPE_CTRLSCORETABLE :
// Get current caption
//block = createTableScoreBlock(caption, hints, data, response.TableScoreMappingData, pageSetting);
// PCA-180: PDF support for Shading and Spacing
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createTableScoreBlockSHADING(header, hints, data, response.TableScoreMappingData, pageSetting);
} else {
// Old method
block = createTableScoreBlock(caption, hints, data, response.TableScoreMappingData, pageSetting);
}
break;
case CONST_CTRL_TYPE_INPUTATTACHMENT :
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
var url_server = response.url_server;
block = createImageBlockSHADING(header, hints, value, data, pageSetting, url_server);
} else {
block = createImageBlock(caption, hints, value);
}
break;
default :
// Setting default data for null value
if (value == undefined || value == null) {
value = "";
}
if (data['type'] != CONST_CTRL_TYPE_INPUT_TEXT && value == 'null') {
value = '';
}
// Special processing currency for Number/Calculation controls
if (data['type'] === CONST_CTRL_TYPE_INPUTCALCULATE
|| data['type'] === 'Integer' || data['type'] === 'Decimal'
|| data['type'] === CONST_CTRL_TYPE_INPUT_NUMERIC
|| data['type'] === CONST_CTRL_TYPE_INPUTTRENDS
) {
if (isVersion(VERSION_CALCULATION_KIND_STRING)
&& data['type'] === CONST_CTRL_TYPE_INPUTCALCULATE
&& data['dataKind'] === 'String') {
// 0024949: PDF Report - Text Calculation displays incorrectly (add commas for thousands) incase all values of operand are number
// DO NOTHING because it's a Text Calculation
} else {
if (value != '') {
if (data['_useCurrentcySymbol'] !== undefined && data['_useCurrentcySymbol'] === CONST_VALUE_TRUE_STR) {
var currencySymbol = data['_currencySymbol'];
if (currencySymbol === undefined || currencySymbol === null) {
currencySymbol = '$';
}
// Apply format number using currency with format ,
value = formatNumberValue4Currency(value, currencySymbol, data['type'], orgName);
} else {
// Special treating with Decimal type and NO CURRENCY
value = formatDecimalNumberWithoutCurrency(value, data, orgName);
}
}
}
// PCA-212 : Print Preview/PDF support for Text Calculations
if (isVersion(VERSION_CALCULATION_KIND_STRING)) {
if (data['type'] === CONST_CTRL_TYPE_INPUTCALCULATE
&& data['showAsTextMobile'] === true) {
// Clear caption and hints
caption = '';
hints = '';
}
}
}
if (data['type'] == CONST_CTRL_TYPE_INPUTEMAILREPORT ||
data['type'] == CONST_CTRL_TYPE_INPUTFAX ||
data['type'] == CONST_CTRL_TYPE_INPUTSECUREEMAILREPORT) {
// PCA-180: PDF support for Shading and Spacing
//block = createEmailReportBlock(caption, hints, value);
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createEmailReportBlockSHADING(header, hints, value, data);
} else {
block = createEmailReportBlock(caption, hints, value);
}
} else if (data['type'] == CONST_CTRL_TYPE_INPUTSCORESUMMARY) {
// PCA-294: PDF/Preview - Apply new block formats for all widgets.
block = createScoreSummaryBlockSHADING(header, hints, value, data);
} else {
// if (data['type'] == CONST_CTRL_TYPE_INPUT_TEXT) {
// Special treating for TEXT (Replace line feed of PDF \n into HTML line feed (
)
// Only affected in normal case or email normal, NOT IN EMAIL REPORT
// Process other normal cases
value = value + '';
if (typeof value === 'string' || value instanceof String) {
if (value != null && value != '') {
value = value.replace(/\n/g,'
');
}
}
// 0024855: PDF Report: Text Calculation - Mobile text align works incorrectly
if (data['type'] === CONST_CTRL_TYPE_INPUTCALCULATE) {
// Process create Calculation
block = createCalculationBlockSHADING(header, hints, replaceTagBR2LineFeed(value), data);
break;
}
// Replace special <br> into LINE FEED html
// PCA-180: PDF support for Shading and Spacing
//block = createGeneralBlock(caption, hints, replaceTagBR2LineFeed(value));
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createTextBlockSHADING(header, hints, replaceTagBR2LineFeed(value), data);
} else {
block = createGeneralBlock(caption, hints, replaceTagBR2LineFeed(value));
}
}
//block = createGeneralBlock(caption, hints, value);
break;
}
// Put the previous PageBreak for current question
// (Ignore the first position)
var isForcePageBreak = false;
// []Convert PageBreak question into page break
var checkName = orgName;
// Special treating with question inside Group
// We will check top group name
if (name.indexOf('(') > 0) {
if (topGroupMapping4PageBreak[orgName] !== undefined && topGroupMapping4PageBreak[orgName] !== null) {
var topGroup = topGroupMapping4PageBreak[orgName];
checkName = topGroup;
}
}
var indexOfFieldInPageBreak = listQuestionAfterPageBreak.indexOf(checkName);
if (indexOfFieldInPageBreak >= 0 && pageSetting.page_break_question_to_actual_page_break === true && i !== 0) {
isForcePageBreak = true;
// Remove current name out of listQuestionAfterPageBreak
listQuestionAfterPageBreak.splice(indexOfFieldInPageBreak, 1);
}
// Each loop in repeatable section start a new page
else if (listFirstItemInsideGroup.indexOf(name) >= 0 && pageSetting.page_break_for_loop_question === true && i !== 0) {
isForcePageBreak = true;
}
// PCA-219: Print Preview/PDF support for Remove space options
// Put block into page
putBlockIntoPage(block, pageSetting.two_column_format, isForcePageBreak, data);
// Special treating with POD table (created from multiple fragments)
if (data['type'] === CONST_CTRL_TYPE_CTRLPOD) {
// Get structure of current POD
var mapPODTable = response['@MapPODTable'][orgName];
if (mapPODTable['~showOSDReport'] === true) {
var blockQuery = '';
if (mapPODTable['~showOSDReportType'] === 'across') {
// Show OSD report (in table), layout ACROSS
blockQuery = createPODBlockSHADINGHelper(header, hints, data
, POD_OSD_REPORT
, response.SelectionsDataMappingInCaptions
, response.SelectionsDataMappingInUnderlineValue
, pageSetting
, mapPODTable
);
} else {
// Layout DOWN
blockQuery = createPODOSDReportInDownLayout(header, hints, data);
}
// Put block into page
putBlockIntoPage(blockQuery, pageSetting.two_column_format, isForcePageBreak, data);
}
// Check if we need show the Delivered Table of POD
if (mapPODTable['~showDeliveredPickupReport'] === true) {
var block1 = createPODBlockSHADINGHelper(header, hints, data
, POD_DELIVER_TABLE
, response.SelectionsDataMappingInCaptions
, response.SelectionsDataMappingInUnderlineValue
, pageSetting
, mapPODTable
);
// Put block into page
putBlockIntoPage(block1, pageSetting.two_column_format, isForcePageBreak, data);
}
}
}
glbHashObject['print_page_markers'] = printPageMarkers;
// Add the Open Street Map (if exists)
if (hasExistMap === true && pageSetting.show_GPS_coordinates === true && printPageMarkers.length > 0) {
var mapRegionTemplate = '';
$('#PrintRegionData').append(mapRegionTemplate);
// Put the custom page break
$('.map_region_title').css('page-break-before', 'auto');
}
// Process show/hide shade headings
if (pageSetting.shade_headings == false) {
// Clear shade headings
$('.form_title_region, .label_question').addClass('clear_shade_headings');
$('.map_region_title')
.addClass('clear_shade_headings')
.css('border', CONST_VALUE_NONE);
} else {
$('.form_title_region, .label_question').removeClass('clear_shade_headings');
$('.map_region_title')
.removeClass('clear_shade_headings');
}
// Process label shading width
if (pageSetting.two_column_format == false) {
$('.label_question').removeClass('label_question_two_column');
} else {
$('.label_question').addClass('label_question_two_column');
}
// Process max-width image
updateMaxWidthImageForPrinting();
// Process word-wrap for printing
processWordWrapForPrinting();
// Show map and markers (if existed)
if (hasExistMap == true && pageSetting.show_GPS_coordinates == true && printPageMarkers.length > 0) {
// Apply default width for osm_map_region (in printing status)
$('#osm_map_region').addClass('osm_map_region_print');
if (showMapAndMarkers() == false) {
jAlert(msg_print_create_map_fail);
return;
}
}
// Put events for checking load progress of images
putEventForImages();
// Apply page break into table blocks (after 1s for loading all image complete)
// setTimeout('applyPageBreak(#hasExistMap#, #numberOfMarkers#);'
// .replace('#hasExistMap#', hasExistMap)
// .replace('#numberOfMarkers#', printPageMarkers.length)
// , 1000);
setTimeout(function(){
applyPageBreak(hasExistMap, printPageMarkers.length, function() {
writeToLogInfoRequired('After finish apply PageBreak + Finish load images ...');
// Wait in 1s for make sure data has been load okie
setTimeout(function() {
// autoClickPrint=true
// autoCloseAfterPrint=true
var autoClickPrint = getQuerystring('autoClickPrint');
var autoCloseAfterPrint = getQuerystring('autoCloseAfterPrint');
var hideLogo = getQuerystring('hideLogo');
writeToLogInfoRequired('autoClickPrint : ' + autoClickPrint);
writeToLogInfoRequired('autoCloseAfterPrint : ' + autoCloseAfterPrint);
writeToLogInfoRequired('hideLogo : ' + hideLogo);
if (autoClickPrint == CONST_VALUE_TRUE_STR) {
// Hide all menu items
$('.print_preview_body .menuItem4PrintPreview').addClass('hiddenMenuItem');
// Trigger the button [Print]
// Call this function instead of trigger click event of [Print]
processPrintData();
}
if (autoCloseAfterPrint == CONST_VALUE_TRUE_STR) {
// Process close window
setTimeout('window.close();', 1000);
}
}, 1000);
});
}, 1000);
// PCA-266 Print Preview/PDF support for color option in Grids, questionnaires and Tables
// Apply custom appearance CSS for all controls
applyAppearance4ShadingHeadingsPDFLastAction();
}
// Get data from server
$.ajax({
url : '/Print4WAServlet',
dataType : 'json',
type : 'GET',
data : {
cacheId : cacheIdValue
},
cache : false,
complete : function() {
//waitForDataLoading(false);
},
success : function(response, status) {
processAjaxSuccess(response);
},
error: function(request, status, error) {
if(status == 'parsererror' && request.responseText){
processAjaxSuccess(JSON.parse(request.responseText));
return;
}
jAlert(msg_unknown_error);
}
});
}
/**
* Create the data all in JSON object
*/
function processDataAllCurrentRecord4WA(jsonDataPrint) {
var dataAll = new Array();
// The mapping of Name/Value for FixedTable
var nameValueMapping4FixedTable = new Object();
// The list of all FixedTable names
var listInvoiceTableDataNames = new Array();
// The mapping of Name/Value for PODTable
var nameValueMapping4POD = new Object();
// The list of all POD names
var listPODDataNames = new Array();
// The mapping of Name/Value for Grid
var nameValueMapping4Grid = new Object();
// Get TimeZone of current browser (include calculating daylight savings)
var timezoneClient = getClientTimeZoneMillis();
// The TimeZone of current browser
// (after auto process [x]Automatically adjust clock for daylight saving changes)
var timezoneClientActualCurrent = -((new Date()).getTimezoneOffset()) * 60 * 1000;
var specialDataNames = 'start,end,today,deviceid,subscriberid,simid,phonenumber,mobilekey,projectkey,recordid'.split(',');
// Init mapGroupCount4WA
mapGroupCount4WA = new Object();
var childrenData = fvDataNS.inputData.children;
var length = childrenData.length;
for (var i = 0; i < length; i++) {
var item = childrenData[i];
var type = item[CONST_VALUE_CTRLTYPE];
// Special processing with Group
if (type === CONST_CTRL_TYPE_GROUP) {
processDataAllGroup4WA(jsonDataPrint, dataAll, item, specialDataNames, nameValueMapping4Grid, nameValueMapping4FixedTable, listInvoiceTableDataNames, nameValueMapping4POD, listPODDataNames, timezoneClient);
} else {
// Normal question
processDataAllItem4WA(jsonDataPrint, dataAll, item, specialDataNames, nameValueMapping4Grid, nameValueMapping4FixedTable, listInvoiceTableDataNames, nameValueMapping4POD, listPODDataNames, timezoneClient);
}
}
jsonDataPrint['nameValueMapping4Grid'] = nameValueMapping4Grid;
jsonDataPrint['nameValueMapping4FixedTable'] = nameValueMapping4FixedTable;
jsonDataPrint['strListInvoiceTableDataNames'] = listInvoiceTableDataNames.join(',');
// Apply for POD Data
jsonDataPrint['nameValueMapping4POD'] = nameValueMapping4POD;
jsonDataPrint['strListPODDataNames'] = listPODDataNames.join(',');
// Put timezoneClient4WA for using in Date/Time format
//jsonDataPrint['timezoneClient4WA'] = timezoneClient;
// We will get timezone client directly by new Date().getTimezoneOffset() * 60 * 1000
jsonDataPrint['timezoneClient4WA'] = timezoneClientActualCurrent;
// Calculate the different value between timezoneClientActualCurrent and timezoneClient
writeToLogInfoRequired('timezoneClient4WA : ' + timezoneClient + ' >> timezoneClientActualCurrent : ' + timezoneClientActualCurrent);
// We are in [x]Automatically adjust clock for daylight saving changes
if (timezoneClientActualCurrent - timezoneClient === 3600000) {
jsonDataPrint['flgTimezoneClient4WADaylightSavingChanges'] = true;
}
return dataAll;
}
/**
* Process all control inside Group
*/
function processDataAllGroup4WA(jsonDataPrint, dataAll, item, specialDataNames
, nameValueMapping4Grid, nameValueMapping4FixedTable, listInvoiceTableDataNames, nameValueMapping4POD, listPODDataNames, timezoneClient) {
//
// // NEW RULE REQUEST : Ignore Skip&Relevant in PDF Report
// // Check [Hide in GUI], Skip&Relevant for current control
// if (item['isCtrlHidden'] === true) {
// return;
// }
// if (item['skipByCtrls'] !== undefined && item['skipByCtrls'].length > 0) {
// return;
// }
// Apply hidden field/relevance with Print Preview data from WebApps
// (only using when print directly from WebApps) by customer's requirements
// Fwd: Emailing: verizon event (17-Sep-2015)
// Check [Hide in GUI], Skip&Relevant for current control
if (item['isCtrlHidden'] === true) {
return;
}
if (item['skipByCtrls'] !== undefined && item['skipByCtrls'].length > 0) {
return;
}
// Get all children inside Group
var innerChildrenData = item.children;
var length = innerChildrenData.length;
for (var i = 0; i < length; i++) {
var innerItem = innerChildrenData[i];
var innerType = innerItem[CONST_VALUE_CTRLTYPE];
// Special processing with Group
if (innerType === CONST_CTRL_TYPE_GROUP) {
processDataAllGroup4WA(jsonDataPrint, dataAll, innerItem, specialDataNames, nameValueMapping4Grid, nameValueMapping4FixedTable, listInvoiceTableDataNames, nameValueMapping4POD, listPODDataNames, timezoneClient);
} else {
// Normal question
processDataAllItem4WA(jsonDataPrint, dataAll, innerItem, specialDataNames, nameValueMapping4Grid, nameValueMapping4FixedTable, listInvoiceTableDataNames, nameValueMapping4POD, listPODDataNames, timezoneClient);
}
}
}
/**
* Process current selected item getting from GUI (for WebApps)
*/
function processDataAllItem4WA(jsonDataPrint, dataAll, item, specialDataNames
, nameValueMapping4Grid, nameValueMapping4FixedTable, listInvoiceTableDataNames, nameValueMapping4POD, listPODDataNames, timezoneClient) {
//var item = childrenData[i];
//
// // NEW RULE REQUEST : Ignore Skip&Relevant in PDF Report
// // Check [Hide in GUI], Skip&Relevant for current control
// Process for Skip&Relevants
// if (item['skipByCtrls'] !== undefined && item['skipByCtrls'].length > 0) {
// return;
// }
// Apply hidden field/relevance with Print Preview data from WebApps
// (only using when print directly from WebApps) by customer's requirements
// Fwd: Emailing: verizon event (17-Sep-2015)
// Check [Hide in GUI], Skip&Relevant for current control
if (item['isCtrlHidden'] === true) {
return;
}
if (item['skipByCtrls'] !== undefined && item['skipByCtrls'].length > 0) {
return;
}
var curDName = item['name'];
var curDType = item[CONST_VALUE_CTRLTYPE];
// Special treating with Approval
// 0026089: Print Preview - not display selected value of Approval
if (item['realType'] === CONST_CTRL_TYPE_INPUTAPPROVAL) {
curDType = CONST_CTRL_TYPE_INPUTAPPROVAL;
}
// Special treating with Label & Skip&Relevants
if (item['isCtrlHidden'] === true && curDType === 'inputLabel') {
return;
}
// Process with special kind
if (item['kind'] !== undefined && item['kind'] !== null) {
if (curDType === CONST_CTRL_TYPE_INPUT_NUMERIC || curDType === CONST_CTRL_TYPE_INPUTDATE || curDType === CONST_CTRL_TYPE_INPUTMEDIA) {
curDType = item['kind'];
}
}
// Process special data name [start,end,today,deviceid,subscriberid,simid,phonenumber,mobilekey,projectkey,recordid]
//if (i <= 9 && specialDataNames.indexOf(curDName) >= 0) {
if (specialDataNames.indexOf(curDName) >= 0) {
// Put [Date_Created, MobileDevice]
if (curDName === 'start') {
// Also put record name into value
var curRecordName = new Object();
curRecordName['name'] = 'Record_Name';
curRecordName['caption'] = 'Record Name';
curRecordName['type'] = '';
curRecordName[CONST_VALUE] = '';
dataAll.push(curRecordName);
var curDate = new Object();
curDate['name'] = 'Date_Created';
curDate['caption'] = 'Date Created';
curDate['type'] = '';
curDate[CONST_VALUE] = convertTDate2StandardDate(item[CONST_VAL], CONST_VALUE_DATE_SPACE_TIME, timezoneClient);
dataAll.push(curDate);
jsonDataPrint.Date_Created = curDate[CONST_VALUE];
} else if (curDName === 'mobilekey') {
jsonDataPrint.mobileKey = item[CONST_VAL];
var curDevice = new Object();
curDevice['name'] = 'Mobile_Device';
curDevice['caption'] = 'Mobile_Device';
curDevice['type'] = '';
curDevice[CONST_VALUE] = item[CONST_VAL];
dataAll.push(curDevice);
}
return;
}
// TODO: Modify current data name (only for Groups)
//curDName = curDName + '(1,2,3,4)';
//data GroupNext1_loop_1 Group2_loop_3 Numeric_in_Gr2
var classPath = item['classPath'];
if (classPath !== undefined) {
// Remove first data and last SPACE character
// we will have GroupNext1_loop_1 Group2_loop_3 and parse into (1,3)
var arrClassPath = classPath.split(' ');
if (arrClassPath.length > 2) {
var groupIndexBuilder = new Array();
for (var k = 1; k < arrClassPath.length-1; k++) {
var currentLoopGroup = arrClassPath[k];
if (currentLoopGroup.indexOf(CONST_VALUE_DASH_LOOP) > 0) {
currentLoopGroup = currentLoopGroup.replace(/.*_loop_(.+)$/, '$1');
groupIndexBuilder.push(currentLoopGroup);
}
}
curDName = curDName + '(' + groupIndexBuilder.join(',') + ')';
}
// Apply Hide Option (Build Forms)
if (isNeedHiddenControlInBuildForms(item)) {
return;
}
}
var data = new Object();
//data['caption'] = curDName;
data['name'] = curDName;
data['type'] = curDType;
if (item[CONST_VAL] !== undefined && item[CONST_VAL] !== null) {
data[CONST_VALUE] = item[CONST_VAL];
// Special treating with SelectOne/ChooseOne/SelectMultiple
if (curDType === CONST_CTRL_TYPE_INPUTSELECTMANY) {
if (data[CONST_VALUE] !== '') {
//data[CONST_VALUE] = data[CONST_VALUE].split('<br>');
data[CONST_VALUE] = data[CONST_VALUE].split('
');
} else {
data[CONST_VALUE] = new Array();
}
} else if (curDType === CONST_CTRL_TYPE_INPUTLOCATION) {
var arrLocation = item[CONST_VAL].split(' ');
var objLocation = new Object();
objLocation['lat'] = 'no-gps';
objLocation['lng'] = 'no-gps';
objLocation['alt'] = 'no-gps';
objLocation['acc'] = 'no-gps';
if (arrLocation.length > 0) { objLocation['lat'] = arrLocation[0]; }
if (arrLocation.length > 1) { objLocation['lng'] = arrLocation[1]; }
if (arrLocation.length > 2) { objLocation['alt'] = arrLocation[2]; }
if (arrLocation.length > 3) { objLocation['acc'] = arrLocation[3]; }
data[CONST_VALUE] = objLocation;
} else if (curDType === CONST_CTRL_TYPE_INPUTEMAILREPORT ||
curDType === CONST_CTRL_TYPE_INPUTFAX ||
curDType === CONST_CTRL_TYPE_INPUTSECUREEMAILREPORT) {
// Process email report into standard type
// Check empty value in case there's no email address
if (data[CONST_VALUE] === '$$' || data[CONST_VALUE].indexOf('$$') === 0) {
data[CONST_VALUE] = '';
}
} else if (curDType === CONST_CTRL_TYPE_INPUTIMAGE || curDType === 'Image'
|| curDType === CONST_CTRL_TYPE_INPUTSKETCH || curDType === 'Sketch'
|| curDType === CONST_CTRL_TYPE_INPUTSIGNATURE || curDType === 'Signature'
|| curDType === CONST_CTRL_TYPE_INPUTAUDIO || curDType === 'Audio'
|| curDType === CONST_CTRL_TYPE_INPUTVIDEO || curDType === 'Video'
|| curDType === CONST_CTRL_TYPE_INPUTMEDIA
|| curDType === 'inputLabel'
) {
if (item['hintLink'] !== undefined && item['hintLink'] !== null && item['hintLink'] !== '') {
data[CONST_VALUE] = item['hintLink'];
} else {
data[CONST_VALUE] = '';
}
}
else if (curDType === CONST_CTRL_TYPE_INPUTAPPROVAL) {
// 0026089: Print Preview - not display selected value of Approval
// Extract data of Approval
if (data[CONST_VALUE] && data[CONST_VALUE] !== null && data[CONST_VALUE] !== '') {
var strApprovalVal = data[CONST_VALUE].toLowerCase();
if (strApprovalVal.indexOf('pending') >= 0) {
data[CONST_VALUE] = 'Pending';
} else if (strApprovalVal.indexOf('approve') >= 0) {
data[CONST_VALUE] = 'Approve';
} else if (strApprovalVal.indexOf('deny') >= 0 || strApprovalVal.indexOf('reject')) {
data[CONST_VALUE] = 'Deny';
}
}
}
} else if (curDType === CONST_CTRL_TYPE_CTRLGRID) {
// Special processing with Grid
nameValueMapping4Grid[curDName] = parseGridData4WA(item, timezoneClient);
// Put data of Grid into value
data[CONST_VALUE] = '';
} else if (curDType === CONST_CTRL_TYPE_CTRLTABLE) {
// Special processing with FixedTable
parseFixedTableData4WA(item, nameValueMapping4FixedTable, curDName, listInvoiceTableDataNames, timezoneClient);
data[CONST_VALUE] = '';
// Ignore with the seconds and later row inside FixedTable
// (because every row in FixedTable will be an item)
if (nameValueMapping4FixedTable[curDName].length > 1) {
return;
}
} else if (curDType === CONST_CTRL_TYPE_CTRLPOD) {
var isTheFirstTime = false;
if (listPODDataNames.indexOf(curDName) < 0) {
isTheFirstTime = true;
}
// Special processing with FixedTable
parsePODData4WA(jsonDataPrint, item, nameValueMapping4POD, curDName, listPODDataNames, timezoneClient);
data[CONST_VALUE] = '';
//writeToLogInfo('current POD : ' + JSON.stringify(item));
// Ignore with the seconds and later row inside FixedTable
// (because every row in FixedTable will be an item)
// if (nameValueMapping4POD[curDName] === undefined
// || nameValueMapping4POD[curDName].length > 1) {
// return;
// }
if (isTheFirstTime === false) {
return;
}
} else if (curDType === CONST_CTRL_TYPE_CTRLSCORETABLE) {
// Special processing with ScoreCard (Questionaire)
parseScoreCardData4WA(dataAll, item, curDName);
return;
} else {
data[CONST_VALUE] = '';
}
// Convert Date/Time/DateTime into standard value and UTC
if (data[CONST_VALUE] !== '') {
data[CONST_VALUE] = convertTDate2StandardDate(data[CONST_VALUE], curDType, timezoneClient);
}
// Add 0. into value of number as pattern -.ttt or .ttt
if (curDType === CONST_CTRL_TYPE_INPUT_NUMERIC || curDType === 'Decimal' || curDType === CONST_CTRL_TYPE_INPUTCALCULATE || curDType === CONST_CTRL_TYPE_INPUTTRENDS) {
if (data[CONST_VALUE] !== undefined && data[CONST_VALUE] !== null) {
var currentModifyVal = data[CONST_VALUE].toString();
var currentModifyLen = currentModifyVal.length;
if (currentModifyVal.indexOf('-.') === 0 && currentModifyLen > 2) {
currentModifyVal = '-0.' + currentModifyVal.substring(2, currentModifyLen);
} else if (currentModifyVal.indexOf('.') === 0 && currentModifyLen > 1) {
currentModifyVal = '0.' + currentModifyVal.substring(1, currentModifyLen);
}
data[CONST_VALUE] = currentModifyVal;
}
}
if (data['caption'] === undefined || data['caption'] === null) {
data['caption'] = '';
}
dataAll.push(data);
}
/**
* Processing save file (the same as Download file)
*/
function saveFileContent4WebApps(extension) {
// Check if we are using Backends or not
if (true === isUsingBackends4PR()) {
saveFileContent4WebAppsInBackends();
return;
}
// Step 1 : Put data to server for processing in Queue
waitForDataLoading(true);
// Create task id for current download task
var taskId = getRandomString(15);
// Save start time for limit waiting time download file.
glbHashObject['saveFileContent4WebApps_waitingDownloadTime'] = new Date().getTime();
$.ajax({
url: '/PrintMail4WAServlet' ,
dataType: 'json',
type: 'POST',
data: {
action : 'add_to_queue_print'
,cacheId : glbHashObject['PrintDataObject_cacheId']
,taskId : taskId
},
cache: false,
success: function(response, status) {
// Step 2 : Call AJAX multiple times for checking results
// Wait 3 seconds before checking result file
setTimeout(function() {
checkResultProcessFile4WebApps(glbHashObject['PrintDataObject_cacheId'], taskId);
}, 1000);
},
error: function(request, status, error) {
jAlert(err_support_unknown);
waitForDataLoading(false);
}
});
}
/**
* Checking result process file for WebApps
*/
function checkResultProcessFile4WebApps(cacheId, taskId) {
// Wait after 3s for checking next time.
$.ajax({
url: '/PrintMail4WAServlet' ,
dataType: 'json',
type: 'POST',
data: {
action : 'check_process_print'
,cacheId : cacheId
,taskId : taskId
},
cache: false,
complete : function() {
//waitForDataLoading(false);
},
success: function(response, status) {
// The progress is not completed
if (response.finish !== true) {
// Check limit time (over 3')
var waitTime = new Date().getTime() - glbHashObject['saveFileContent4WebApps_waitingDownloadTime'];
if (waitTime > WAITING_TIME_DOWNLOAD_FILE_REPORT) {
jAlert(msg_web_app_save_file_error);
waitForDataLoading(false);
return;
}
setTimeout(function() {
checkResultProcessFile4WebApps(cacheId, taskId);
}, 1000);
return;
}
// Finish the progress
var linkDownload = glbHashObject['url_server'] + '/PrintMail4WAServlet?download=true&type=pdf';
linkDownload += '&taskId=' + taskId;
// Redirect into download page (using iframe)
$('#savePDF_iFrameContent').attr('src', linkDownload);
// Hide waiting dialog until 3 seconds
waitForDataLoading(false);
},
error: function(request, status, error) {
jAlert(err_support_unknown);
waitForDataLoading(false);
}
});
}
/**
* Process parse data from item and put to data[CONST_VALUE] for Grid
* @param {} item
* @returns {}
*/
function parseGridData4WA(item, timezoneClient) {
var value = new Object();
value['name'] = item['name'];
value['type'] = item[CONST_VALUE_CTRLTYPE];
value['numColumns'] = item['colCount'];
value['equallySpaceColumns'] = item['equallySpaceColumns'];
value['relevancecondsExpression'] = item['relevancecondsExpression'];
// Copy all children data
var children = new Object();
for (var t = 0; t < item.children.length; t++) {
var child = new Object();
var curChild = item.children[t];
// Apply Hide Option (Build Forms)
if (isNeedHiddenControlInBuildForms(curChild)) {
// Mark this child will be hidden
child['~hideOnMobileApp'] = true;
}
child['type'] = curChild[CONST_VALUE_CTRLTYPE];
if (child['type'] === CONST_CTRL_TYPE_INPUT_NUMERIC || child['type'] === CONST_CTRL_TYPE_INPUTDATE || child['type'] === CONST_CTRL_TYPE_INPUTMEDIA) {
if (curChild['kind'] !== undefined && curChild['kind'] !== null && curChild['kind'] !== '') {
child['type'] = curChild['kind'];
}
}
var currentChildName = curChild['name'];
child['name'] = currentChildName;
child[CONST_VALUE] = curChild[CONST_VAL];
// Special treating value with media type (Image/Sketch/Signature/Audio/Video)
if (child['type'] === CONST_CTRL_TYPE_INPUTIMAGE || child['type'] === 'Image'
|| child['type'] === CONST_CTRL_TYPE_INPUTSKETCH || child['type'] === 'Sketch'
|| child['type'] === CONST_CTRL_TYPE_INPUTSIGNATURE || child['type'] === 'Signature'
|| child['type'] === CONST_CTRL_TYPE_INPUTAUDIO || child['type'] === 'Audio'
|| child['type'] === CONST_CTRL_TYPE_INPUTVIDEO || child['type'] === 'Video'
) {
if (curChild['hintLink'] !== undefined) {
var path = curChild['hintLink'];
if (path !== '' && curChild[CONST_VAL] !== undefined && curChild[CONST_VAL] !== null && curChild[CONST_VAL] !== '') {
path += '&blobName=' + curChild[CONST_VAL];
}
child[CONST_VALUE] = path;
}
} else if (child['type'] === 'inputLabel') {
child[CONST_VALUE] = curChild['hintLink'];
}
// Special treating with Date/Time/DateTime
if (child['type'] === CONST_CTRL_TYPE_INPUTDATE || child['type'] === CONST_VALUE_DATE || child['type'] === CONST_VALUE_TIME || child['type'] === CONST_VALUE_DATE_SPACE_TIME) {
child[CONST_VALUE] = convertTDate2StandardDate(child[CONST_VALUE], child['type'], timezoneClient);
}
//child[''] = curChild[''];
//child[''] = curChild[''];
//children.push(child);
children[currentChildName] = child;
}
//value['children'] = children;
return children;
}
/**
* Process parse data from item and put to data[CONST_VALUE] for FixedTable
* @param {} item
* @returns {}
*/
function parseFixedTableData4WA(item, nameValueMapping4FixedTable, curDName, listInvoiceTableDataNames, timezoneClient) {
var value = new Object();
value['name'] = item['name'];
value['type'] = item[CONST_VALUE_CTRLTYPE];
value['numColumns'] = item['colCount'];
value['equallySpaceColumns'] = item['equallySpaceColumns'];
value['relevancecondsExpression'] = item['relevancecondsExpression'];
// Initialize nameValueMapping4FixedTable[curDName] (only once)
var nmValMapping4FixedTable = new Array();
if (nameValueMapping4FixedTable[curDName] !== undefined) {
nmValMapping4FixedTable = nameValueMapping4FixedTable[curDName];
}
// Add to list of InvoiceTable (Not Duplicate)
if (listInvoiceTableDataNames.indexOf(curDName) < 0) {
listInvoiceTableDataNames.push(curDName);
}
// Copy all children data
var childrenMap = new Object();
//var arrMedia = 'inputImage,Image,inputSketch,Sketch,inputSignature,Signature,inputAudio,Audio,inputVideo,Video'.split(',')
for (var t = 0; t < item.children.length; t++) {
var curChild = item.children[t];
var childType = curChild[CONST_VALUE_CTRLTYPE];
if (childType === CONST_CTRL_TYPE_INPUTDATE && curChild['kind'] !== undefined) {
childType = curChild['kind'];
}
var currentChildName = curChild['name'];
var currentChildVal = curChild[CONST_VAL];
// Apply Hide Option (Build Forms)
if (isNeedHiddenControlInBuildForms(curChild)) {
// Mark this child will be hidden
childrenMap[currentChildName + '~hideOnMobileApp'] = true;
}
childrenMap[currentChildName] = currentChildVal;
// Special treating value with media type (Image/Sketch/Signature/Audio/Video)
if (childType === CONST_CTRL_TYPE_INPUTIMAGE || childType === 'Image'
|| childType === CONST_CTRL_TYPE_INPUTSKETCH || childType === 'Sketch'
|| childType === CONST_CTRL_TYPE_INPUTSIGNATURE || childType === 'Signature'
|| childType === CONST_CTRL_TYPE_INPUTAUDIO || childType === 'Audio'
|| childType === CONST_CTRL_TYPE_INPUTVIDEO || childType === 'Video'
) {
if (curChild['hintLink'] !== undefined) {
var path = curChild['hintLink'];
if (path !== '' && currentChildVal !== undefined && currentChildVal !== null && currentChildVal !== '') {
path += '&blobName=' + currentChildVal;
}
childrenMap[currentChildName] = path;
}
} else if (childType === 'inputLabel') {
childrenMap[currentChildName] = curChild['hintLink'];
} else if (childType === CONST_CTRL_TYPE_INPUTDATE || childType === CONST_VALUE_DATE || childType === CONST_VALUE_TIME || childType === CONST_VALUE_DATE_SPACE_TIME) {
// Convert TDate into standard Date/Time/DateTime
childrenMap[currentChildName] = convertTDate2StandardDate(currentChildVal, childType, timezoneClient);
}
}
// Add current row data inside FixedTable
nmValMapping4FixedTable.push(childrenMap);
nameValueMapping4FixedTable[curDName] = nmValMapping4FixedTable;
}
/**
* Process parse data from item and put to data[CONST_VALUE] for POD Table
* @param {} item
* @returns {}
*/
function parsePODData4WA(jsonDataPrint, item, nameValueMapping4POD, curDName, listPODDataNames, timezoneClient) {
var value = new Object();
value['name'] = item['name'];
value['type'] = item[CONST_VALUE_CTRLTYPE];
value['numColumns'] = item['colCount'];
value['equallySpaceColumns'] = item['equallySpaceColumns'];
value['relevancecondsExpression'] = item['relevancecondsExpression'];
// Copy all children data
var childrenMap = new Object();
var currentStatus = '';
for (var t = 0; t < item.children.length; t++) {
var curChild = item.children[t];
var childType = curChild[CONST_VALUE_CTRLTYPE];
if (childType === CONST_CTRL_TYPE_INPUTDATE && curChild['kind'] !== undefined) {
childType = curChild['kind'];
}
var currentChildName = curChild['name'];
var currentChildVal = curChild[CONST_VAL];
// // Apply Hide Option (Build Forms), not available in POD controls
// if (isNeedHiddenControlInBuildForms(curChild)) {
// continue;
// }
childrenMap[currentChildName] = currentChildVal;
// Update the status value
if (currentChildName.endsWith(POD_SUFFIX_STATUS)) {
currentStatus = currentChildVal;
}
}
// // Add current row data inside POD (with checking status)
// // currentStatus ...
// // Only get value with status
// var isGetCurrentRow = false;
// switch(currentStatus) {
// case POD_STATUS_MANIFEST_EMPTY :
// case POD_STATUS_MANIFEST_0 :
// case POD_STATUS_MANIFEST_16 :
// isGetCurrentRow = true;
// break;
// default :
// // Stop process current row
// return;
// }
// Add to list of InvoiceTable (Not Duplicate)
if (listPODDataNames.indexOf(curDName) < 0) {
listPODDataNames.push(curDName);
var osdData = fvDataNS.inputData.PODData[curDName];
// Special treating with the first time of processing POD question (first loop)
// Apply main data
jsonDataPrint['~OSDData_' + curDName] = osdData;
var deliverTable = fvDataNS.inputData.PODExtData[curDName];
jsonDataPrint['~DeliverData_' + curDName] = parseDeliverData4PODQuestion(deliverTable);
}
// Add current row data inside POD (with checking status)
// currentStatus ...
// Only get value with status
// var isGetCurrentRow = false;
// switch(currentStatus) {
// case POD_STATUS_MANIFEST_EMPTY :
// case POD_STATUS_MANIFEST_0 :
// case POD_STATUS_MANIFEST_16 :
// isGetCurrentRow = true;
// break;
// default :
// // Stop process current row
// return;
// }
// Initialize nameValueMapping4POD[curDName] (only once)
var nmValMapping4FixedTable = new Array();
if (nameValueMapping4POD[curDName] !== undefined) {
nmValMapping4FixedTable = nameValueMapping4POD[curDName];
}
// Add current row data inside POD (with checking status)
// currentStatus ...
// Only get value with status
var isGetCurrentRow = false;
switch(currentStatus) {
case POD_STATUS_MANIFEST_EMPTY :
case POD_STATUS_MANIFEST_0 :
case POD_STATUS_MANIFEST_16 :
isGetCurrentRow = true;
nmValMapping4FixedTable.push(childrenMap);
break;
}
//nmValMapping4FixedTable.push(childrenMap);
nameValueMapping4POD[curDName] = nmValMapping4FixedTable;
}
/**
* Process parse data for ScoreCard
* @param {} item
* @returns {}
*/
function parseScoreCardData4WA(dataAll, item, curDName) {
// Copy all children data
for (var t = 0; t < item.children.length; t++) {
var curChild = item.children[t];
var currentChildName = curChild['name'];
var currentChildType = curChild[CONST_VALUE_CTRLTYPE];
var data = new Object();
data['name'] = currentChildName;
data['caption'] = currentChildName;
var value = '';
if (curChild[CONST_VAL] !== undefined && curChild[CONST_VAL] !== null) {
value = curChild[CONST_VAL];
}
// Check if the current question is a comment (ends with __comment)
if (curChild['id'].toString().endsWith('__comment')) {
// Force the type is EMPTY
currentChildType = '';
}
data['type'] = currentChildType;
// Special processing with SelectMultiple
if (currentChildType === CONST_CTRL_TYPE_INPUTSELECTMANY) {
data[CONST_VALUE] = new Array();
if (value !== '') {
//data[CONST_VALUE] = value.split('<br>');
data[CONST_VALUE] = value.split('
');
}
} else {
// The ChooseOne and ScoreOne
data[CONST_VALUE] = value;
}
// Apply Hide Option (Build Forms)
if (isNeedHiddenControlInBuildForms(curChild)) {
// Mark that this data will be hidden in Questionnaire
data['~hideOnMobileApp'] = true;
}
dataAll.push(data);
}
}
/**
* Process convert TDate into standard Date/Time/DateTime
* @param {} strDateValue
* @param {} strType
* @param {} timezoneClient
* @returns {}
*/
function convertTDate2StandardDate(strDateValue, strType, timezoneClient) {
// Validate strDateValue
if (strDateValue === undefined || strDateValue === null || strDateValue === '') { return ''; }
try {
switch (strType) {
case CONST_VALUE_DATE :
case CONST_CTRL_TYPE_INPUTDATE :
//var objDate = new Date(strDateValue);
var objDate = parseDateTFormat(strDateValue, strType);
return objDate.format('mm/dd/yyyy');
case CONST_VALUE_DATE_SPACE_TIME :
case CONST_VALUE_DATE_TIME :
// Fix bug 0019175: Date:Time Settings - Print View - Value of Time/Cal display incorrectly in case Setting uncheck DST but User check DST(GMT-5)
var objDate = parseDateTFormat(strDateValue, strType);
// Check current timezone offset with NOW timezone offset (for Date/Time)
var dayTZOffset = -objDate.getTimezoneOffset() * 60 * 1000;
if (nowTimezoneOffset4WA !== dayTZOffset) {
// Append time with x = nowOffset - dayOffset
objDate = new Date(objDate.getTime() + (dayTZOffset - nowTimezoneOffset4WA) );
writeToLogInfoRequired('Type : ' + strType + ' >> Plus 1 hour for date (DST) : ' + strDateValue);
}
return objDate.toString();
case CONST_VALUE_TIME :
var objDate = parseDateTFormat(strDateValue, strType);
return objDate.toString();
}
} catch (ex) {
writeToLogInfoRequired('Exception in convertTDate2StandardDate() : ' + ex);
}
return strDateValue;
}
/**
* Process save file PDF for WebApps (using in Backends case)
*/
function saveFileContent4WebAppsInBackends() {
// Put process save file to servlet : PrintRPHandlerServle.java
waitForDataLoading(true);
// The task info key (only used in Backends)
var previewTaskInfoKey = getQuerystring('taskInfoKey');
// Check dummy processing ExcelTemplate
$.ajax({
url : '/PrintRPHandlerServlet',
dataType : 'json',
type : 'POST',
data : {
action : 'save_file'
,taskInfoKey : previewTaskInfoKey
// ,isClickMenuPdf : isClickMenuPdf
// ,isExcelTemplate : isExcelTemplate
},
cache : false,
complete: function() {
//waitForDataLoading(false);
},
success : function(response, status) {
setTimeout('processCheckingFileAndDownloadInBE("' + response.taskInfoKey + '")', 3000);
},error : function() {
jAlert(msg_unknown_error);
waitForDataLoading(false);
}
});
}
/**
* Process PrintView in WebApps with silent mode
* (we don't show any GUI but forward directly to printer)
*/
function processPrintViewWAInSilentMode(htmlParams) {
// Create an iframe
var urlSrc = '/html/PrintPreview4WA.html' + htmlParams;
var builderFrame = new Array();
builderFrame.push('');
var resultHTML = builderFrame.join('');
$('.configWAFrame4EditRecordAndPrint').html(resultHTML);
}
/**
* Parse Deliver Table data for POD question
* @param deliverTable
*/
function parseDeliverData4PODQuestion(deliverTable) {
var resultRows = new Array();
if (typeof deliverTable == 'undefined') {
return resultRows;
}
for (var i = 0; i < deliverTable.length; i++) {
var objRow = new Object();
var rowItem = deliverTable[i];
var childCols = rowItem.children;
for (var t = 0; t < childCols.length; t++) {
var colItem = childCols[t];
var colName = colItem['name'];
var colVal = '';
if (colItem[CONST_VAL] !== undefined) { colVal = colItem[CONST_VAL]; }
objRow[colName] = colVal;
}
resultRows.push(objRow);
}
return resultRows;
}
/**
* Check if we need hide this control by config Hide > ... in Build Forms
*/
function isNeedHiddenControlInBuildForms(item) {
var isHideControl = false;
try {
// Apply Hide Option
if (isVersion(VERSION_READ_ONLY_REQUIRED_HIDE_OPTION)) {
var classPath = item['classPath'];
if (classPath) {
// Process by checking class : hideOnMobileApp
if (fvDataNS.ctrlArray) {
var objectControl = fvDataNS.ctrlArray[classPath];
if (objectControl && objectControl.hasClass('hideOnMobileApp')) {
isHideControl = true;
}
}
// We will hide this control
if (isHideControl === true) {
return true;
}
}
}
} catch (e) { }
return isHideControl;
}