/**
* form_record.js
* Process for printing form record (from version 1.2)
*/
// Prototype for startsWith string function
String.prototype.startsWith = function(prefix) {
return this.indexOf(prefix) === 0;
}
// Prototype for endsWith string function
String.prototype.endsWith = function(suffix) {
return this.match(suffix+"$") == suffix;
};
// Append the elements of the array a to this array
Array.prototype.append = function(a) {
Array.prototype.push.apply(this, a);
}
// Get browser name information
var browserNameGlobal = getBrowserInfo();
var MAXIMUM_VALUE = Number.MAX_VALUE;
var MINIMUM_VALUE = -(Number.MAX_VALUE / 2);
var DEFAULT_ZOOM_FOR_ONE_MARKER = 15;
// Adjust max-width image
//var MAX_WIDTH_IMAGE = 140; // In unit milimetre
var MAX_WIDTH_IMAGE = 155; // In unit milimetre
var MAX_WIDTH_CONTENT = 170; // In unit milimetre
// The constants getting from PageSetting about scale image (100%, 66%, ...)
var SCALE_IMAGE_VALUE_NO_SCALE = '';
var SCALE_IMAGE_VALUE14 = '1/4';
var SCALE_IMAGE_VALUE13 = '1/3';
var SCALE_IMAGE_VALUE12 = '1/2';
var SCALE_IMAGE_VALUE23 = '2/3';
// The time between checking status of Print Data
// (used in download only 1 file, in PrintPreview/Print Merchandizing Account)
// (default is 5s)
var WAITING_TIME_BETWEEN_CHECKING = 5000; // 5000
// The time between checking status of PrintData (Multiple Records)
// (between at least 7s seconds for make sure download successful)
// used in Bulk Download/Print Merchandizing Facings
var WAITING_TIME_BETWEEN_CHECKING_4MULTI_FILES = 10000; //7000;
// The padding value used in Grid/Table/ScoreCard (PCA-190)
var PADDING_LEFT_INVOICE_TABLE_GENERAL = 5;
//The constants value for Label Shading (1, 2, 3)
var LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_LINES = '1';
var LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_SHADE = '2';
var LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_NO_LINES_AND_SHADING = '3';
var LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_APPEARANCE_DEFAULT = 'Default'; // Appearance Default
var LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_APPEARANCE_CUSTOM = 'Custom'; // Appearance Custom
// PCA-212 : Print Preview/PDF support for Text Calculations
var FIXED_TABLE_CALC_SHOW_TEXT_MOBILE = 'fixedTable_showAsTextMobile'; // showAsTextMobile
var FIXED_TABLE_CALC_MOBILE_TEXT_ALIGN = 'fixedTable_mobileTextAlign'; // mobileTextAlign
var CALCULATION_TEXT_MOBILE_ALIGNMENT_LEFT = "Left";
var CALCULATION_TEXT_MOBILE_ALIGNMENT_RIGHT = "Right";
var CALCULATION_TEXT_MOBILE_ALIGNMENT_CENTER = "Center";
// The value of Grid Type
// PCA-174 (PDF/Excel Reports support for New Grid Type)
var GRID_TYPE_ROW_BASED_JAVASCRIPT = "1"; // Row Based
var GRID_TYPE_COLUMN_BASED_JAVASCRIPT = "2"; // Column Based
var GRID_TYPE_CENTER_GRID_JAVASCRIPT = "3"; // Center grid type
// PCA-174 (PDF/Excel Reports support for New Grid Type)
// The constants value for Table/Grid Shading (1,2,3)
// The variable in $control will be 'shadedKind'
var TABLE_CONSTANTS_VALUE_OPTION_BF_TOP_ROW_ONLY = "1"; // Top Row Only
var TABLE_CONSTANTS_VALUE_OPTION_BF_FIRST_COL_ONLY = "2"; // First Column Only
var TABLE_CONSTANTS_VALUE_OPTION_BF_EVERY_OTHER_COL = "3"; // Every Other Column
// PCA-266 Print Preview/PDF support for color option in Grids, questionnaires and Tables
// The constants about we are using Appearance ()Custom + []Shaded headings
var CONTROL_APPEARANCE_NO_SHADING_CHECKBOX = "NO SHADING CHECKBOX";
// PCA-174: PDF/Excel Reports support for New Grid Type
// The constants about columnSpaceType in Grid/Table/Questionnaire
var CONTAINER_COLUMN_SPACE_TYPE_EQUALLY_SPACE_COLUMNS = "0"; // Equally space columns
var CONTAINER_COLUMN_SPACE_TYPE_USE_CAPTION_LENGTH = "1"; // Use caption length
var CONTAINER_COLUMN_SPACE_TYPE_ADJUST_COLUMN_WIDTH = "2"; // Adjust column width
//The default shading background color with OLD FORM (#E9E9E9)
var DEFAULT_SHADING_BACKGROUND_COLOR_4_OLD_FORMS = '#E9E9E9';
// Apply Justification for all controls
var JUSTIFICATION_CONTROL_VALUE_LEFT = '0';
var JUSTIFICATION_CONTROL_VALUE_CENTER = '1';
var JUSTIFICATION_CONTROL_VALUE_RIGHT = '2';
// PCA-406: Report Settings [] show buttons and check boxes in PDF same as PDF
// The constant value for showPicturesOnTheirOwnPageValue
//var SHOW_PICTURE_ON_THEIR_OWN_PAGE_1 = "OnePerPage";
//var SHOW_PICTURE_ON_THEIR_OWN_PAGE_2 = "TwoPerPage";
// List of item we need refresh layout after finishing render GUI
var listSelectControlsNeedRefreshInPDF = new Array();
// Global variable for POD (Extract from PODUtils.java)
var POD_CHILDREN_NAMES_KEY = "~ChildrenNames";
var POD_SHADE_KIND_KEY = "~shadedKind";
var POD_COLUMN_WEIGHT_KEY = "~withFormat4ColumnWeight";
var POD_NAME_KEY = "~name";
// The POD property : @PODQuantity
var POD_QUANTITY = "@PODQuantity";
// The POD property : @PODDamage
var POD_DAMAGE = "@PODDamage";
// The POD property : @PODOver
var POD_OVER = "@PODOver";
// The POD property : @PODTableName
var POD_TABLE_NAME = "@PODTableName";
// The POD property : @Header
var POD_HEADER = "@Header";
// The POD property : @Caption
var POD_HEADER_CAPTION = "@Caption";
// The POD property : @TopTable
var POD_TOP_TABLE = "@TopTable";
// The POD property : @OSDReport
var POD_OSD_REPORT = "@OSDReport";
// The POD property : @DeliverTable
var POD_DELIVER_TABLE = "@DeliverTable";
// The POD property : @Rows
var POD_ROWS = "@Rows";
// The POD Header : Damaged/Rejected/Comment
var POD_HEADER_DAMAGE = "S2__Damaged";
var POD_HEADER_REJECT = "S2__Rejected";
var POD_HEADER_OVER = "S2__Over";
var POD_HEADER_COMMENT = "S2__Comment";
var POD_HEADER_DELIVER = "S2__Deliver";
var POD_HEADER_PICKUP = "S2__Pickup";
var POD_HEADER_QTY = "S2__Qty";
var POD_HEADER_ACTUAL = "S2__Actual";
var POD_HEADER_CHANGE = "S2__Change";
var POD_HEADER_STATUS = "S2__Status";
var POD_HEADER_AUTO_ID = "S2__AutoID";
// The suffix values of POD
var POD_SUFFIX_DAMAGED = "__Damaged";
var POD_SUFFIX_REJECTED = "__Rejected";
var POD_SUFFIX_DELIVER = "__Deliver";
var POD_SUFFIX_PICKUP = "__Pickup";
var POD_SUFFIX_COMMENT = "__Comment";
var POD_SUFFIX_SHORT = "__Short";
var POD_SUFFIX_OVER = "__Over";
var POD_SUFFIX_QTY = "__Qty";
var POD_SUFFIX_ACTUAL = "__Actual";
var POD_SUFFIX_CHANGE = "__Change";
var POD_SUFFIX_STATUS = "__Status";
var POD_SUFFIX_AUTOID = "__AutoID";
var POD_CHECKBOX_YES_VALUE = "yes";
var POD_CHECKBOX_YES_CAPTION = "Yes";
// The status value of manifest table rows
var POD_STATUS_MANIFEST_EMPTY = "";
var POD_STATUS_MANIFEST_0 = "0";
var POD_STATUS_MANIFEST_16 = "16";
var POD_STATUS_HIDDEN_32 = "32";
// Control for applying : Answer Color for PrintPreview/Standard PDF
var CONTROL_APPLY_ANSWER_COLOR_GUI_PREVIEW_PDF = 'inputText,inputNumeric,Decimal,Integer,Percent,inputLocation,inputNumbering,inputDate,Date,Time,Date time,inputBarcode,inputEmailReport,inputSecureEmailReport,inputLookup,inputLFBluetooth,inputCalculate,inputNFC,inputCounter,inputTrends,inputPayment,inputNewPayment,';
// Control not apply remove border answer
var CONTROL_NOT_APPLY_REMOVE_BORDER_ANSWER_PREVIEW_PDF = 'inputPageBreak,group,ctrlTable,ctrlPOD,inputFacingTable,ctrlScoreTable,ctrlGrid,inputLabelDummy4Grid,';
// Add image for ChooseOne/SelectMultiple Option
var LIST_IMAGE_OPTIONS_4_PREVIEW = "~listImageOptions~";
/**
* Process printing data
*/
function processPrintData() {
// 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();
// Hide the line header
$('#idLineFormatHeaderPrintPreview').addClass('hideLineFormatHeader');
// Show map and markers in printing mode
showMapAndMarkers(true);
$('.jqmOverlay:visible').css('opacity', 0);
window.print();
// Make sure the print okie after restoring the GUI in normal print view (HTML)
setTimeout('restoreGUITimeout();', 1000);
}
// The list list all of Decimal Fields (Decimal questions/Calculation related Decimal/...)
var listAllDecimalFields = null;
/**
* Process HTML content for current print form record
*/
function processHTMLPrintFormRecord() {
// The flag about click menu [Excel Report]
var isExcelReport = getQuerystring('isExcelReport');
// Check if we are in creating PDF (menu PDF Report)
var isClickMenuPdf = getQuerystring(CONST_KEY_ISCLICKMENUPDF);
var cacheIdValue = getQuerystring('cacheId');
// The task info key (only used in Backends)
var taskInfoKey = getQuerystring('taskInfoKey');
// 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();
// Special treating with data is from menu [Edit] > PDF Preview (ReadOnly user)
var isRequestFromReadOnlyAndView = getQuerystring('isRequestFromReadOnlyAndView');
if (!isRequestFromReadOnlyAndView || isRequestFromReadOnlyAndView === null) {
isRequestFromReadOnlyAndView = '';
}
// Get data from server
$.ajax({
url : '/dataview/print',
dataType : 'json',
type : 'GET',
data : {
cacheId : cacheIdValue
,taskInfoKey : taskInfoKey
,isRequestFromReadOnlyAndView : isRequestFromReadOnlyAndView
,isExcelReport : isExcelReport
},
cache : false,
complete : function() {
//waitForDataLoading(false);
},
success : function(response, status) {
// CO-2078
var ppvWebsiteIconStyles = '';
switch(!undefined) {// CO-2050
case (response.website_icon_color != undefined) :
// CO-2051 Add custom style for icon color
ppvWebsiteIconStyles += '.svg-icon svg path {fill: ' + response.website_icon_color + ';}';
ppvWebsiteIconStyles += '.svg-label {color: ' + response.website_icon_color + ';}';
// CO-2051 Add custom style for icon color
// CO-2050
// CO-2078
case (response.website_active_icon_color != undefined) :
// CO-2051 Add custom style for icon color
ppvWebsiteIconStyles += '.svgIconContainer:hover .svg-label {color: ' + response.website_active_icon_color + ';}';
ppvWebsiteIconStyles += '.svgIconContainer:hover .svg-icon svg path {fill: ' + response.website_active_icon_color + ';}';
ppvWebsiteIconStyles += '.svgIconContainer .svg-label.selected {color: ' + response.website_active_icon_color + ';}';
$('#ppvWebsiteIconStyles').html(ppvWebsiteIconStyles);
// CO-2051 Add custom style for icon color
}
// CO-2078
// Process update constants value (only affected on localhost for developing)
updateConstantsValueOnly4LocalhostFAST();
// Update flag glbHashObject['isUsingBackends4PR']
glbHashObject['isUsingBackends4PR'] = response.isUsingBackends4PR;
writeToLogInfo('Setting flag using backend : ' + glbHashObject['isUsingBackends4PR']);
// Update global variable for Shading in PDF (same as Shading in WebApps)
updateGlobalVariable4ShaddingAndButtonTextBuildFormsInPDF(response);
// 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);
$('#projectKey').val(response.projectId);
// Get setting for PDF (Standard Report Template/Custom Report Template)
var isShowExcelScreen = false;
if (isExcelReport != undefined && isExcelReport != null && isExcelReport == CONST_VALUE_TRUE_STR
&& !(isClickMenuPdf === CONST_VALUE_TRUE_STR && (pageSetting.templateUseWhenCreatePdf === CREATE_PDF_BY_STANDARD_REPORT_TEMLATE || pageSetting.templateUseWhenCreatePdf === undefined))
) {
isShowExcelScreen = true;
} else {
// Check Report Settings
if (isClickMenuPdf === CONST_VALUE_TRUE_STR && pageSetting.templateUseWhenCreatePdf == CREATE_PDF_BY_CUSTOM_REPORT_TEMLATE) {
isShowExcelScreen = true;
}
}
// Special treating with data is from menu [Edit] > PDF Preview (ReadOnly user)
// => Show Standard Report PDF Print Preview with default settings
if (isRequestFromReadOnlyAndView === CONST_VALUE_TRUE_STR) {
isShowExcelScreen = false;
}
// Special processing for Excel Report page
if (isShowExcelScreen) {
// Only process this function for the first time
// if (glbHashObject['loading_excel_template_html_content'] == undefined
// || glbHashObject['loading_excel_template_html_content'] == null
// || glbHashObject['loading_excel_template_html_content'] == false)
{
// Clear all data of print view (in Excel Report)
$('#PrintRegionData').empty();
processExcelReport(response);
// In Excel Report screen, we will move the bottom menu controls into main region
// Bottom menu controls include [Email Save Settings Cancel], Powered by www.doForms.com
// Move #bottomMenuId into #PrintRegionData
// $('#bottomMenuId').appendTo('#PrintRegionData');
// $('#bottomPoweredId').appendTo('#PrintRegionData');
// Modify about CSS/style
$('#bottomMenuId').css('padding-top', '0px');
$('#footerFirstPadding').hide();
$('#bottomPoweredId').css('margin-left', '0px');
$('#bottomMenuId').css('margin-left', '1in');
$('#bottomPoweredId').css('margin-left', '1in');
$('#PrintRegionData').css('margin', '0.5in 1in 0in');
// Make double font size 2X
$('.double2XFontSize').css('font-size', '22px');
// Setting the flag value for ignoring loading data later
glbHashObject['loading_excel_template_html_content'] = true;
// Process show/hide [Convert to PDF]
//if (false === isVersion5_0())
{
$('.processConvert2Pdf').hide();
}
// Show all button related ExcelTemplate report
$('.btnPrint_EmailExcelTemplate,.btnPrint_ExcelTemplateSave,.btnPrint_EmailPageSetting,.btnPrint_Close')
.removeClass('hiddenMenuItem');
// Hide all button related Pdf Report
$('.btnPrint_Submit,.btnPrint_Email,.btnPrint_Save')
.addClass('hiddenMenuItem');
// Hide all button in the bottom of page.
$('.menuItem4PrintPreview#bottomMenuId').addClass('hiddenMenuItem');
}
// Apply font title for Custom Template
$('#PrintRegionData .form_title_region').addClass('form_title_region_ORIGINAL');
callFormLoadedEvents();
setTimeout(function(){
$('#PrintRegionData').append('
');
var observer = new MutationObserver(reportFormResizedWithSelector);
$('body.print_preview_body #PrintRegionData > *').each(function (index, element) {
observer.observe(element, {attributes: true, attributeFilter: ['style']});
});
reportFormResizedWithSelector();
}, 1000);
waitForDataLoading(false);
return;
} else {
// Show the bottom menu items (main menu)
$('.menuItem4PrintPreview#bottomMenuId').removeClass('hiddenMenuItem')
// Hide all menu related to Excel Report feature
//$('.btnPrint_ExcelTemplate, .btnPrint_EmailExcelTemplate').hide();
// Show all button related Pdf Report
$('.btnPrint_Submit,.btnPrint_Email,.btnPrint_Save,.btnPrint_EmailPageSetting,.btnPrint_Close')
.removeClass('hiddenMenuItem');
// Hide all button related ExcelTemplate report
$('.btnPrint_EmailExcelTemplate,.btnPrint_ExcelTemplateSave')
.addClass('hiddenMenuItem');
$('#bottomMenuId').css('margin-left', '0in');
// $('#bottomPoweredId').css('margin-left', '10px'); // Remove margin-left => resolve problem with bototm scrollbar
$('#footerFirstPadding').show();
// Restore css in normal pdf layout
$('#PrintRegionData').css('margin', '0.5in 1in 1in');
// Restore font size 1X
$('.double2XFontSize').css('font-size', '11px');
// Apply font title for Standard Template
$('#PrintRegionData .form_title_region').removeClass('form_title_region_ORIGINAL');
}
// Special treating with data is from menu [Edit] > PDF Preview (ReadOnly user)
// => Show Standard Report PDF Print Preview with default settings
// Hide all menu button, except the button Cancel
if (isRequestFromReadOnlyAndView === CONST_VALUE_TRUE_STR) {
$('.menuItem4PrintPreview').find('.modalButton:not(.btnPrint_Close)').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);
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 = '
#logo_path#
';
htmlData.push(logoTemplate.replace('#logo_path#',
'')
);
}
// Add title based on []Display form name setting
if (pageSetting.display_form_name === true) {
var formTitleTemplate = '
#form_name#
';
// Apply tag into Print/PDF
//htmlData.push(formTitleTemplate.replace('#form_name#', replaceTagBR2LineFeed(response.form_name)));
htmlData.push(formTitleTemplate.replace('#form_name#', response.form_name));
}
// CO-1066: Show/Hide footer message
if (true == pageSetting.displayFooterMessage) {
$('#bottomPoweredId').css('display', '');
} else{
$('#bottomPoweredId').css('display', 'none');
}
// 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.end = '
';
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;
// Apply Compability > Do not show the repeatable caption in Report Settings
var previousData = null;
var previousIsForcePageBreak = 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
|| (data['pageBreak'] != undefined && data['pageBreak'].indexOf('-hidden') > 0)) { // CO-3243
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
// var header = replaceTagBR2LineFeed(data['header']);
// var hints = replaceTagBR2LineFeed(data['hints']);
// Apply tag into Print/PDF
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 {
// Force showing GroupTail for question inside Group
// (in Compatibility Mode + Do not Show Group sections)
// Apply Compability > Do not show the repeatable caption in Report Settings
if (isVersion(VERSION_COMPABILITY_DONOT_SHOW_GROUP_CAPTION)
&& pageSetting.isCompatibilityMode === true
&& pageSetting.isCompatibilityDontShowGroupCpt === true
) {
// Do nothing for Group header
} else {
// Normal cases
var groupTailLength = name.length - orgName.length;
if (groupTailLength > 0) {
header = header.substring(0, header.length - groupTailLength);
}
}
// var groupTailLength = name.length - orgName.length;
// if (groupTailLength > 0) {
// header = header.substring(0, header.length - groupTailLength);
// }
}
}
// Ignore the question with header == '' + value == '' + hints == ''
// Special treating with Questionnaire (ctrlScoreTable)
if (header === '' && hints === '' && value === ''
&& data['type'] !== CONST_CTRL_TYPE_CTRLSCORETABLE
&& data['type'] !== 'inputLabel'
) {
continue;
}
}
var caption = getDisplayHeader(header, false);
switch (data['type']) {
case 'inputLabel' :
// PCA-214 (Apply label coloring for PDF)
//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);
}
if (block === '') { continue; }
break;
case CONST_CTRL_TYPE_INPUTACTION :
block = createPDFBlockSHADING(header, hints, value, data, pageSetting);
break;
// Fix bug 0023688: Report Settings - Forward, Payments are not displayed in report although they are checked in field list
// case CONST_CTRL_TYPE_INPUTPAYMENT :
// // Do nothing
// continue;
case mdi_kind_inputMedia :
case mdi_kind_inputImage :
case mdi_kind_image :
case mdi_kind_inputSketch :
case mdi_kind_sketch :
case CONST_CTRL_TYPE_IMAGE_VIEWER :
// 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 :
// PCA-180: PDF support for Shading and Spacing
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createSignatureBlockSHADING(header, hints, value, data, pageSetting);
} 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_INPUTATTACHMENT:
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
block = createAttachmentBlockSHADING(header, hints, value, data);
} else {
block = createAttachmentBlock(caption, hints, value);
}
break;
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) {
// PCA-587: Ability to select the answer as displayed to the mobile user, or the underlying_value for Choose One, Score, Select Multiple in Standard PDF/Excel reports
if (isVersion(VERSION_SHOWING_SELECT_VALUES_4REPORT)) {
if (pageSetting.typeOfShowingSelectValue === TYPE_OF_SHOWING_SELECT_UNDERLINE_VALUE) {
var listOptions = response.SelectionsDataMappingInCaptions[orgName];
var listOptionsUValue = response.SelectionsDataMappingInUnderlineValue[orgName];
// Get underline value
value = getContentDataOfUnderlineValueSelections4Pdf(value
, listOptions, listOptionsUValue);
}
}
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 :
case CONST_CTRL_TYPE_REPEATABLE_SUMMARY :
//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(header, hints, value, data['fixedTableTypes'], data['fixedTableKinds'], data['fixedTableCurrency'], pageSetting.two_column_format, data['fixedTableDataNameHeader'], data);
}
break;
case CONST_CTRL_TYPE_CTRLPOD :
// Apply Hide > []Non-selected radio buttons and checkboxes
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(header, 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(header, hints, data, response.TableScoreMappingData, pageSetting);
}
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' || data['dataKind'] === 'Date')) {
// 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 != '' && true != data['encrypted']) {
if (data['isShowComma'] || (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);
}
}
}
// 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);
//
//// if (data['type'] === 'Decimal') {
//// if (value.indexOf('.') < 0) {
//// value += '.0';
//// }
//// }
// }
// }
// 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
if (value != null && value != '') {
value = value.toString();
value = value.replace(/\n/g,' ');
// Check value of Form_Record
if (name === 'Form_Record' && caption === 'Form_Record: ') {
value = value.replace(/&/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);
}
// PCA-180: PDF support for Shading and Spacing
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
// Each loop in repeatable section start a new page
if (isForcePageBreak === false
&& pageSetting.page_break_for_loop_question === true
&& data['type'] === CONST_CTRL_TYPE_GROUP && i !== 0) {
isForcePageBreak = true;
}
} else {
// Each loop in repeatable section start a new page
if (isForcePageBreak === false && listFirstItemInsideGroup.indexOf(name) >= 0 && pageSetting.page_break_for_loop_question === true && i !== 0) {
isForcePageBreak = true;
}
}
var isForcePageBreakActual = isForcePageBreak;
// Apply Compability > Do not show the repeatable caption in Report Settings
if (isVersion(VERSION_COMPABILITY_DONOT_SHOW_GROUP_CAPTION)) {
// The current question is a group + page break
if (pageSetting && pageSetting.isCompatibilityMode === true
&& pageSetting.isCompatibilityDontShowGroupCpt === true
&& isForcePageBreak === true
&& data['type'] === CONST_CTRL_TYPE_GROUP
&& previousData !== null
&& isForcePageBreak === true
) {
// Get previous data block for processing
if (previousData['type'] === CONST_CTRL_TYPE_GROUP || previousData['type'] === 'inputPageBreak') {
isForcePageBreak = false;
}
}
}
// 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);
}
// var block2 = createPODBlockSHADINGHelper(header, hints, data
// , POD_DELIVER_TABLE
// , response.SelectionsDataMappingInCaptions
// , response.SelectionsDataMappingInUnderlineValue
// , pageSetting
// );
// // Put block into page
// putBlockIntoPage(block2, pageSetting.two_column_format, isForcePageBreak, data);
}
// Apply Compability > Do not show the repeatable caption in Report Settings
previousData = data;
previousIsForcePageBreak = isForcePageBreakActual;
}
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 = '
Location Map
';
$('#PrintRegionData').append(mapRegionTemplate);
// Put the custom page break
$('.map_region_title').css('page-break-before', 'auto');
}
// Ignore shade headings in Report Settings (PCA-190)
// 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(){
$('#PrintRegionData').append('');
var observer = new MutationObserver(reportFormResizedWithSelector);
$('body.print_preview_body #PrintRegionData > *').each(function (index, element) {
observer.observe(element, {attributes: true, attributeFilter: ['style']});
});
reportFormResizedWithSelector();
}, 1000);
// PCA-266 Print Preview/PDF support for color option in Grids, questionnaires and Tables
// Apply custom appearance CSS for all controls
applyAppearance4ShadingHeadingsPDFLastAction();
},
error : function(request, status, error) {
jAlert(msg_unknown_error);
}
});
// // Apply Dummy Processing Excel Template
// applyDummyProcessingExcelTemplate();
}
function reportFormResizedWithSelector () {
var height = document.body.scrollHeight;
var width = $('body').outerWidth(true);
var content = $('#PrintRegionData');
if (content.length) {
width = content.outerWidth(true);
}
var eventData = {
eventType: 'doforms-form-resized',
height: height,
width: width
};
console.log(eventData);
top.postMessage(eventData, '*');
}
var GENERAL_HEADER_TEMPLATE = '
#header#
';
var GENERAL_HEADER_LABEL_TEMPLATE = '
#header#
';
var GENERAL_CONTENT_TEMPLATE = '
#content#
';
var GENERAL_HINT_TEMPLATE = '
#hint#
';
var GENERAL_HINT_IMG_TEMPLATE = '
';
/**
* Create general block content
*/
function createGeneralBlock(header, hint, content) {
var block = new Array();
block.push('
');
if (header !== '') {
block.push(GENERAL_HEADER_TEMPLATE.replace('#header#', header));
}
if (content != '') {
block.push(GENERAL_CONTENT_TEMPLATE.replace('#content#', content));
}
if (hint != '') {
block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', hint));
}
block.push('
');
var resultHTML = block.join('');
// Adjust padding-left = 0 in case of empty header
if (header === '') {
var objBlock = $(resultHTML);
objBlock.find('.content_question').css('padding-left', '0px');
//resultHTML = objBlock[0].outerHTML();
// Get outerHTML
resultHTML = jQuery('').append(objBlock).html();
}
return resultHTML;
}
/**
* Create email report content
*/
function createEmailReportBlock(header, hint, content) {
var block = new Array();
block.push('
');
block.push(GENERAL_HEADER_TEMPLATE.replace('#header#', header));
// Check if we need add hints object into GUI
if (hint !== '') {
block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', hint));
}
//block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', hint));
// Unwrap HTML
content = replaceTagBR2LineFeed(content);
// Save the line feed
//content = content.replace(/ - /, '[[\nSpecial_LINE_FEED_01\n]]');
//content = content.replace(/
- /, '[[\nSpecial_LINE_FEED_02\n]]');
// Replace content for Email To, Email Content
// - mail@yahoo.com
// =>
- mail@yahoo.com
//var regExp = /
-(.+?)
(-?)/g
//content = content.replace(regExp, '
-$1
$2');
// The email report receive from server :
//
- tran.dung.chien@quantic.com.vn- Biet em con chut doi hon.
Xuong hang MAU DO THANH PHO Mua bay ...
// will be converted into
// - tran.dung.chien@quantic.com.vn
');
return block.join('');
}
var HEADER_BLOCK_TEMPLATE = '
#header##content#
';
/**
* Create general block content
*/
function createHeaderBlock(headerBlock) {
var block = new Array();
if (headerBlock.length > 0) {
block.push('
');
for (var j = 0; j < headerBlock.length; j++) {
// Apply tag into Print/PDF
//var header = replaceTagBR2LineFeed(headerBlock[j].header);
var header = headerBlock[j].header;
var content = replaceTagBR2LineFeed(headerBlock[j].value);
block.push(HEADER_BLOCK_TEMPLATE
.replace('#header#', header + ':')
.replace('#content#', content)
);
}
block.push('
');
}
return block.join('');
}
/**
* Create label block content
*/
function createLabelBlock(header, hint, content, labelAligment, isTwoColumnFormat, dataObject) {
// Check empty label
if (header === '' && hint === '' && content === '') {
return '';
}
var block = new Array();
var wrapContent = '
';
wrapContent = wrapContent.replace('#align#', labelAligment);
// Setting height in case of empty all value
if (header === '' && hint === '' && content === '') {
wrapContent = wrapContent.replace('#height#', '20px');
block.push(wrapContent);
block.push('
');
return block.join('');
}
block.push(wrapContent);
// var leftBlock = new Array();
// Parse common tag into HTML type
var customHeader = parseCommonHTMLTags4Header(replaceTagBR2LineFeed4Label(header));
//leftBlock.push(GENERAL_HEADER_LABEL_TEMPLATE.replace('#header#', customHeader));
if (header !== '')
{
block.push(GENERAL_HEADER_LABEL_TEMPLATE.replace('#header#', customHeader));
}
if (hint !== '') {
// Apply tag into Print/PDF
//block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', replaceTagBR2LineFeed(hint)));
block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', hint));
}
var maxWidthImage = MAX_WIDTH_IMAGE / 3;
if (isTwoColumnFormat === true) {
maxWidthImage = maxWidthImage / 2;
}
// Make image label
if (content !== "") {
//rightBlock.push('');
var imgContent = '
';
// Remove space if header == '' + hints == ''
if (header === '' && hint === '') {
imgContent = imgContent.replace('spacing_general_4pdf_padding_top', '');
}
imgContent = imgContent.replace('#max_width#', maxWidthImage);
// if (header !== '' || hint !== '') {
// imgContent = imgContent.replace('#style#', 'style="padding-top:5px;"');
// }
block.push('
');
block.push(imgContent);
}
block.push('
');
var resultHtml = block.join('');
if (header === '' && hint === '') {
resultHtml = resultHtml
.replace('#style_header_of_label_border#', ' style="display:none !important;" ')
.replace('#style_label_image_region4layout#', ' style="padding-top:0px !important;" ')
;
}
// Adjust border, shading based on Label config (PCA-214)
if (isVersion(VERSION_LABEL_SHADING)) {
var settingCSSLabel = '';
// Get current information from Build Forms
var labelShading = null;
// For Lines
var linesLineColor = null;
var linesTextColor = null;
// For Shading
var shadedColor = null;
var shadedTextColor = null;
// For NoLines+Shading
var nolinesTextColor = null;
var apperance = null;
if (dataObject.apperance === LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_APPEARANCE_CUSTOM) {
if (dataObject.labelShading !== undefined) {
labelShading = dataObject.labelShading;
}
if (dataObject.linesLineColor !== undefined) {
linesLineColor = dataObject.linesLineColor;
}
if (dataObject.linesTextColor !== undefined) {
linesTextColor = dataObject.linesTextColor;
}
if (dataObject.shadedColor !== undefined) {
shadedColor = dataObject.shadedColor;
}
if (dataObject.shadedTextColor !== undefined) {
shadedTextColor = dataObject.shadedTextColor;
}
if (dataObject.nolinesTextColor !== undefined) {
nolinesTextColor = dataObject.nolinesTextColor;
}
} else {
// We are in default appearance
// Get from the Form Settings about Label Coloring config
labelShading = glbBuildFormSettingsWA.labelShading;
linesLineColor = glbBuildFormSettingsWA.labelLineColor;
linesTextColor = glbBuildFormSettingsWA.labelTextColor;
shadedColor = glbBuildFormSettingsWA.labelHeadingColor;
shadedTextColor = glbBuildFormSettingsWA.labelTextColor;
nolinesTextColor = glbBuildFormSettingsWA.labelTextColor;
}
// Check the option of labelShading
// labelShading will have one of 3 values : 1, 2 , 3
// <=> Lines / Shade / No lines or shading
if (labelShading === null || labelShading === '') {
return resultHtml;
}
// Init CSS
settingCSSLabel = '';
if (labelShading === LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_LINES) {
// Draw lines + Text color
if (linesTextColor != null) {
settingCSSLabel += ' color: ' + linesTextColor + ' !important; ';
}
if (linesLineColor != null) {
settingCSSLabel += ' border-top: 1px solid ' + linesLineColor + ' !important; ';
settingCSSLabel += ' border-bottom: 1px solid ' + linesLineColor + ' !important; ';
}
} else if (labelShading === LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_SHADE) {
// Draw shading + Text color
if (shadedTextColor != null) {
settingCSSLabel = ' color: ' + shadedTextColor + ' !important; ';
}
if (shadedColor !== null) {
settingCSSLabel += ' background: ' + shadedColor + ' !important; ';
settingCSSLabel += ' border : none !important; ';
}
} else if (labelShading === LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_NO_LINES_AND_SHADING) {
// Only setting text color
// Do nothing because we have already set color above...
if (nolinesTextColor !== null) {
settingCSSLabel += ' color: ' + nolinesTextColor + ' !important; ';
settingCSSLabel += ' border : none !important; ';
}
} else {
settingCSSLabel = '';
}
// Apply setting CSS for label
if (settingCSSLabel !== '') {
resultHtml = resultHtml
.replace('#style_header_of_label_border#', ' style=" ' + settingCSSLabel + ' " ')
}
}
return resultHtml;
}
var IMAGE_REGION_TEMPLATE = '
#image_source#
';
var ATTACHMENT_REGION_TEMPLATE = '
#attachment_source#
';
/**
* Create label block content
*/
function createImageBlock(header, hint, content) {
var block = new Array();
block.push('
');
block.push(GENERAL_HEADER_TEMPLATE.replace('#header#', header));
block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', hint));
// Make image label (if not empty)
if (content != undefined && content != null && content != "") {
var imageSource = '';
block.push(IMAGE_REGION_TEMPLATE.replace('#image_source#', imageSource));
}
block.push('
');
return block.join('');
}
function createAttachmentBlock(header, hint, content) {
var block = new Array();
block.push('
');
//
// return block.join('');
//}
var MULTIPLE_ITEM_TEMPLATE_TABLE_FORMAT = '
#multiple_item_content#
';
/**
* Create select multiple block
*/
function createSelectMultipleBlock1(header, hint, content, data, selectionsMapping) {
var block = new Array();
block.push('
');
block.push(GENERAL_HEADER_TEMPLATE.replace('#header#', header));
block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', hint));
if (content != undefined && content != null && content != 'null') {
// Browse all multiple answers
if (content.length > 0) {
block.push('
');
for (var j = 0; j < content.length; j++) {
var currentContent = content[j];
block.push('
');
// Replace into line feed
currentContent = replaceTagBR2LineFeed(currentContent);
block.push(MULTIPLE_ITEM_TEMPLATE_TABLE_FORMAT.replace('#multiple_item_content#', currentContent));
block.push('
');
}
block.push('
');
}
}
block.push('
');
return block.join('');
}
var SELECT_ONE_ITEM_TEMPLATE = MULTIPLE_ITEM_TEMPLATE;
/**
* Create ChooseOne/Score block
*/
function createChooseOneBlock(header, hint, content, data, selectionsMapping) {
var block = new Array();
block.push('
');
block.push(GENERAL_HEADER_TEMPLATE.replace('#header#', header));
block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', hint));
var originalName = getOriginalDataName(data['name']);
// Get all of answer for current question
var selectionsCaption = selectionsMapping[originalName];
if (selectionsCaption === undefined) {
selectionsCaption = [content];
}
if (selectionsCaption !== undefined && selectionsCaption !== null) {
// Browse all multiple answers
if (content === undefined || content === null || content === 'null') {
content = '';
}
block.push('
');
// Browse all available selection captions
for (var j = 0; j < selectionsCaption.length; j++) {
var currentContent = selectionsCaption[j];
//currentContent = HtmlEncode4Website(currentContent);
// Choose Check/Uncheck image
var imgPath = 'radio_tablescore_unchecked.png';
if (content === currentContent) {
imgPath = 'radio_tablescore_checked.png';
}
var lineItem = SELECT_ONE_ITEM_TEMPLATE
.replace('#img_path#', imgPath)
.replace('#multiple_item_content#', replaceTagBR2LineFeed(currentContent));
if (j === 0) {
lineItem = lineItem.replace('#first_mutiple_item#', 'multiple_item_first');
} else {
lineItem = lineItem.replace('#first_mutiple_item#', '');
}
block.push(lineItem);
}
block.push('
');
}
block.push('
');
return block.join('');
}
var INVOICE_TABLE_HEADER_TEMPLATE = '
#cell_value#
';
var INVOICE_TABLE_CELL_TEMPLATE = '
#cell_value#
';
/**
* Create Invoice Table block
* @deprecated This function will never use in the latest version
*/
function createInvoiceTableBlock(header, hint, content, fixedTableTypes, fixedTableKinds, fixedTableCurrency, isTwoColumnFormat, fixedTableDataNameHeader, dataObject) {
var block = new Array();
// PCA-266 : Print Preview/PDF support for color option in Grids, questionnaires and Tables
// block.push('
');
var classTable = ' general_question ctrlTable ';
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
// Apply shade headings (from Form Settings)
// Check if we have the appearance settings
var hasApplyShading = false;
//if (hasSettingAppearance4ShadingHeadings() === true)
{
var customApperance = applyAppearance4ShadingHeadingsPDF(dataObject);
if (customApperance === CONTROL_APPEARANCE_NO_SHADING_CHECKBOX) {
// Do not apply shading color
hasApplyShading = true;
} else if (customApperance !== '') {
classTable += customApperance;
hasApplyShading = true;
}
}
// Check if we need apply shading based on Form Setting
if (hasApplyShading == false) {
// PCA-266: Print PreviewPDF support for color option in Grids, questionnaires and Tables
classTable += ' shadingControlBackground4PDF ';
}
}
// CO-412 Table text size for PrintPreview/Standard PDFs
if (isVersion(VERSION_TABLE_TEXT_SIZE)) {
classTable += getTextSizeClassOfPrint(dataObject.textSize);
}
block.push('
'.replace('#class#', classTable));
var strHeader = GENERAL_HEADER_TEMPLATE.replace('#header#', header);
var strHint = GENERAL_HINT_TEMPLATE.replace('#hint#', hint);
block.push(strHeader);
block.push(strHint);
// PCA-212 (Print Preview/PDF support for Text Calculations)
var fTblShowAsTextMobile = null;
var fTblMobileTextAlign = null;
if (isVersion(VERSION_CALCULATION_KIND_STRING)) {
// fixedTable_showAsTextMobile
if (dataObject[FIXED_TABLE_CALC_SHOW_TEXT_MOBILE] !== undefined) {
fTblShowAsTextMobile = dataObject[FIXED_TABLE_CALC_SHOW_TEXT_MOBILE];
}
// fixedTable_mobileTextAlign
if (dataObject[FIXED_TABLE_CALC_MOBILE_TEXT_ALIGN] !== undefined) {
fTblMobileTextAlign = dataObject[FIXED_TABLE_CALC_MOBILE_TEXT_ALIGN];
}
}
// The content will be a JSON object
if (content != undefined && content != null && content != 'null') {
// Browse all multiple answers
if (content.length > 0) {
var totalWidth = 160;
// Special width for IE
if (browserNameGlobal == 'ie') { totalWidth = 160; }
if (isTwoColumnFormat == true) {
totalWidth = 73;
// Special width for IE
if (browserNameGlobal == 'ie') { totalWidth = 73; }
block.push('
');
} else {
block.push('
');
}
var numTableColumns = content[0].length;
// var widthValueCss = totalWidth / numTableColumns;
// var widthValueCssInPercent = 100 / numTableColumns;
var strWidthCss = 'style="#text_align#vertical-align:middle; width:#width#%; max-width:#maxWidth#mm !important; #padding#"'
// .replace('#width#', widthValueCssInPercent)
// .replace('#maxWidth#', widthValueCss)
;
// The flag for checking process alignment for table cell
var isNeededCheckAlignment = true;
if (fixedTableTypes == undefined || fixedTableTypes == null || fixedTableTypes.length != numTableColumns) {
isNeededCheckAlignment = false;
}
// Init the width array in percent/millimet
var arrColWidthPercent = new Array();
var arrColWidthMillis = new Array();
processColumnWidth4ContainerPDF(dataObject
, arrColWidthPercent
, arrColWidthMillis
, totalWidth
, numTableColumns
);
for (var row = 0; row < content.length; row++) {
// With odd rows, we will highlight row by background
if (row % 2 == 0) {
block.push('
');
} else {
block.push('
');
}
var currentLineData = content[row];
if (currentLineData != null) {
for (var col = 0; col < currentLineData.length; col++) {
var strWidthCss4Cell = strWidthCss;
var cellValue = INVOICE_TABLE_CELL_TEMPLATE;
// Get header row
if (row == 0) {
cellValue = INVOICE_TABLE_HEADER_TEMPLATE;
}
// The actual value of current cell
var strCurrentValue = currentLineData[col];
// PCA-174 (PDF/Excel Reports support for New Grid Type)
var wPercent = arrColWidthPercent[col];
var wMillis = arrColWidthMillis[col];
// Replace the custom width
strWidthCss4Cell = strWidthCss4Cell
.replace('#width#', wPercent)
.replace('#maxWidth#', wMillis)
;
// Fix bug 0023779: PDF Report - Table - Header not smooth when the widget inside table use space
if (row == 0) {
// Special treating with header, auto trim value of header, ignore all SPACE
strCurrentValue = strCurrentValue.trim();
// Adjust text-align:center;
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:center;');
}
// Fix bug 0021690: Suggestion - on Report: Should apply the adding comma signal for thousandths of Calculation field without using currency symbol
// Fix bug 0023342: Calculation DateTime displays wrong format in report
var currentTypeInFixedTable = fixedTableTypes[col];
var currentKindInFixedTable = null;
if (fixedTableKinds !== undefined && fixedTableKinds !== null) {
currentKindInFixedTable = fixedTableKinds[col];
}
// PCA-212 : Print Preview/PDF support for Text Calculations
var curCalcShowTxtMb = null;
if (fTblShowAsTextMobile !== null) {
curCalcShowTxtMb = fTblShowAsTextMobile[col];
}
var curCalcAlignment = null;
if (fTblMobileTextAlign !== null) {
curCalcAlignment = fTblMobileTextAlign[col];
}
// Process alignment for cell value (Normal => LEFT, Number => RIGHT)
if (row > 0 && isNeededCheckAlignment == true) {
var isLeftAlign = true;
switch (currentTypeInFixedTable) {
case 'Integer' :
case 'Decimal' :
case CONST_CTRL_TYPE_INPUT_NUMERIC :
case CONST_CTRL_TYPE_INPUTCALCULATE :
// With Calculation DateTime, we will set align left
// Fix bug 0021146: PDF&Print View - Alignment display incorrectly at Table and Grid question
if (currentKindInFixedTable === CONST_VALUE_DATE || currentKindInFixedTable === CONST_CTRL_TYPE_INPUTDATE) {
isLeftAlign = true;
break;
}
// PCA-212 (Print Preview/PDF support for Text Calculations)
if (isVersion(VERSION_CALCULATION_KIND_STRING)) {
if (currentTypeInFixedTable === CONST_CTRL_TYPE_INPUTCALCULATE
&& currentKindInFixedTable === 'String'
&& curCalcShowTxtMb === true
)
{
// Align Right
if (curCalcAlignment === CALCULATION_TEXT_MOBILE_ALIGNMENT_RIGHT) {
isLeftAlign = false;
} else if (curCalcAlignment === CALCULATION_TEXT_MOBILE_ALIGNMENT_CENTER) {
// Align Center (direct setting in CSS)
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:center;')
.replace('#padding#', '');
} else {
isLeftAlign = true;
}
}
}
// Fix bug 0022362: Calculation, number > 1000 display wrong on report - see attach file
if (currentKindInFixedTable === 'Number'
|| currentKindInFixedTable === 'Decimal'
|| currentKindInFixedTable === 'Integer'
|| currentKindInFixedTable === CONST_CTRL_TYPE_INPUT_NUMERIC) {
isLeftAlign = false;
break;
}
case CONST_CTRL_TYPE_INPUTTRENDS :
// Only align right with number
try {
if (!isNaN(parseFloat(strCurrentValue)) && isFinite(strCurrentValue)) {
isLeftAlign = false;
}
} catch (e) {}
break;
case CONST_CTRL_TYPE_INPUTCOUNTER :
// Align center with Counter in FixedTable
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:center;')
.replace('#padding#', '');
break;
default :
isLeftAlign = true;
}
if (isLeftAlign == true) {
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:left;')
.replace('#padding#', 'padding-leftx: ' + PADDING_LEFT_INVOICE_TABLE_GENERAL + 'px !important;');
} else {
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:right;')
.replace('#padding#', 'padding-rightx: ' + PADDING_LEFT_INVOICE_TABLE_GENERAL + 'px !important;');
}
}
// Put style width for header row
cellValue = cellValue.replace('#style_column#', strWidthCss4Cell);
// Put style width for cell value
// Special processing for IE
// PCA-174 (PDF/Excel Reports support for New Grid Type)
// if (browserNameGlobal == 'ie') {
// cellValue = cellValue.replace('#style_value#', 'style="max-width:' + wMillis + 'mm; width:' + wMillis + 'mm;"');
// } else {
// cellValue = cellValue.replace('#style_value#', 'style="max-width:' + wMillis + 'mm;"');
// }
cellValue = cellValue.replace('#style_value#', 'style="max-width:' + (wMillis+3) + 'mm;"');
// Replace all into line feed
strCurrentValue = replaceTagBR2LineFeed(strCurrentValue);
if (strCurrentValue == null || strCurrentValue == '') {
strCurrentValue = ' ';
}
// Modify value in case of using currency (for Numeric/Calculation)
//if (row > 0) {
var currentChildName = '';
var currentFixedTableCurrency = fixedTableCurrency[col];
if (currentFixedTableCurrency != null && currentFixedTableCurrency != undefined) {
if (strCurrentValue !== '' && strCurrentValue !== ' ') {
// Apply format number using currency with format ,
//var currentChildName = '';
if (fixedTableDataNameHeader !== undefined) {
currentChildName = fixedTableDataNameHeader[col];
}
// Fix customer ticket : [doForms Community & Support] Assignment: Account: tgrmaintenance ; PDF export/email
// Only format number currency in case NOT HEADER ROW
if (row > 0) {
strCurrentValue = formatNumberValue4Currency(strCurrentValue, currentFixedTableCurrency, currentTypeInFixedTable, currentChildName);
}
// strCurrentValue = formatNumberValue4Currency(strCurrentValue, currentFixedTableCurrency, currentTypeInFixedTable, currentChildName);
}
}
//}
// Fix bug 0021690: Suggestion - on Report: Should apply the adding comma signal for thousandths of Calculation field without using currency symbol
// Fix bug 0023342: Calculation DateTime displays wrong format in report
if (strCurrentValue !== '') {
if (currentTypeInFixedTable === CONST_CTRL_TYPE_INPUTCALCULATE &&
(currentKindInFixedTable === CONST_VALUE_DATE || currentKindInFixedTable === CONST_CTRL_TYPE_INPUTDATE)
) {
strCurrentValue = formatCalculationDateTimeValue(strCurrentValue, currentTypeInFixedTable, currentChildName);
}
}
cellValue = cellValue.replace('#cell_value#', strCurrentValue);
block.push(cellValue);
}
}
block.push('
');
}
block.push('
');
}
}
block.push('');
// PCA-174 (PDF/Excel Reports support for New Grid Type)
var resultHTML = block.join('');
// Check version for apply shading
if (!isVersion(VERSION_GRID_TYPE_FUNCTION)) {
return resultHTML;
}
var tableHTML = '';
var $wrapper = null;
// var isNeedShading = false;
// The shading in normal cases
var shadedKind = '';
if (dataObject._tableContainerShadeKind !== undefined && dataObject._tableContainerShadeKind !== null) {
shadedKind = dataObject._tableContainerShadeKind;
}
$wrapper = $(resultHTML);
var $table = $wrapper.find('table');
// Apply shading based on shadedKind
if (shadedKind === TABLE_CONSTANTS_VALUE_OPTION_BF_FIRST_COL_ONLY
|| shadedKind === TABLE_CONSTANTS_VALUE_OPTION_BF_EVERY_OTHER_COL) {
applyShading4TableContainerInPW4ColumnFormat($table, shadedKind);
} else {
// Apply shading for Every row/Top row
applyShading4TableContainerInPW($table, dataObject);
}
//applyShading4TableContainerInPW($table, dataObject, shadedKind);
// Check if we need use default shading
if ($wrapper !== null) {
// Create the full block of tableHTML wrapper
//return '
' + tableHTML + '
';
return getAllControlHTMLWrapperWebSite($wrapper);
}
return resultHTML;
}
/**
* Create Grid block (same as InvoiceTable)
* @deprecated This function is never used in latest version
*/
function createGridBlock(header, hint, content, numTableColumns, isTwoColumnFormat, pageSetting, dataObject) {
var block = new Array();
// PCA-266 : Print Preview/PDF support for color option in Grids, questionnaires and Tables
// block.push('
');
var classGrid = ' general_question ctrlGrid ';
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
// Apply shade headings (from Form Settings)
// Check if we have the appearance settings
var hasApplyShading = false;
//if (hasSettingAppearance4ShadingHeadings() === true)
{
var customApperance = applyAppearance4ShadingHeadingsPDF(dataObject);
if (customApperance === CONTROL_APPEARANCE_NO_SHADING_CHECKBOX) {
// Do not apply shading color
hasApplyShading = true;
} else if (customApperance !== '') {
classGrid += customApperance;
hasApplyShading = true;
}
}
// Check if we need apply shading based on Form Setting
if (hasApplyShading == false) {
classGrid += ' shadingControlBackground4PDF ';
}
}
// Apply gridType
var gridTypeLayout = dataObject._gridType4Layout;
if (gridTypeLayout === GRID_TYPE_ROW_BASED_JAVASCRIPT) {
classGrid += ' gridTypeRowBased4PDF ';
} else if (gridTypeLayout === GRID_TYPE_COLUMN_BASED_JAVASCRIPT) {
classGrid += ' gridTypeColumnBased4PDF ';
} else if (gridTypeLayout === GRID_TYPE_CENTER_GRID_JAVASCRIPT) {
classGrid += ' gridTypeCenterGrid4PDF ';
}
block.push('
'.replace('#class#', classGrid));
block.push(GENERAL_HEADER_TEMPLATE.replace('#header#', header));
block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', hint));
// Adjust max width image with Scale image
var maxWidthImagePercent = '100%';
// PCA-406: Report Settings
// Ignore Scale image in Standard Report Pdf
// switch (pageSetting.scale_image) {
// case SCALE_IMAGE_VALUE14 : maxWidthImagePercent = '25%'; break;
// case SCALE_IMAGE_VALUE13 : maxWidthImagePercent = '33%'; break;
// case SCALE_IMAGE_VALUE12 : maxWidthImagePercent = '50%'; break;
// case SCALE_IMAGE_VALUE23 : maxWidthImagePercent = '66%'; break;
// }
// The content will be a JSON object
if (content != undefined && content != null && content != 'null') {
// Browse all multiple answers
if (content.length > 0) {
// PCA-174 (PDF/Excel Reports support for New Grid Type)
//var totalWidth = 160;
var totalWidth = 170;
// Special width for IE
//if (browserNameGlobal == 'ie') { totalWidth = 160; }
if (isTwoColumnFormat == true) {
// PCA-174 (PDF/Excel Reports support for New Grid Type)
//totalWidth = 73;
totalWidth = 80;
// Special width for IE
//if (browserNameGlobal == 'ie') { totalWidth = 73; }
block.push('
');
} else {
block.push('
');
}
// PCA-174 (PDF/Excel Reports support for New Grid Type)
// var widthValueCss = totalWidth / numTableColumns;
// var widthValueCssInPercent = 100 / numTableColumns;
var strWidthCss = 'style="#text_align#vertical-align:top; width:#width#%; max-width:#maxWidth#mm !important; #padding# #label_style# " '
// .replace('#width#', widthValueCssInPercent)
// .replace('#maxWidth#', widthValueCss)
;
// Init the width array in percent/millimet
var arrColWidthPercent = new Array();
var arrColWidthMillis = new Array();
processColumnWidth4ContainerPDF(dataObject
, arrColWidthPercent
, arrColWidthMillis
, totalWidth
, numTableColumns
);
// The flag for checking process alignment for table cell
var isNeededCheckAlignment = true;
var numRow = content.length / numTableColumns;
var controlIndex = 0;
for (var row = 0; row < numRow; row++) {
// Exit when we goto the last column
if (controlIndex >= content.length) { break; }
// With odd rows, we will highlight row by background
if (row % 2 === 0) {
if (!isVersion(VERSION_GRID_TYPE_FUNCTION)) {
block.push('
');
} else {
block.push('
');
}
} else {
block.push('
');
}
for (var col = 0; col < numTableColumns; col++) {
// The current control inside Grid
var child = content[controlIndex];
// Create a dummy child when we are over of last column
// (for filling empty last cells, not breaking layout)
if (controlIndex >= content.length) {
child = new Object();
child['type'] = '';
child[CONST_VALUE] = '';
}
var strWidthCss4Cell = strWidthCss;
var cellValue = INVOICE_TABLE_CELL_TEMPLATE;
// Get header row
// if (row == 0) {
// cellValue = INVOICE_TABLE_HEADER_TEMPLATE;
// }
// The actual value of current cell inside Grid
var strCurrentValue = child[CONST_VALUE];
var currentTypeInGrid = child['type'];
// Fix bug 0021690: Suggestion - on Report: Should apply the adding comma signal for thousandths of Calculation field without using currency symbol
// Fix bug 0023342: Calculation DateTime displays wrong format in report
var currentKindInGrid = child['kind'];
// Process alignment for cell value (Normal => LEFT, Number => RIGHT)
if (row >= 0 && isNeededCheckAlignment == true) {
var isLeftAlign = true;
var isImageField = false;
switch (currentTypeInGrid) {
case 'Integer' :
case 'Decimal' :
case CONST_CTRL_TYPE_INPUT_NUMERIC :
case CONST_CTRL_TYPE_INPUTTRENDS :
case CONST_CTRL_TYPE_INPUTCALCULATE :
// With Calculation DateTime, we will set align left
// Fix bug 0021146: PDF&Print View - Alignment display incorrectly at Table and Grid question
if (currentKindInGrid === CONST_VALUE_DATE || currentKindInGrid === CONST_CTRL_TYPE_INPUTDATE) {
isLeftAlign = true;
break;
}
// Fix bug 0022362: Calculation, number > 1000 display wrong on report - see attach file
if (currentKindInGrid === 'Number' || currentKindInGrid === CONST_CTRL_TYPE_INPUT_NUMERIC
|| currentKindInGrid === 'Integer' || currentKindInGrid === 'Decimal') {
isLeftAlign = false;
break;
}
// PCA-212 : Print Preview/PDF support for Text Calculations
if (isVersion(VERSION_CALCULATION_KIND_STRING)) {
if (currentTypeInGrid === CONST_CTRL_TYPE_INPUTCALCULATE
&& currentKindInGrid === 'String'
&& child['showAsTextMobile'] === true
) {
// Align Right
if (child['mobileTextAlign'] === CALCULATION_TEXT_MOBILE_ALIGNMENT_RIGHT) {
isLeftAlign = false;
break;
}
// Align Center in Grid (direct setting in CSS)
else if (child['mobileTextAlign'] === CALCULATION_TEXT_MOBILE_ALIGNMENT_CENTER) {
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:center !important;')
.replace('#padding#', '');
break;
} else {
isLeftAlign = true;
break;
}
}
}
// Only align right with number
try {
if (!isNaN(parseFloat(strCurrentValue)) && isFinite(strCurrentValue)) {
isLeftAlign = false;
}
} catch (e) {}
break;
case CONST_CTRL_TYPE_INPUTNUMBERING :
// Align left with AutoNumber in Grid
// Fix bug 0024506: PDF Report and Email Report - Autonumber inside Grid is aligned incorrectly
isLeftAlign = true;
break;
case CONST_CTRL_TYPE_INPUTCOUNTER :
// Align center with Counter in Grid
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:center !important;')
.replace('#padding#', '');
break;
case CONST_CTRL_TYPE_INPUTIMAGE :
case 'Image' :
case CONST_CTRL_TYPE_INPUTSKETCH :
case 'Sketch' :
case CONST_CTRL_TYPE_INPUTSIGNATURE :
case 'Signature' :
isImageField = true;
break;
default :
isLeftAlign = true;
}
// Align center with image field (Image/Sketch/Signature)
if (isImageField === true) {
// With Image/Sketch/Signature, we align center
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:center !important;');
// Center in vertical orientation
// Apply scale image in Grid based on Report Settings
strWidthCss4Cell = strWidthCss4Cell.replace('vertical-align:top;', 'vertical-align:middle;')
.replace('#padding#', '');
}
if (isLeftAlign === true) {
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:left !important;')
.replace('#padding#', 'padding-leftx: ' + PADDING_LEFT_INVOICE_TABLE_GENERAL + 'px !important;');
} else {
// Align with number/calculation, ...
strWidthCss4Cell = strWidthCss4Cell.replace('#text_align#', 'text-align:right !important;')
.replace('#padding#', 'padding-rightx: ' + PADDING_LEFT_INVOICE_TABLE_GENERAL + 'px !important;');
}
}
// PCA-174 (PDF/Excel Reports support for New Grid Type)
var wPercent = arrColWidthPercent[col];
var wMillis = arrColWidthMillis[col];
// Replace the custom width
strWidthCss4Cell = strWidthCss4Cell
.replace('#width#', wPercent)
.replace('#maxWidth#', (wMillis - 4) ) // tdchien PROCESS
;
// Put style width for header row
cellValue = cellValue.replace('#style_column#', strWidthCss4Cell);
// PCA-174 (PDF/Excel Reports support for New Grid Type)
// Put style width for cell value
// Special processing for IE
// if (browserNameGlobal == 'ie') {
// // Apply scale image in Grid based on Report Settings
// if (isImageField === true) {
// cellValue = cellValue.replace('#style_value#', 'style="text-align:center;"');
// } else {
// // PCA-174 (PDF/Excel Reports support for New Grid Type)
// //cellValue = cellValue.replace('#style_value#', 'style="max-width:' + widthValueCss + 'mm; width:' + widthValueCss + 'mm;"');
// cellValue = cellValue.replace('#style_value#', 'style="max-width:' + widthValueCss + 'mm; "');
// }
// //cellValue = cellValue.replace('#style_value#', 'style="max-width:' + widthValueCss + 'mm; width:' + widthValueCss + 'mm;"');
// } else {
// // Apply scale image in Grid based on Report Settings
// //cellValue = cellValue.replace('#style_value#', 'style="max-width:' + widthValueCss + 'mm;"');
// if (isImageField === true) {
// cellValue = cellValue.replace('#style_value#', 'style="text-align:center;"');
// } else {
// cellValue = cellValue.replace('#style_value#', 'style="max-width:' + widthValueCss + 'mm;"');
// }
// }
// PCA-174 (PDF/Excel Reports support for New Grid Type)
// Apply scale image in Grid based on Report Settings
//cellValue = cellValue.replace('#style_value#', 'style="max-width:' + widthValueCss + 'mm;"');
if (isImageField === true) {
cellValue = cellValue.replace('#style_value#', 'style="text-align:center;"');
} else {
cellValue = cellValue.replace('#style_value#', 'style="max-width:' + (wMillis+3) + 'mm;"');
}
// Process value based on current type (ignore empty value for preventing error image loading)
if (strCurrentValue != '') {
if (isImageField === true) {
strCurrentValue = ''
.replace(/#image#/g, child[CONST_VALUE]);
//.replace('#max_width#', widthValueCss + 'mm');
// Control max-width based on scale on Report Settings
strCurrentValue = strCurrentValue.replace('#max_width#', maxWidthImagePercent);
} else {
// Replace all into line feed
strCurrentValue = replaceTagBR2LineFeed(strCurrentValue);
}
}
if (strCurrentValue === null || strCurrentValue === '') {
strCurrentValue = ' ';
}
// Process currency
var currentGridCurrency = child['currency'];
if (child['useCurrentcySymbol'] === true && currentGridCurrency !== undefined && currentGridCurrency !== null) {
if (strCurrentValue !== '' && strCurrentValue !== ' ') {
// Apply format number using currency with format ,
strCurrentValue = formatNumberValue4Currency(strCurrentValue, currentGridCurrency, currentTypeInGrid, child['name']);
}
}
// Process current child hint value (ignore the header row)
if (row !== 0 && pageSetting.display_hints === true
&& child['hint'] !== undefined && child['hint']['eng'] !== undefined) {
curHint = replaceTagBR2LineFeed(child['hint']['eng']);
// Put dummy data
curHint = '';
if (curHint !== '') {
curHint = GENERAL_HINT_TEMPLATE.replace('#hint#', curHint);
if (strCurrentValue === '' || strCurrentValue === ' ') {
strCurrentValue = curHint;
} else if (isImageField) {
strCurrentValue = curHint + ' ' + strCurrentValue;
} else {
strCurrentValue = curHint + strCurrentValue;
}
}
}
// Fix bug 0021690: Suggestion - on Report: Should apply the adding comma signal for thousandths of Calculation field without using currency symbol
// Fix bug 0023342: Calculation DateTime displays wrong format in report
if (currentTypeInGrid === CONST_CTRL_TYPE_INPUTCALCULATE &&
(currentKindInGrid === CONST_VALUE_DATE || currentKindInGrid === CONST_CTRL_TYPE_INPUTDATE)
) {
strCurrentValue = formatCalculationDateTimeValue(strCurrentValue, currentTypeInGrid, child['name']);
}
cellValue = cellValue.replace('#cell_value#', strCurrentValue);
// Special treating with Label question inside Grid
// PCA-174 (PDF/Excel Reports support for New Grid Type)
if (currentTypeInGrid === 'inputLabel' || currentTypeInGrid === 'inputLabelDummy4Grid') {
cellValue = applyControl4LabelInGridCellPdf(cellValue, child, pageSetting);
}
block.push(cellValue);
// Increase control index for going to next control inside Grid
controlIndex++;
}
block.push('
');
}
block.push('
');
}
}
block.push('');
// PCA-174 (PDF/Excel Reports support for New Grid Type)
var resultHTML = block.join('');
// Check version for apply shading
if (!isVersion(VERSION_GRID_TYPE_FUNCTION)) {
return resultHTML;
}
var tableHTML = '';
var $wrapper = null;
// Check if we need shading table or not
var gridType = '';
if (dataObject._gridType4Layout !== undefined && dataObject._gridType4Layout !== null) {
gridType = dataObject._gridType4Layout;
}
$wrapper = $(resultHTML);
var $table = $wrapper.find('table');
// 0027015: Border bug issue
applyShading4GridCustomSpecial($table, dataObject.value, gridType);
resultHTML = getAllControlHTMLWrapperWebSite($wrapper);
// Return the original HTML (before apply custom shading)
return resultHTML;
}
/**
* Create Table Score block
* This function using algorithm same as PdfPrintObject.createTableScoreBlock()
* @deprecated This function is never used in the latest version
*
* @param {} header
* @param {} hint
* @param {} data
* @param {} tableScoreMappingData
* @param {} isTwoColumnFormat
* @returns {}
*/
var IMAGE_DATA_4_TABLE_SCORE_CONTENT_TEMPLATE = '';
var TABLE_SCORE_HEADER_TEMPLATE = '
#cell_value#
';
var TABLE_SCORE_CELL_TEMPLATE = '
#cell_value#
#hints#
';
var TABLE_SCORE_CELL_COMMENT_TEMPLATE = '
#cell_value#
';
function createTableScoreBlock(header, hint, data, tableScoreMappingData, pageSetting) {
var block = new Array();
// PCA-266 : Print Preview/PDF support for color option in Grids, questionnaires and Tables
//block.push('
');
var classTableScore = ' general_question ctrlScoreTable ';
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
// Apply shade headings (from Form Settings)
// Check if we have the appearance settings
var hasApplyShading = false;
//if (hasSettingAppearance4ShadingHeadings() === true)
{
var customApperance = applyAppearance4ShadingHeadingsPDF(data);
if (customApperance === CONTROL_APPEARANCE_NO_SHADING_CHECKBOX) {
// Do not apply shading color
hasApplyShading = true;
} else if (customApperance !== '') {
classTableScore += customApperance;
hasApplyShading = true;
}
}
// Check if we need apply shading based on Form Setting
if (hasApplyShading == false) {
classTableScore += ' shadingControlBackground4PDF ';
}
}
block.push('
'.replace('#class#', classTableScore));
block.push(GENERAL_HEADER_TEMPLATE.replace('#header#', header));
block.push(GENERAL_HINT_TEMPLATE.replace('#hint#', hint));
try {
// The first item will be using in standard.
// Check the first item is a SelectOne/Score or SelectMultiple
var tableName = data['name'];
var childrens = tableScoreMappingData[tableName];
var firstItem = childrens[0];
var headerData = new Array();
var headerDataCaption = new Array();
var firstType = firstItem['type'];
// The mapping value for rendering data in PDF
// Save []Image and [x]Image into mappingTableScoreValue
var mappingTableScoreValue = new Object();
var emptyImage = null;
var checkedImage = null;
if (firstType === CONST_CTRL_TYPE_INPUTSELECTMANY) {
emptyImage = 'checkbox_tablescore_unchecked.gif';
checkedImage = 'checkbox_tablescore_checked.gif';
} else {
emptyImage = 'radio_tablescore_unchecked.gif';
checkedImage = 'radio_tablescore_checked.gif';
}
// Update full template for showing IMAGE
emptyImage = IMAGE_DATA_4_TABLE_SCORE_CONTENT_TEMPLATE.replace('#image_file#', emptyImage);
checkedImage = IMAGE_DATA_4_TABLE_SCORE_CONTENT_TEMPLATE.replace('#image_file#', checkedImage);
// Create list of headers (based on option list)
var options = firstItem['options'];
for (var i = 0; i < options.length; i++) {
headerData.push( options[i][CONST_VAL] );
headerDataCaption.push( replaceTagBR2LineFeed(options[i]['text']['eng']) );
}
// Apply task : https://doforms.atlassian.net/browse/PCA-136
// (Ability to change the caption when appending a comment in Questionaire)
// Put the comment column based on current ScoreCard config ([]Append comment field)
headerData.push('Comment');
// headerDataCaption.push('Comment');
var listFields = new Array();
var listFieldsCaption = new Array();
var listFieldsHints = new Array();
var listFieldsComments = new Array();
for (var i = 0; i < childrens.length; i++) {
// We have to get data inside tableScoreMappingData
// because it also contains value in GUI
var item = tableScoreMappingData[childrens[i].name];
// Get value based on current type
var curType = item['type'];
var curName = item['name'];
var curCaption = replaceTagBR2LineFeed(item['label']['eng']);
// Setting curCaption based on Report Settings
// Fix bug 0018492: Questions inside Questionnaire still not display Dataname based on Report Settings
if (pageSetting.display_data_name === true) {
curCaption = curName;
}
var curHint = '';
// Setting current hint based on PageSettings
if (pageSetting.display_hints === true
&& item['hint'] !== undefined && item['hint']['eng'] !== undefined) {
curHint = replaceTagBR2LineFeed(item['hint']['eng']);
}
var curComment = item[TABLE_SCORE_COMMENT_NAME];
if (curComment === undefined || curComment === null) { curComment = ''; }
listFields.push(curName);
listFieldsCaption.push(curCaption);
listFieldsHints.push(curHint);
listFieldsComments.push(item[TABLE_SCORE_COMMENT_NAME]);
// When the current item has no value <=> EMPTY
if (item[CONST_VALUE] === undefined || item[CONST_VALUE] === null) { continue; }
// Create mapping data for rendering in PDF
if (curType === CONST_CTRL_TYPE_INPUTSELECTMANY) {
var strSelectValues = item[CONST_VALUE].replace(/ /g, ' ').replace(/ /g, '<br>');
var arrValue = strSelectValues.split('<br>');
for (var t = 0; t < arrValue.length; t++) {
mappingTableScoreValue[curName + "_" + arrValue[t]] = true;
}
} else if (curType === CONST_CTRL_TYPE_INPUTSELECTONE || curType === CONST_CTRL_TYPE_INPUTSCOREONE) {
var curValue = item[CONST_VALUE];
if (curValue != '') {
mappingTableScoreValue[curName + "_" + curValue] = true;
}
}
}
// Render data into GUI same as Invoice Table
var totalWidth = 160;
// Special width for IE
if (browserNameGlobal == 'ie') { totalWidth = 160; }
if (pageSetting.two_column_format == true) {
totalWidth = 73;
// Special width for IE
if (browserNameGlobal == 'ie') { totalWidth = 73; }
block.push('
');
} else {
block.push('
');
}
// The flag about checking equal spacing columns
var isEqualColumnSpacing = true;
if (tableScoreMappingData[tableName + '~isEqualColumnSpacing~'] !== undefined) {
isEqualColumnSpacing = tableScoreMappingData[tableName + '~isEqualColumnSpacing~'];
}
// The flag about checking []Append comment (default is false)
var isAppendComment = false;
if (tableScoreMappingData[tableName + '~appendCommentInScoreCard~'] !== undefined) {
isAppendComment = tableScoreMappingData[tableName + '~appendCommentInScoreCard~'];
}
// Apply task : https://doforms.atlassian.net/browse/PCA-136
// (Ability to change the caption when appending a comment in Questionaire)
if (currentVersion >= VERSION_SHOW_COMMENT_LABEL_QUESTIONNAIRE_PRINT_PREVIEW) {
// Put the caption for label comment
var labelCommentAppend = lbl_score_table_col_comment;
if (tableScoreMappingData[tableName + '~labelCommentInScoreCard~'] !== undefined) {
labelCommentAppend = tableScoreMappingData[tableName + '~labelCommentInScoreCard~'];
}
if (labelCommentAppend == '') {
labelCommentAppend = 'Comment';
}
// Put the custom comment
headerDataCaption.push(labelCommentAppend);
} else {
headerDataCaption.push('Comment');
}
// Add the comment column
var numTableColumns = (headerData.length+1);
// var widthValueCss = totalWidth / numTableColumns;
// var widthValueCssInPercent = 100 / numTableColumns;
var strWidthCss = 'style="#text_align#vertical-align:middle; width:#width#%; max-width:#maxWidth#mm !important;"'
// .replace('#width#', widthValueCssInPercent)
// .replace('#maxWidth#', widthValueCss)
;
// Init the width array in percent/millimet
var arrColWidthPercent = new Array();
var arrColWidthMillis = new Array();
var actualNumTableColumns = numTableColumns;
if (isAppendComment !== true) {
actualNumTableColumns--;
}
processColumnWidth4ContainerPDF(data
, arrColWidthPercent
, arrColWidthMillis
, totalWidth
, actualNumTableColumns
);
// Put header row
//block.push('
');
block.push('
');
for (var col = 0; col < headerData.length+1; col++) {
// Put the comment column based on current ScoreCard config ([]Append comment field)
if (isAppendComment !== true && col >= headerData.length) {
continue;
}
var headerCaption = '';
// Only get caption with the second column or above
if (col > 0) {
headerCaption = headerDataCaption[col-1];
}
// Make the header row (first row) BOLD
var strWidthCss4Cell = strWidthCss.replace('#text_align#', 'text-align: center; font-weight:bold;');
var cellValue = TABLE_SCORE_HEADER_TEMPLATE.replace('#cell_value#', headerCaption).replace('#hints#', '');
// PCA-174 (PDF/Excel Reports support for New Grid Type)
// Apply custom percent/default
// PCA-174 (PDF/Excel Reports support for New Grid Type)
var wPercent = arrColWidthPercent[col];
var wMillis = arrColWidthMillis[col];
// Replace the custom width
strWidthCss4Cell = strWidthCss4Cell
.replace('#width#', wPercent)
.replace('#maxWidth#', wMillis)
;
// Put style width for header row
// if (isEqualColumnSpacing === true) {
// cellValue = cellValue.replace('#style_column#', strWidthCss4Cell);
// } else
// {
// // Make BOLD
// cellValue = cellValue.replace('#style_column#', 'style="font-weight:bold; text-align:center;"');
// }
cellValue = cellValue.replace('#style_column#', strWidthCss4Cell);
block.push(cellValue);
}
block.push('
');
for (var row = 0; row < childrens.length; row++) {
// With odd rows, we will highlight row by background
if (row % 2 != 0) {
block.push('
');
} else {
block.push('
');
}
var fieldName = listFields[row];
// Make the first column is NOT BOLD
//var strWidthCss4Cell = strWidthCss.replace('#text_align#', 'text-align: left; font-weight:bold; ');
var strWidthCss4Cell = strWidthCss.replace('#text_align#', 'text-align: left; padding-leftx:' + PADDING_LEFT_INVOICE_TABLE_GENERAL + 'px !important; ');
// Limit width for the first field
var cellValue = TABLE_SCORE_CELL_TEMPLATE.replace('#cell_value#', listFieldsCaption[row]);
// Adding hints (if exists)
var curHints = listFieldsHints[row];
if (curHints !== '') {
cellValue = cellValue.replace('#hints#', '
' + curHints + '
');
} else {
cellValue = cellValue.replace('#hints#', '');
}
// PCA-174 (PDF/Excel Reports support for New Grid Type)
// Put style width for header row
// if (isEqualColumnSpacing === true) {
// cellValue = cellValue.replace('#style_column#', strWidthCss4Cell);
// } else
{
// The normal case (NOT BOLD)
//cellValue = cellValue.replace('#style_column#', 'style="font-weight:bold;"');
cellValue = cellValue.replace('#style_column#', 'style=""');
}
// The first cell is the field name
block.push(cellValue);
for (var col = 0; col < headerData.length - 1; col++) {
var hdr = headerData[col];
block.push('
');
// Get mapping object data value for putting []Uncheck or [x]Checked
if (mappingTableScoreValue[fieldName + '_' + hdr] === undefined) {
// Put empty image
block.push(emptyImage);
} else {
// Put checked image
block.push(checkedImage);
}
block.push('
');
}
// Put the comment column based on current ScoreCard config ([]Append comment field)
if (isAppendComment === true) {
// Fix bug 0023701: Value of questionnaire comment display incorrectly if having special chars (EX: $&)
var strCommentValNotRegular = listFieldsComments[row].replace('$', "$");
var cellValueComment = TABLE_SCORE_CELL_COMMENT_TEMPLATE.replace('#cell_value#', strCommentValNotRegular);
if(false == pageSetting.hideEntryBoxes){
cellValueComment = cellValueComment.replace('invoice_table_cell_value','invoice_table_cell_value forComment');
}
var strWidthCss4CellCmt = strWidthCss.replace('#text_align#', 'text-align: left;');
// Put style width for header row
// if (isEqualColumnSpacing === true)
// {
// cellValueComment = cellValueComment.replace('#style_column#', strWidthCss4CellCmt);
// } else
{
// The normal case
cellValueComment = cellValueComment.replace('#style_column#', 'style=""');
}
block.push(cellValueComment);
}
block.push('
');
}
block.push('
');
} catch (ex) {
writeToLogInfo('Exception in createTableScoreBlock() : ' + ex);
}
block.push('');
return block.join('');
}
/**
* Create the data all in JSON object
*/
function processDataAllCurrentRecord(caption, dataName, dataType, dataValue) {
var dataAll = new Array();
// Validate data
if (caption.length != dataName.length
|| dataName.length != dataType.length
|| dataType.length != dataValue.length) {
return dataAll;
}
var locationMap = new Object();
var length = caption.length;
for (i = 0; i < length; i++) {
var data = new Object();
var curDName = dataName[i];
data['caption'] = caption[i];
data['name'] = curDName;
data['type'] = dataType[i];
data[CONST_VALUE] = dataValue[i];
var objLocation = null;
var currentLocationCaption = '';
var isLocationField = false;
var latPattern = /(.+) Latitude(\(.+\))/
var lngPattern = /(.+) Longitude(\(.+\))/
var altPattern = /(.+) Altitude(\(.+\))/
var accPattern = /(.+) Accuracy(\(.+\))/
// Extract location and multi-select
if (curDName.endsWith(' Latitude')) {
isLocationField = true;
curDName = curDName.replace(' Latitude', '');
currentLocationCaption = caption[i].replace(' Latitude', '');
objLocation = updateLocationMapData(curDName, locationMap, dataValue[i], null, null, null);
} else if (curDName.endsWith(' Longitude')) {
isLocationField = true;
curDName = curDName.replace(' Longitude', '');
currentLocationCaption = caption[i].replace(' Longitude', '');
objLocation = updateLocationMapData(curDName, locationMap, null, dataValue[i], null, null);
} else if (curDName.endsWith(' Altitude')) {
isLocationField = true;
curDName = curDName.replace(' Altitude', '');
currentLocationCaption = caption[i].replace(' Altitude', '');
objLocation = updateLocationMapData(curDName, locationMap, null, null, dataValue[i], null);
} else if (curDName.endsWith(' Accuracy')) {
isLocationField = true;
curDName = curDName.replace(' Accuracy', '');
currentLocationCaption = caption[i].replace(' Accuracy', '');
objLocation = updateLocationMapData(curDName, locationMap, null, null, null, dataValue[i]);
} else {
// Process location inside repeat group
if (latPattern.test(curDName) == true) {
isLocationField = true;
curDName = curDName.replace(latPattern, '$1$2');
objLocation = updateLocationMapData(curDName, locationMap, dataValue[i], null, null, null);
} else if (lngPattern.test(curDName) == true) {
isLocationField = true;
curDName = curDName.replace(lngPattern, '$1$2');
objLocation = updateLocationMapData(curDName, locationMap, null, dataValue[i], null, null);
} else if (altPattern.test(curDName) == true) {
isLocationField = true;
curDName = curDName.replace(altPattern, '$1$2');
objLocation = updateLocationMapData(curDName, locationMap, null, null, dataValue[i], null);
} else if (accPattern.test(curDName) == true) {
isLocationField = true;
curDName = curDName.replace(accPattern, '$1$2');
objLocation = updateLocationMapData(curDName, locationMap, null, null, null, dataValue[i]);
}
}
// Process for location field
if (isLocationField == true) {
// Putting location value (with checking data)
if (objLocation != null) {
data['name'] = curDName;
data['type'] = CONST_CTRL_TYPE_INPUTLOCATION;
data['caption'] = currentLocationCaption;
data[CONST_VALUE] = objLocation;
} else {
// Go to the next location properties
continue;
}
}
dataAll.push(data);
}
return dataAll;
}
/**
* Update location map data for printing form record
* If there are enough data lat, lng, alt, acc
*/
function updateLocationMapData(currentDataName, locationMap, lat, lng, alt, acc) {
var objLocation = locationMap[currentDataName];
if (objLocation == undefined || objLocation == null) {
objLocation = new Object();
locationMap[currentDataName] = objLocation;
}
if (lat != undefined && lat != null) {
objLocation['lat'] = lat;
}
if (lng != undefined && lng != null) {
objLocation['lng'] = lng;
}
if (alt != undefined && alt != null) {
objLocation['alt'] = alt;
}
if (acc != undefined && acc != null) {
objLocation['acc'] = acc;
}
// Check data for return
if (objLocation['lat'] != undefined && objLocation['lat'] != null
&& objLocation['lng'] != undefined && objLocation['lng'] != null
&& objLocation['alt'] != undefined && objLocation['alt'] != null
&& objLocation['acc'] != undefined && objLocation['acc'] != null
) {
return objLocation;
}
return null;
}
/**
* Update max-width image for printing
*/
function updateMaxWidthImageForPrinting() {
var pageSetting = glbHashObject['print_page_settings'];
if (pageSetting == undefined || pageSetting == null) {
return;
}
var maxWidthImage = MAX_WIDTH_IMAGE;
// Adjust max width of Signature
var maxWidthSignature = MAX_WIDTH_IMAGE;
if (pageSetting.two_column_format == true) {
// In case of two column
maxWidthSignature = (maxWidthSignature / 2);
}
$('.label_image_item_4signature').css('max-width', maxWidthSignature + 'mm');
// PCA-406: Report Settings
// Ignore Scale image in Standard Report Pdf
// // Adjust max width image with Scale image
// switch (pageSetting.scale_image) {
// case SCALE_IMAGE_VALUE14 : maxWidthImage = maxWidthImage / 4; break;
// case SCALE_IMAGE_VALUE13 : maxWidthImage = maxWidthImage / 3; break;
// case SCALE_IMAGE_VALUE12 : maxWidthImage = maxWidthImage / 2; break;
// case SCALE_IMAGE_VALUE23 : maxWidthImage = (2*maxWidthImage) / 3; break;
// }
var maxWidthRegion = maxWidthImage + 10;
if (pageSetting.two_column_format == true) {
// In case of two column
maxWidthImage = (maxWidthImage / 2);
}
if (browserNameGlobal == 'ie') {
maxWidthRegion = maxWidthImage;
}
var maxWidthIE = 'expression(document.body.clientWidth > (500/12) * parseInt(document.body.currentStyle.fontSize)?"' + maxWidthImage + 'mm":"auto")';
var maxWidthIERegion = 'expression(document.body.clientWidth > (500/12) * parseInt(document.body.currentStyle.fontSize)?"' + maxWidthRegion + 'mm":"auto")';
// Max-width for Firefox, Chrome, Safari, and IE
$('.label_image_item').css('max-width', maxWidthImage + 'mm')
.css('width', maxWidthIE);
$('.image_region').css('max-width', maxWidthRegion + 'mm')
.css('width', maxWidthIERegion);
// Update max width image label
var maxWidthImageLabel = 120;
maxWidthImageLabel = maxWidthImageLabel / 3;
if (pageSetting.two_column_format == true) {
maxWidthImageLabel = (maxWidthImageLabel / 2);
} else {
maxWidthImageLabel = maxWidthImageLabel;
}
$('.right_section_label img').css('max-width', maxWidthImageLabel + 'mm');
if (browserNameGlobal == 'ie') {
// Update max width image label in IE
$('.right_section_label img').each(function() {
$(this).css('width', maxWidthImageLabel + 'mm');
});
}
}
var calculateCenterPointForPrinting = function(_minLat, _minLng, _maxLat, _maxLng, _markerCount, osm_canvas){
// --- calculate center point location
var centerLat = 0;
var difLatFlg = ((_minLat*_maxLat) > 0 ? 1 : -1);
if(difLatFlg > 0){
centerLat = (_minLat + _maxLat)/2;
}
else{
centerLat = (Math.abs(_minLat) + Math.abs(_maxLat))/2 + _minLat;
}
var centerLng = 0;
var difLngFlg = (_minLng*_maxLng > 0 ? 1 : -1);
if(difLngFlg > 0){
centerLng = (_minLng + _maxLng)/2;
}
else{
centerLng = (Math.abs(_minLng) + Math.abs(_maxLng))/2 + _minLng;
}
var centerPoint = new OpenLayers.LonLat(centerLng, centerLat)
.transform(
new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
osm_canvas.getProjectionObject() // to Spherical Mercator Projection
);
return centerPoint;
}
/**
* Create OSM Map Url for getting static image
* Notes : This function is used for IE
*/
function createOsmMapImageUrl(isPrintingFlg) {
// Put static image map
var URL_MAP = "http://pafciu17.dev.openstreetmap.org/?module=map";
var URL_MAP_DEFAULT = 'http://pafciu17.dev.openstreetmap.org/?module=map&lon=180&lat=20&zoom=2&width=970&height=1450';
var MAP_IMAGE_SIZE = "&width=630&height=891"; // <=> 3*A4 with pixel values
//var mapLink = 'http://pafciu17.dev.openstreetmap.org/?module=map&bbox=-20.0,60.0,70.0,-1.0&width=630&height=891&points=10,10%3b17,12%3b50,40%3b-10,30%3b70,25%3b-17,-1.0%3b-10,57%3b-20,60%3b1,1&pointImageUrl=http://localhost:8888/map/img/marker.png';
var printPageMarkers = glbHashObject['print_page_markers'];
var pageSetting = glbHashObject['print_page_settings'];
// Create list of markers
if (printPageMarkers.length <= 0) {
return URL_MAP_DEFAULT;
}
if (pageSetting.show_GPS_coordinates == false) {
return URL_MAP_DEFAULT;
}
var url = new Array();
url.push(URL_MAP);
// Build markers
var markerBuilder = new Array();
var minLat = MAXIMUM_VALUE;
var maxLat = MINIMUM_VALUE;
var minLng = MAXIMUM_VALUE;
var maxLng = MINIMUM_VALUE;
for (var i = 0; i < printPageMarkers.length; i++) {
var lat = printPageMarkers[i].lat;
var lng = printPageMarkers[i].lng;
// Ignore the wrong lat, lng
if (lat == undefined || lat == null || lat == '' || lat == "no-gps") {
continue;
}
if (lng == undefined || lng == null || lng == '' || lng == "no-gps") {
continue;
}
var curLat = new Number(lat);
var curLng = new Number(lng);
if (minLat > curLat) { minLat = curLat; }
if (minLng > curLng) { minLng = curLng; }
if (maxLat < curLat) { maxLat = curLat; }
if (maxLng < curLng) { maxLng = curLng; }
markerBuilder.push(lng + "," + lat);
}
// Validate values (min, max)
if (minLat == MAXIMUM_VALUE
|| maxLat == MINIMUM_VALUE
|| minLng == MAXIMUM_VALUE
|| maxLng == MINIMUM_VALUE
) {
return URL_MAP_DEFAULT;
}
// Validation the bbox value bounds (minLng,maxLat,maxLng,minLat) <=> (-180,85,180,-85)
if (minLng == maxLng) {
minLng--;
maxLng++;
}
if (minLng < -180) {
minLng = -180;
}
if (maxLng > 180) {
maxLng = 180;
}
if (minLat == maxLat) {
minLat--;
maxLat++;
}
if (minLat < -85) {
minLat = -85;
}
if (maxLat > 85) {
maxLat = 85;
}
url.push("&bbox=" + minLng + "," + maxLat + "," + maxLng + "," + minLat);
var markerUrl = glbHashObject['url_server'] + "/map/img/marker.png";
url.push(MAP_IMAGE_SIZE);
url.push("&points=");
url.push(markerBuilder.join("%3b"));
url.push("&pointImageUrl=" + markerUrl);
var mapUrl = url.join('');
// Check the result image for validation
var testImg = new Image();
testImg.src = mapUrl;
testImg.onload = function() { }
var dummyWidth = testImg.width;
var dummyHeight = testImg.height;
if (dummyWidth > 0 && dummyHeight > 0) {
if (dummyWidth <= 250 || dummyHeight <= 250) {
mapUrl = URL_MAP_DEFAULT;
}
}
return mapUrl;
}
/**
* Create static Google Map Image URL
* @param isPrintingFlg The flag for printing mode
*/
function createGoogleMapImageUrl(isPrintingFlg) {
// Put static image map
var URL_MAP = "http://maps.googleapis.com/maps/api/staticmap?temp_param=true";
var URL_MAP_DEFAULT = 'http://maps.googleapis.com/maps/api/staticmap?temp_param=true&zoom=1&size=450x590&sensor=true&scale=2';
var URL_MAP_DEFAULT_PREMIER = 'http://maps.googleapis.com/maps/api/staticmap?temp_param=true&zoom=1&size=630x891&sensor=true&scale=2';
var MAP_IMAGE_SIZE = "&size=450x590&scale=2"; // <=> 3*A4 with pixel values
var MAP_IMAGE_SIZE_PREMIER = "&size=630x891&scale=2"; // <=> 3*A4 with pixel values
var printPageMarkers = glbHashObject['print_page_markers'];
var pageSetting = glbHashObject['print_page_settings'];
var isPremierGoogleAccount = glbHashObject['is_premier_google_account'];
// Create list of markers
if (printPageMarkers.length <= 0) {
if (isPremierGoogleAccount == true) {
return URL_MAP_DEFAULT_PREMIER;
}
return URL_MAP_DEFAULT;
}
if (pageSetting.show_GPS_coordinates == false) {
if (isPremierGoogleAccount == true) {
return URL_MAP_DEFAULT_PREMIER;
}
return URL_MAP_DEFAULT;
}
var url = new Array();
url.push(URL_MAP);
// Build markers
var markerBuilder = new Array();
var minLat = MAXIMUM_VALUE;
var maxLat = MINIMUM_VALUE;
var minLng = MAXIMUM_VALUE;
var maxLng = MINIMUM_VALUE;
var markerCount = 0;
for (var i = 0; i < printPageMarkers.length; i++) {
var lat = printPageMarkers[i].lat;
var lng = printPageMarkers[i].lng;
// Ignore the wrong lat, lng
if (lat == undefined || lat == null || lat == '' || lat == "no-gps") {
continue;
}
if (lng == undefined || lng == null || lng == '' || lng == "no-gps") {
continue;
}
var curLat = new Number(lat);
var curLng = new Number(lng);
if (minLat > curLat) { minLat = curLat; }
if (minLng > curLng) { minLng = curLng; }
if (maxLat < curLat) { maxLat = curLat; }
if (maxLng < curLng) { maxLng = curLng; }
markerBuilder.push(lat + "," + lng);
markerCount++;
}
// Validate values (min, max)
if (minLat == MAXIMUM_VALUE
|| maxLat == MINIMUM_VALUE
|| minLng == MAXIMUM_VALUE
|| maxLng == MINIMUM_VALUE
) {
if (isPremierGoogleAccount == true) {
return URL_MAP_DEFAULT_PREMIER;
}
return URL_MAP_DEFAULT;
}
// Validation the bbox value bounds (minLng,maxLat,maxLng,minLat) <=> (-180,85,180,-85)
if (minLng == maxLng) {
minLng--;
maxLng++;
}
if (minLng < -180) {
minLng = -180;
}
if (maxLng > 180) {
maxLng = 180;
}
if (minLat == maxLat) {
minLat--;
maxLat++;
}
if (minLat < -85) {
minLat = -85;
}
if (maxLat > 85) {
maxLat = 85;
}
// Calculate the center value
if (pageSetting.auto_scale == true) {
// TODO: Zoom to maximum value in case of 1 marker
if (markerCount == 1) {
url.push('&zoom=' + DEFAULT_ZOOM_FOR_ONE_MARKER);
}
}
else {
// Apply for manual scale
var customZoom = pageSetting.enter_scale_value;
if (customZoom != undefined && customZoom != null && customZoom != '') {
customZoom = parseInt(customZoom);
var centerLat = (minLat + maxLat) / 2;
var centerLng = (minLng + maxLng) / 2;
//url.push('¢er=' + centerLat + ',' + centerLng);
// Plus the zoom down to 1 unit because Static GoogleMap is larger than OSM Map (with zoom lower than 12)
// if (customZoom <= 12) {
// customZoom = customZoom - 1;
// }
url.push('&zoom=' + customZoom);
}
}
var markerUrl = glbHashObject['url_server'] + "/map/img/marker.png";
if (glbHashObject['url_server'].indexOf('http://localhost:8888') >= 0) {
// TODO: Using temporatory marker from Online Network
markerUrl = CONST_DOFORMS_URL + '/map/img/marker.png';
}
if (isPremierGoogleAccount == true) {
url.push(MAP_IMAGE_SIZE_PREMIER);
} else {
url.push(MAP_IMAGE_SIZE);
}
if (markerBuilder.length > 0) {
url.push('&markers=icon:');
url.push(markerUrl + '|');
glbHashObject['image_marker_builder'] = markerBuilder.join("|");
url.push(glbHashObject['image_marker_builder']);
} else {
glbHashObject['image_marker_builder'] = null;
}
// The sensor parameter is required
url.push("&sensor=true");
var mapUrl = url.join('');
// Check the result image for validation
var testImg = new Image();
testImg.src = mapUrl;
testImg.onload = function() { }
var dummyWidth = testImg.width;
var dummyHeight = testImg.height;
if (dummyWidth == 0 || dummyHeight == 0) {
//mapUrl = URL_MAP_DEFAULT;
} else if (dummyWidth > 0 && dummyHeight > 0) {
if (dummyWidth <= 250 || dummyHeight <= 250) {
if (isPremierGoogleAccount == true) {
mapUrl = URL_MAP_DEFAULT_PREMIER;
} else {
mapUrl = URL_MAP_DEFAULT;
}
}
}
return mapUrl;
}
/**
* Create hyperlink on static image Map
*/
function createHyperlinkOnStaticMap() {
// Put hyperlink into static map
var result = new Array();
var htmlMapUrl = glbHashObject['url_server'] + '/dataview/mapview?1=1';
result.push(htmlMapUrl);
var pageSetting = glbHashObject['print_page_settings'];
// Scale mode, scale value
result.push('&auto_scale=' + pageSetting.auto_scale);
result.push('&enter_scale_value=' + pageSetting.enter_scale_value);
// Create markerBuilder
var markerBuilder = new Array();
var printPageMarkers = glbHashObject['print_page_markers'];
for (var i = 0; i < printPageMarkers.length; i++) {
var lat = printPageMarkers[i].lat;
var lng = printPageMarkers[i].lng;
// Ignore the wrong lat, lng
if (lat == undefined || lat == null || lat == '' || lat == "no-gps") {
continue;
}
if (lng == undefined || lng == null || lng == '' || lng == "no-gps") {
continue;
}
markerBuilder.push(lat + "," + lng);
}
if (markerBuilder.length > 0) {
result.push('&markers=' + markerBuilder.join('|'));
}
// Put current status of logo
var response = glbHashObject['response_object'];
if (response.is_custom_logo != undefined && response.is_custom_logo != null) {
result.push('&is_custom_logo=' + response.is_custom_logo);
}
if (response.customer_key != undefined && response.customer_key != null) {
result.push('&customer_key=' + response.customer_key);
}
// Create content url
$('#map_canvas').off('click');
$('#map_canvas').on('click', function() {
// Open new window
window.open(result.join(''));
});
}
/**
* Show map and markers data
*/
function showMapAndMarkers(isPrintingFlg) {
var printPageMarkers = glbHashObject['print_page_markers'];
if (printPageMarkers == undefined || printPageMarkers == null) {
return false;
}
// Clear and re-draw the open street map
var pageSetting = glbHashObject['print_page_settings'];
if (pageSetting === undefined || pageSetting === null) {
return false;
}
// Do not show map in case of setting show GPS is false
if (pageSetting.show_GPS_coordinates === false) {
return;
}
// Do not show map in case of there's no markers
if (printPageMarkers.length <= 0) {
return;
}
// --- re-initialize map canvas
var osm_canvas = {};
$('#map_canvas').empty();
$('.map_canvas_wrapper').css('height', '240mm');
// --- initialize map structure
//if (browserNameGlobal == 'ie')
if (browserNameGlobal != null)
{
// Put static image map
var mapUrl = createGoogleMapImageUrl(isPrintingFlg);
var width = $('.map_canvas_wrapper').width();
var height = $('.map_canvas_wrapper').height();
if (isPrintingFlg != undefined && isPrintingFlg != null && isPrintingFlg == true)
{
if (browserNameGlobal == 'ie') {
$('.map_canvas_wrapper').css('height', '205mm');
width = $('#temp_IEMap_Size_Printing').width();
height = $('#temp_IEMap_Size_Printing').height();
} else if (browserNameGlobal == 'chrome') {
$('.map_canvas_wrapper').css('height', '205mm');
width = $('#temp_ChromeMap_Size_Printing').width();
height = $('#temp_ChromeMap_Size_Printing').height();
} else if (browserNameGlobal == 'safari') {
$('.map_canvas_wrapper').css('height', '192mm');
width = $('#temp_SafariMap_Size_Printing').width();
height = $('#temp_SafariMap_Size_Printing').height();
}
else if (browserNameGlobal == 'firefox') {
$('.map_canvas_wrapper').css('height', '220mm');
height = $('#temp_FirefoxMap_SizePrinting').height();
}
}
var resultImg = '';
$('#map_canvas').html(resultImg);
}
// show / hide html relating html controls
$('#map_canvas').show();
return true;
}
/**
* Check if the coordinate is valid or not
*/
function isValidCoordinate(lat, lng) {
var numWrong = 0;
// The lat is in range [-90,90]
var latVal = new Number(lat);
if (latVal < -90 || latVal > 90) {
numWrong++;
}
// The lng is in range [-180,180]
var lngVal = new Number(lng);
if (lngVal < -180 || lngVal > 180) {
numWrong++;
}
if (numWrong >= 1) {
return false;
}
return true;
}
/**
* Create OSM Marker for printing
*/
function createPrintMarker(_location) {
var size = new OpenLayers.Size(21,25);
var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
var icon = new OpenLayers.Icon('../map/img/marker.png', size, offset);
var marker = new OpenLayers.Marker(_location, icon.clone());
return marker;
}
/**
* Apply page break into document
*/
function applyPageBreak(hasExistMap, numberOfMarkers, functionFinishAll) {
var pageSetting = glbHashObject['print_page_settings'];
if (pageSetting == undefined || pageSetting == null) {
return;
}
glbHashObject['times_waiting_images']++;
// Check if all the image has been loaded
if (hasAllImageLoaded() == false) {
// Apply page break into table blocks (after 1s for loading all image complete)
// setTimeout('applyPageBreak(#hasExistMap#, #numberOfMarkers#);'
// .replace('#hasExistMap#', hasExistMap)
// .replace('#numberOfMarkers#', numberOfMarkers)
// , 1000);
setTimeout(function() {
applyPageBreak(hasExistMap, numberOfMarkers, functionFinishAll);
}, 1000);
return;
}
// Sorting data into page table
var listBlock = null;
if (pageSetting.two_column_format === false) {
// Process in one column format
listBlock = $('.table_one_column_dummy').children();
for (var i = 0; i < listBlock.length; i++) {
var jQueryBlock = $(listBlock[i]);
putBlockIntoPage_OneCol_PageBreak(jQueryBlock);
}
// Remove the table dummy
$('.table_one_column_dummy').remove();
// Remove float and clear style in table one column
$('.table_one_column').removeClass('show_float_and_clear_table');
} else {
// Process in two column format
listBlock = $('.block_data_unit');
for (var i = 0; i < listBlock.length; i++) {
var jQueryBlock = $(listBlock[i]);
putBlockIntoPage_TwoCol_PageBreak(jQueryBlock);
}
// Remove the table dummy
$('.table_two_column_dummy').remove();
// Remove float and clear style in table two column
$('.table_two_column').removeClass('show_float_and_clear_table');
}
// Setting special width for Chrome, Safari
if (browserNameGlobal == 'chrome' || browserNameGlobal == 'safari') {
$('.table_two_column td.left_col').addClass('left_col_safari');
$('.table_two_column td.right_col').addClass('right_col_safari');
}
// Process [PageNumber] for the last page
var lastTableInPrintingData = null;
if (pageSetting.two_column_format === true) {
lastTableInPrintingData = $('.table_two_column').last();
} else {
lastTableInPrintingData = $('.table_one_column').last();
}
// Show page numbers and dash-line for breaking pages (checking case exist/no exists GPS)
if (hasExistMap === true && pageSetting.show_GPS_coordinates === true && numberOfMarkers > 0) {
createPageNumber4PrintPage(lastTableInPrintingData, true);
// Create page number for location map
var osmMapRegion = $('#osm_map_region');
createPageNumber4PrintPage(osmMapRegion, false);
} else {
// Show page number in normal cases
// (Including check blank pages (page with empty labels)
if (false === applyRemoveBlankPageWithEmptyLabelQuestions(lastTableInPrintingData)) {
createPageNumber4PrintPage(lastTableInPrintingData, false);
} else {
// Remove the last dot separate between pages
$('.dash_line_for_separating_between_pages:last').remove();
}
//createPageNumber4PrintPage(lastTableInPrintingData, false);
}
try{ // CO-3794
if(pageSetting.display_page_numbers_total === true){
$('.page_number_for_printview_html').each(function() {
var name = $(this).attr('name');
if(name != undefined){
$(this).html('Page ' + name.replace('Page','') + ' of ' + (pageNumber4PrintPreviewCounter-1));
}
});
}
} catch(e){ }
waitForDataLoading(false);
// Apply function functionFinishAll, if exists
if (typeof functionFinishAll !== 'undefined' && functionFinishAll !== null) {
writeToLogInfoRequired('Execute the functionFinishAll ...');
functionFinishAll.call(this);
}
$('.label_image_item.showPicturesFitToPage').css('max-width', '165mm').css('max-height', '100%'); // CO-4014
callFormLoadedEvents();
}
/**
* Get window size (width x Height)
*
* @return the height of window
*/
function detectWindowSize()
{
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' )
{
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
}
else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) )
{
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
}
else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) )
{
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
return new Object({"width": myWidth, "height": myHeight});
}
/**
* Get A4 page size in height
*/
function getA4Height() {
if (DOCUMENT_A4_HEIGHT == null) {
DOCUMENT_A4_HEIGHT = $('#temp_region_A4').show().height();
$('#temp_region_A4').hide();
}
return DOCUMENT_A4_HEIGHT;
}
function getBrowserInfo(){
var ie = false;
var browserName = "";
var ua = navigator.userAgent.toLowerCase();
if ( ua.indexOf( "opera" ) != -1 ) {
browserName = "opera";
} else if ( ua.indexOf( "msie" ) != -1 || ua.indexOf('trident/') != -1 || ua.indexOf( "edg/" ) != -1) {
// Fix error print WebApps with IE 10, IE 11
browserName = "ie";
ie = true;
} else if ( ua.indexOf( "chrome" ) != -1 ) {
// The chrome checking must have put before safari checking
browserName = "chrome";
} else if ( ua.indexOf( "safari" ) != -1 ) {
browserName = "safari";
} else if ( ua.indexOf( "mozilla" ) != -1 ) {
if ( ua.indexOf( "firefox" ) != -1 ) {
browserName = "firefox";
} else {
browserName = "mozilla";
}
}
return browserName;
}
/**
* Check if the DIV is overflow
*/
function isOverflow(jQueryDiv) {
return (jQueryDiv[0].scrollHeight > jQueryDiv[0].offsetHeight);
}
/**
* Apply word wrap (in case of two column format)
*/
function processWordWrapForPrinting() {
var pageSetting = glbHashObject['print_page_settings'];
if (pageSetting == undefined || pageSetting == null) {
return;
}
var maxWidthContent = MAX_WIDTH_CONTENT;
if (pageSetting.two_column_format == true) {
maxWidthContent = (maxWidthContent / 2) - 4;
}
// Setting max-width for general question (in mm)
$('.general_question').css('max-width', maxWidthContent + 'mm');
// Fix bug 0025790: IE11 - PDF report - Grid - Caption text of Widgets overlap
// // For IE
// if (browserNameGlobal == 'ie') {
// $('.general_question').css('width', maxWidthContent + 'mm');
// }
}
/**
* Helper function
*/
function getDisplayHeader(orgHeader, isLocation) {
if (orgHeader == undefined || orgHeader == null || orgHeader == '') {
return orgHeader;
}
var pageSetting = glbHashObject['print_page_settings'];
if (pageSetting == undefined || pageSetting == null) {
return orgHeader;
}
var displayHeader = orgHeader;
// Process the end character :
if (isLocation != undefined && isLocation != null && isLocation == true
&& pageSetting.show_GPS_coordinates == true) {
displayHeader = getCleanHeader(orgHeader) + " (see attached map): ";
// PCA-245: Embed static maps into PDF/Excel Template
if (isVersion(VERSION_EMBBED_STATIC_MAP_PDF_EXCEL)) {
displayHeader = getCleanHeader(orgHeader);
}
} else {
if (false == isEndWithCharacter(orgHeader)) {
displayHeader = orgHeader + ": ";
}
}
return displayHeader.replace(/ /g, ' ');
}
/**
* Helper function using in getDisplayHeader()
* @param orgHeader
*/
function isEndWithCharacter(orgHeader) {
if (/.+:\s*$/.test(orgHeader) == true) {
return true;
}
return false;
}
/**
* Helper function using in getDisplayHeader()
* @param orgHeader
*/
function getCleanHeader(orgHeader) {
return orgHeader.replace(/(.+):\s*$/, "$1");
}
function resizeMapcanvasWrapper() {
if (browserNameGlobal == 'ie') {
$('.map_canvas_wrapper').css('width', '170mm');
} else if (browserNameGlobal == 'chrome') {
$('.map_canvas_wrapper').css('width', '151mm');
$('.map_canvas_wrapper').css('height', '235mm');
$('.map_region_title').css('width', '164.6mm');
} else if (browserNameGlobal == 'firefox') {
$('.map_canvas_wrapper').css('width', '170mm');
} else if (browserNameGlobal == 'safari') {
// Process browser of Chrome and Safari
$('.map_canvas_wrapper').css('width', '165mm');
}
}
/**
* Processing save file (the same as Download file)
*/
function saveFileContent(extension) {
// The task info key (only used in Backends)
var taskInfoKey = getQuerystring('taskInfoKey');
var token = getQuerystring('token');
if (taskInfoKey !== undefined && taskInfoKey !== '') {
// Using in backends
processSaveFileInBackends(taskInfoKey, undefined, undefined, token);
return;
}
var formId = "";
var linkDownload = glbHashObject['url_server'] + '/dataview/sendMail?download=true';
// Fix bug 0022726: PDF-Excel Report and Print Preview - Duplicate file when save file from 2 record different
var cacheId = $('#PrintDataObject_cachedId_value').val();
linkDownload += '&cacheId=' + cacheId;
switch (extension) {
case '.pdf' :
// Save in format PDF (the same as Email PDF)
// http://localhost:8888/dataview/sendMail
linkDownload += '&type=pdf';
break;
}
linkDownload += '&formId=' + glbHashObject['response_object'].formId;
// Check if IE environment
if (browserNameGlobal === 'ie') {
linkDownload += '&is_IE_request=true';
}
// Show waiting dialog until 3 seconds
waitForDataLoading(true);
setTimeout(function() {
waitForDataLoading(false);
}
, 3000);
// Redirect into download page (using iframe)
$('#savePDF_iFrameContent').attr('src', linkDownload);
}
/**
* Process layout 2 column (in vertical and zigzac)
* @param listBlocks The list of blocks data
*/
function processLayout2ColumnVertical(listBlocks, strCenter) {
var mainTable = new Array();
var leftTable = new Array();
var rightTable = new Array();
var strStart = '
';
var strEnd = '
';
var isLeftColumn = true;
// Process adding data into left, right table
for (var i = 0; i < listBlocks.length; i++) {
var block = listBlocks[i];
if (isLeftColumn == true) {
leftTable.push(strStart + block + strEnd);
} else {
rightTable.push(strStart + block + strEnd);
}
isLeftColumn = !isLeftColumn;
}
mainTable.push('
');
mainTable.push('
' + leftTable.join('') + '
');
mainTable.push(strCenter);
mainTable.push('
' + rightTable.join('') + '
');
mainTable.push('
');
return mainTable;
}
/**
* Put the block into page
* @param block The block content
* @param isTwoColumn The flag of two column mode
*/
function putBlockIntoPage(block, isTwoColumn, isForcePageBreak, dataObject) {
var jQueryBlock = $(block);
// Assign a special class for identify the current block
jQueryBlock.addClass('block_data_unit');
jQueryBlock.addClass('spacing_general_4pdf_margin_top');
jQueryBlock.addClass('spacing_general_4pdf_margin_bottom');
// Put forcePageBreak flag
if (isForcePageBreak === true) {
// Add page break into current question for processing later
jQueryBlock.addClass('force_page_break');
}
// PCA-406: Report Settings [] show buttons and check boxes in PDF same as PDF
// Add page break based on required data
if (dataObject.force_page_break === true) {
jQueryBlock.addClass('force_page_break');
}
// Apply Justification for all controls
if (isVersion(VERSION_TOOL_NEW_JUSTIFICATION)) {
// Caption
var jtfClassC = getJustificationClassOfPrint(dataObject.justificationCaption);
if (jtfClassC !== '') {
jQueryBlock.find('p.header_title').addClass(jtfClassC);
}
// Hints
var jtfClassH = getJustificationClassOfPrint(dataObject.justificationHint);
if (jtfClassH !== '') {
jQueryBlock.find('p.hint_title').addClass(jtfClassH);
}
// Answer
var jtfClassA = getJustificationClassOfPrint(dataObject.justificationAnswer, true);
if (jtfClassA !== '') {
// For Text Plain
jQueryBlock.find('div.general_content').addClass(jtfClassA);
}
}
// For the one column case
if (isTwoColumn == false) {
putBlockIntoPage_OneCol(jQueryBlock);
} else {
putBlockIntoPage_TwoCol(jQueryBlock);
}
// PCA-219: Print Preview/PDF support for Remove space options
if (typeof dataObject !== 'undefined' && dataObject !== null) {
var removeSpaceAbove = false;
var type = '';
if (dataObject.type !== undefined) { type = dataObject.type; }
if (dataObject['removeSpaceAbove'] === true) {
removeSpaceAbove = true;
}
if (removeSpaceAbove === true) {
// Special treating with Label
//if (type !== 'inputLabel')
{
jQueryBlock.addClass('removeSpaceAbove_TOP');
}
jQueryBlock.removeClass('spacing_general_4pdf_margin_top');
}
var removeSpaceBelow = false;
if (dataObject['removeSpaceBelow'] === true) {
removeSpaceBelow = true;
}
if (removeSpaceBelow === true) {
//if (type !== 'inputLabel')
{
jQueryBlock.addClass('removeSpaceBelow_BOTTOM');
}
jQueryBlock.removeClass('spacing_general_4pdf_margin_bottom');
}
// Process Answer Color for PrintPreview/Standard PDF
if (isVersion(VERSION_ANSWER_COLOR)) {
// Only limit specified type for answer color
if (CONTROL_APPLY_ANSWER_COLOR_GUI_PREVIEW_PDF.indexOf(type + ',') >= 0
&& type !== '') {
if (dataObject['appearance'] === LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_APPEARANCE_CUSTOM) {
if (dataObject['isAnswerColor']) {
if (browserNameGlobal == 'firefox' && dataObject['answerColor'].toLowerCase() == '#ffffff') {
jQueryBlock.find('.general_content').css('color', 'rgba(0, 0, 0, 0)').css('text-shadow', '0 0 0 #fff');
}else{
jQueryBlock.find('.general_content').css('color', dataObject['answerColor']);
}
}
} else {
// Use global answer color
if (glbBuildFormSettingsWA.isAnswerColor) {
if (browserNameGlobal == 'firefox' && glbBuildFormSettingsWA.answerColor.toLowerCase() == '#ffffff') {
jQueryBlock.find('.general_content').css('color', 'rgba(0, 0, 0, 0)').css('text-shadow', '0 0 0 #fff');
}else{
jQueryBlock.find('.general_content').css('color', glbBuildFormSettingsWA.answerColor);
}
}
}
}
}
}
}
/**
* Process block in case of 1 column
* @param {} jQueryBlock
* @returns {}
*/
function putBlockIntoPage_OneCol(jQueryBlock) {
// Get last block for putting data
var lastTable = $('.table_one_column_dummy');
if (lastTable.length <= 0) {
// Add new table (only once)
lastTable = $('.table_one_column_template').clone();
lastTable.removeClass('table_one_column_template');
lastTable.addClass('table_one_column');
lastTable.addClass('table_one_column_dummy');
lastTable.appendTo($('#PrintRegionData'));
}
// Put the jQueryBlock into last table
jQueryBlock.appendTo(lastTable);
}
//The number of items inside Last Table (mode One Page)
var numberItemsInsideLastTableInOnePage = 0;
var numberEmptyLabelsInsideLastTableInOnePage = 0;
/**
* Process putting block into apply page break mode
* @param jQueryBlock The block content in jquery object
*/
function putBlockIntoPage_OneCol_PageBreak(jQueryBlock) {
// Get last block for putting data (before the dummy table)
var lastTable = $('.table_one_column_dummy').prev('.table_one_column');
if (lastTable.length <= 0) {
// Add new table
lastTable = $('.table_one_column_template').clone();
lastTable.removeClass('table_one_column_template');
lastTable.addClass('table_one_column');
// Insert the last table before the dummy table
$('.table_one_column_dummy').before(lastTable);
}
// Save the current table height for using later
var lastTableHeight = calculateHeight(lastTable);
lastTable.addClass('show_float_and_clear_table');
jQueryBlock.appendTo(lastTable);
var tableHeight = calculateHeight(lastTable);
// Plus the height of top content into the first table content
if ($('.table_one_column').length == 2) {
// Include the height of top data
var topHeight = lastTable.position().top - 100;
if (browserNameGlobal == 'firefox') {
topHeight = lastTable.position().top - 50;
} else if (browserNameGlobal == 'chrome') {
topHeight = lastTable.position().top - 50;
} else if (browserNameGlobal == 'safari') {
topHeight = lastTable.position().top - 50;
} else if (browserNameGlobal == 'ie') {
topHeight = lastTable.position().top - 50;
}
tableHeight = tableHeight + topHeight;
}
// Process custom page break (Page Break Question/Page break loop question)
var isForcePageBreak = false;
if (jQueryBlock.hasClass('force_page_break')) {
isForcePageBreak = true;
}
// Make page break when height is over limit one page or isForcePageBreak == true)
if (tableHeight > DOCUMENT_HEIGHT || isForcePageBreak === true) {
// Move the current block into the next table
var nextTable = $('.table_one_column_template').clone();
nextTable.removeClass('table_one_column_template');
nextTable.addClass('table_one_column');
//nextTable.addClass('page_break_print');
// Insert the last table before the dummy table
$('.table_one_column_dummy').before(nextTable);
// Move the current content from lastTable into the next table
jQueryBlock.appendTo(nextTable);
// Put page number, include dash-line
//createPageNumber4PrintPage(lastTable, true);
// Check if we need remove the blank pages (only empty label with no shading or transparent shadding)\
if (false === applyRemoveBlankPageWithEmptyLabelQuestions(lastTable)) {
createPageNumber4PrintPage(lastTable, true);
}
// Apply page break for the first item
if (browserNameGlobal == 'ie' || browserNameGlobal == 'chrome' || browserNameGlobal == 'safari') {
//nextTable.addClass('page_break_print');
nextTable.before('');
} else {
// Affected in firefox
//jQueryBlock.addClass('page_break_print');
nextTable.before('');
}
nextTable.addClass('show_float_and_clear_table');
}
// Check the block of empty label total (empty header/hint/image + empty shading)
numberItemsInsideLastTableInOnePage++;
if (jQueryBlock.hasClass('isEmptyLabelTotal')) {
numberEmptyLabelsInsideLastTableInOnePage++;
}
}
/**
* Put block into page (2 col mode)
* @param {} jQueryBlock
* @returns {}
*/
function putBlockIntoPage_TwoCol(jQueryBlock) {
// Get last block for putting data
var lastTable = $('.table_two_column_dummy');
if (lastTable.length <= 0) {
// Add new table (only once)
lastTable = $('.table_two_column_template').clone();
lastTable.removeClass('table_two_column_template');
lastTable.addClass('table_two_column');
lastTable.addClass('table_two_column_dummy');
lastTable.appendTo($('#PrintRegionData'));
}
var currentCol = lastTable.find('.left_col');
jQueryBlock.appendTo(currentCol);
}
/**
* Put the block content into 2 column structure
* @param jQueryBlock
*/
function putBlockIntoPage_TwoCol_PageBreak(jQueryBlock) {
// Get last block for putting data (before the dummy table)
var lastTable = $('.table_two_column_dummy').prev('.table_two_column');
if (lastTable.length <= 0) {
// Add new table
lastTable = $('.table_two_column_template').clone();
lastTable.removeClass('table_two_column_template');
lastTable.addClass('table_two_column');
// Insert the last table before the dummy table
$('.table_two_column_dummy').before(lastTable);
}
putBlockIntoTableTwoCol(jQueryBlock, lastTable)
lastTable.addClass('show_float_and_clear_table');
var tableHeight = calculateHeightTwoCol(lastTable);
// Plus the height of top content into the first table content
if ($('.table_two_column').length == 2) {
// Include the height of top data
var topHeight = lastTable.position().top - 100;
if (browserNameGlobal == 'firefox') {
topHeight = lastTable.position().top - 50;
} else if (browserNameGlobal == 'chrome') {
topHeight = lastTable.position().top - 50;
} else if (browserNameGlobal == 'safari') {
topHeight = lastTable.position().top - 50;
} else if (browserNameGlobal == 'ie') {
topHeight = lastTable.position().top - 50;
}
tableHeight = tableHeight + topHeight;
}
// Process custom page break (Page Break Question/Page break loop question)
var isForcePageBreak = false;
if (jQueryBlock.hasClass('force_page_break')) {
isForcePageBreak = true;
}
if (tableHeight > DOCUMENT_HEIGHT || isForcePageBreak === true) {
// Put page number, include dash-line for breaking pages
createPageNumber4PrintPage(lastTable, true);
// Move the current block into the next table
var nextTable = $('.table_two_column_template').clone();
nextTable.removeClass('table_two_column_template');
nextTable.addClass('table_two_column');
// Add page break for printing in HTML
//nextTable.addClass('page_break_print');
nextTable.before('');
// Insert the last table before the dummy table
$('.table_two_column_dummy').before(nextTable);
// Reset the position of first control (From LEFT)
glbHashObject['put_block_left_status'] = true;
// Move the current content from lastTable into the next table
putBlockIntoTableTwoCol(jQueryBlock, nextTable);
nextTable.addClass('show_float_and_clear_table');
}
// Inverse the current position of block (left or right)
glbHashObject['put_block_left_status'] = !glbHashObject['put_block_left_status'];
}
/**
* Calculate the height of table
* @param jQueryTable
* @returns The height of total of children component in table
*/
function calculateHeight(jQueryTable) {
return jQueryTable.height();
// var listBlocks = jQueryTable.children();
// var height = 0;
// for (i = 0; i < listBlocks.length; i++) {
// height += $(listBlocks[i]).height();
// }
// return height;
}
/**
* Apply printing after timeout 1s
*/
function restoreGUITimeout() {
// Restore the current width
$('#PrintRegionData').addClass('PrintRegionData_Original');
$('#PrintRegionData').removeClass('PrintRegionData4Safari');
$('#PrintRegionData').removeClass('PrintRegionData4Chrome');
// Apply default width for osm_map_region (in printing status)
$('#osm_map_region').addClass('osm_map_region_print');
// Show all dash-line for breaking pages (previous hide for printing)
$('.dash_line_for_separating_between_pages').show();
$('.page_number_for_printview_html').show();
// Show the line header
$('#idLineFormatHeaderPrintPreview').removeClass('hideLineFormatHeader');
// Modify the GPS map
showMapAndMarkers();
callFormLoadedEvents();
}
/**
* Put a specified block into the table in 2 column mode
* @param jQueryBlock The block content in jquery object
* @param lastTable The wrapper table
*/
function putBlockIntoTableTwoCol(jQueryBlock, lastTable) {
// Check if we can put the current block into the current table
var currentCol = null;
if (glbHashObject['put_block_left_status'] == true) {
// Put the left block
currentCol = lastTable.find('.left_col');
} else {
// Put the right block
currentCol = lastTable.find('.right_col');
}
jQueryBlock.appendTo(currentCol);
}
/**
* Calculate the height of the specified table (in 2 column mode)
* @param lastTable
*/
function calculateHeightTwoCol(lastTable) {
return lastTable.height();
// Return the maximum height between left col and right col
/* var leftBlocks = lastTable.find('.left_col .block_data_unit');
var rightBlocks = lastTable.find('.right_col .block_data_unit');
var leftHeight = 0;
var rightHeight = 0;
for (var i = 0; i < leftBlocks.length; i++) {
leftHeight += $(leftBlocks[i]).height();
}
for (var i = 0; i < rightBlocks.length; i++) {
rightHeight += $(rightBlocks[i]).height();
}
return Math.max(leftHeight, rightHeight);
*/
}
/**
* Create a jquery page break
*/
function createJQueryPageBreak() {
var pageBreakCnt = '';
return $(pageBreakCnt);
}
/**
* Update document height
*/
function updateDocumentHeight() {
// The default for 2 columns
// Get A4 document height
DOCUMENT_HEIGHT = $('#document_height_A4').height();
// Get the document height in safari
var browserInfo = getBrowserInfo();
if (browserInfo === 'safari') {
DOCUMENT_HEIGHT = $('#document_height_A4_Safari').height();
} else if (browserInfo == 'chrome') {
DOCUMENT_HEIGHT = $('#document_height_A4_Chrome').height();
}
var response = glbHashObject['response_object'];
if (response === undefined || response === null) {
return;
}
var pageSetting = response.page_settings;
if (pageSetting === undefined || pageSetting == null) {
return;
}
if (pageSetting.two_column_format === false) {
if (browserInfo == 'firefox') {
DOCUMENT_HEIGHT = $('#document_height_A4_OneCol').height();
} else if (browserInfo == 'chrome') {
DOCUMENT_HEIGHT = $('#document_height_A4_OneCol_Chrome').height();
} else if (browserInfo == 'safari') {
DOCUMENT_HEIGHT = $('#document_height_A4_OneCol_Safari').height();
}
}
// // Update document height based on []Show page numbers
// if (pageSetting.display_page_numbers === true) {
// // Decrease document height
// DOCUMENT_HEIGHT -= 50;
// }
}
/**
* Check if all of the image has been loaded
*/
function hasAllImageLoaded() {
writeToLogInfoRequired('Total process images : ' + glbHashObject['total_process_images'] + ' >> Number of all images : ' + glbHashObject['number_of_images']);
if (glbHashObject['total_process_images'] >= glbHashObject['number_of_images']) {
return true;
}
// Special processing when wait long image (about 3')
if (glbHashObject['times_waiting_images'] > 180) {
// When the remain images < 5 => all finish
var remainImages = glbHashObject['number_of_images'] - glbHashObject['total_process_images'];
writeToLogInfoRequired('Time waiting image > 180s : ' + glbHashObject['times_waiting_images'] + ' >> remain images : ' + remainImages);
if (remainImages < 3) {
return true;
}
}
// Special processing when wait long image (about 5')
if (glbHashObject['times_waiting_images'] > 300) {
return true;
}
return false;
}
/**
* Put event for checking load progress of images
*/
function putEventForImages() {
// Unbind all of previous events
$("img").off('load').off('error');
// Reset the image value
glbHashObject['number_of_images'] = $('img:not([src=""])').length;
glbHashObject['total_process_images'] = 0;
glbHashObject['times_waiting_images'] = 0;
$("img").load(function() {
glbHashObject['total_process_images']++;
})
.error(function() {
glbHashObject['total_process_images']++; writeToLogInfo('Image loaded FAIL ... Image of ' + glbHashObject['total_process_images']);
});
}
/**
* Process Excel Report page content
* @returns {}
*/
function processExcelReport(response) {
// Copy all code from function processHTMLPrintFormRecord with header contents
var htmlData = new Array();
htmlData.push('
');
// Adding logo, Form Title, Header Block (Record Name, Mobile Device Number, Date Created)
// if (response.page_settings.display_logo == true) {
// var logoTemplate = '
'
.replace('#msg_info_excel_template_gui_preview#', msg_info_excel_template_gui_preview)
);
// Process Image compression ratio (Will be deleted later)
// htmlData.push('
Image compression ratio :
');
// Put header data into print region
$('#PrintRegionData').append(htmlData.join(''));
// Hide all menu related to PDF Report feature
//$('.btnPrint_Submit, .btnPrint_Email').hide();
}
/**
* Process data for TableScore, includes
* + Remove questions inside TableScore and put back to tableScoreMappingData
* + Insert placeholder data object mapping with TableScores
* (This function has been ripped from function PrintUtils.processTableScoreDataAll() )
* @returns {}
*/
var TABLE_SCORE_CHILD_INDEX = 'table_score_child_index';
var TABLE_SCORE_DATA_NAME = 'table_score_data_name';
var TABLE_SCORE_CAPTION_NAME = 'table_score_caption_name';
var TABLE_SCORE_COMMENT_NAME = 'table_score_comment_name';
function processTableScoreDataAll(dataAll, tableScoreMappingData, pageSetting) {
try {
var result = new Array();
// There is no table score blocks.
if (tableScoreMappingData['~hasExistTableScore~'] !== true) {
return dataAll;
}
var isDisplayDataName = false;
if (pageSetting !== undefined && pageSetting['display_data_name'] !== undefined) {
isDisplayDataName = pageSetting['display_data_name'];
}
var browseTableNames = new Array();
for (var i = 0; i < dataAll.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[CONST_VALUE] === undefined) { data[CONST_VALUE] = ''; }
var name = data['name'];
// Put comment value of field inside Score Card
if (name.endsWith('__comment')) {
var fieldInsideScoreCard = name.replace(/__comment$/, '');
var child = tableScoreMappingData[fieldInsideScoreCard + ''];
if (child !== undefined) {
// Put comment into current child
child[TABLE_SCORE_COMMENT_NAME] = data[CONST_VALUE];
}
continue;
}
// Check the current data is inside a TableScore or not.
var child = tableScoreMappingData[name + ''];
if (child !== undefined) {
// Transfer current data into resultMap
var value = "";
if (data[CONST_VALUE] !== undefined && data[CONST_VALUE] !== null) {
value = data[CONST_VALUE];
}
// Update value to EMPTY in current child
if (value === '') {
child[CONST_VALUE] = '';
} else {
// Update value for preventing error of ScoreCard value
if (child[CONST_VALUE] === undefined || child[CONST_VALUE] === null || child[CONST_VALUE] === '') {
if (value instanceof Array) {
child[CONST_VALUE] = value.join('<br>');
} else {
child[CONST_VALUE] = value;
}
}
}
var tableName = child[TABLE_SCORE_DATA_NAME];
// Add table name into current data (for the first question)
if (child[TABLE_SCORE_CHILD_INDEX] === 0
|| browseTableNames.indexOf(tableName) < 0) {
var tableScoreObject = new Object();
tableScoreObject['name'] = tableName;
tableScoreObject['type'] = CONST_CTRL_TYPE_CTRLSCORETABLE;
tableScoreObject['hints'] = '';
// Setting header based on current PageSettings
if (isDisplayDataName === true) {
tableScoreObject['header'] = tableName;
} else {
// Display caption
tableScoreObject['header'] = child[TABLE_SCORE_CAPTION_NAME];
}
// Tag the current table has been extracted to final result data
browseTableNames.push(tableName);
tableScoreObject[CONST_VALUE] = '';
// Apply information about current appearance
// PCA-266 Print Preview/PDF support for color option in Grids, questionnaires and Tables
// appearance, isShadeHeadings, headingColor, textColor
if (isVersion(VERSION_GRID_TYPE_FUNCTION)) {
// Extract appearance information from tableScoreMappingData into new object
// Transfer appearance information
if (tableScoreMappingData[tableName + '~AppearanceInfoInScoreCard~'] !== undefined) {
var currentAppearance = tableScoreMappingData[tableName + '~AppearanceInfoInScoreCard~'];
// appearance
if (currentAppearance.appearance !== undefined) {
tableScoreObject.appearance = currentAppearance.appearance;
}
// isShadeHeadings
if (currentAppearance.isShadeHeadings !== undefined) {
tableScoreObject.isShadeHeadings = currentAppearance.isShadeHeadings;
}
// headingColor
if (currentAppearance.headingColor !== undefined) {
tableScoreObject.headingColor = currentAppearance.headingColor;
}
// isBorderAroundHeading
if (currentAppearance.isBorderAroundHeading !== undefined) {
tableScoreObject.isBorderAroundHeading = currentAppearance.isBorderAroundHeading;
}
// textColor
if (currentAppearance.textColor !== undefined) {
tableScoreObject.textColor = currentAppearance.textColor;
}
// activeTextColor
if (currentAppearance.activeTextColor !== undefined) {
tableScoreObject.activeTextColor = currentAppearance.activeTextColor;
}
// PCA-266: Print PreviewPDF support for color option in Grids, questionnaires and Tables
// isShadedRow
if (currentAppearance.isShadedRow !== undefined) {
tableScoreObject.isShadedRow = currentAppearance.isShadedRow;
}
// rowColor
if (currentAppearance.rowColor !== undefined) {
tableScoreObject.rowColor = currentAppearance.rowColor;
}
// rowTextColor
if (currentAppearance.rowTextColor !== undefined) {
tableScoreObject.rowTextColor = currentAppearance.rowTextColor;
}
// PCA-219: Print Preview/PDF support for Remove space options
// removeSpaceAbove
if (currentAppearance.removeSpaceAbove !== undefined) {
tableScoreObject.removeSpaceAbove = currentAppearance.removeSpaceAbove;
}
// removeSpaceBelow
if (currentAppearance.removeSpaceBelow !== undefined) {
tableScoreObject.removeSpaceBelow = currentAppearance.removeSpaceBelow;
}
}
// PCA-174 (PDF/Excel Reports support for New Grid Type)
// Get other information about columnsSpaceType, withFormat4ColumnWeight
if (tableScoreMappingData[tableName + '~ControlStructureInSC~'] !== undefined) {
var controlStruct = tableScoreMappingData[tableName + '~ControlStructureInSC~'];
if (controlStruct.columnsSpaceType !== undefined) {
tableScoreObject.columnsSpaceType = controlStruct.columnsSpaceType;
}
if (controlStruct.withFormat4ColumnWeight2 !== undefined) {
var wF4ColW2 = controlStruct.withFormat4ColumnWeight2;
// Question
if (wF4ColW2.withFormat4CWQuestion !== undefined) {
tableScoreObject.withFormat4CWQuestion = wF4ColW2.withFormat4CWQuestion;
}
// Answer
if (wF4ColW2.withFormat4CWAnswer !== undefined) {
tableScoreObject.withFormat4CWAnswer = wF4ColW2.withFormat4CWAnswer;
}
// Comment
if (wF4ColW2.withFormat4CWComment !== undefined) {
tableScoreObject.withFormat4CWComment = wF4ColW2.withFormat4CWComment;
}
}
// []Append comment
if (controlStruct.appendComment !== undefined) {
tableScoreObject.appendComment = controlStruct.appendComment;
}
// PCA-174 (PDF/Excel Reports support for New Grid Type)
// Fix undefined error
if (controlStruct.withFormat4ColumnWeight2 !== undefined) {
var withFormat4ColumnWeight = wF4ColW2.withFormat4CWQuestion;
// Parse number value based on answer value
var numOptions = child.options.length;
if (numOptions <= 1) {
withFormat4ColumnWeight += '|' + wF4ColW2.withFormat4CWAnswer;
} else {
var itemPercent = parseFloat(wF4ColW2.withFormat4CWAnswer) / numOptions;
for (t = 0; t < numOptions; t++) {
withFormat4ColumnWeight += '|' + itemPercent;
}
}
// Check if we are using []Append comment
if (controlStruct.appendComment == true) {
withFormat4ColumnWeight += '|' + wF4ColW2.withFormat4CWComment;
}
tableScoreObject.withFormat4ColumnWeight = withFormat4ColumnWeight;
}
}
}
result.push(tableScoreObject);
}
continue;
}
// Adding current data into final list
result.push(data);
}
return result;
} catch (ex) {
writeToLogInfo('Exception in processTableScoreDataAll() : ' + ex);
}
}
/**
* Replace tag <br> into LINE FEED in HTML
* We are in HTML encode, so we will get the direct character <br>
* @param {} inputText
* @returns {}
*/
function replaceTagBR2LineFeed(inputText) {
if (inputText === undefined || inputText === null) { return ''; }
if (inputText !== '') {
// Convert to string type
inputText = inputText.toString();
inputText = inputText.replace(/<[Bb][Rr]\s*\/?>/ig, " ");
inputText = inputText.replace(/<[Bb][Rr]\s*\/?>/ig, " ");
// Save all line feeds
inputText = inputText.replace(/ /ig, "[[\nLINE_FEED\n]]");
// Unwrap HTML tags
inputText = unwrapHTMLTags(inputText);
// Restore line feeds
inputText = inputText.replace(/\[\[\nLINE_FEED\n\]\]/ig, " ");
// Make default \n into
inputText = inputText.replace(/\n/ig, " ");
// 0025711: Label/Text Calculation display not good on pdf if having special chars
/*
// Replace special characters $, &
inputText = inputText.replace(/&/g, "&");
inputText = inputText.replace(/\$/g, "$");
*/
}
return inputText;
}
/**
* Replace tag <br> into LINE FEED in HTML (only for Label)
* We are in HTML encode, so we will get the direct character <br>
* @param {} inputText
* @returns {}
*/
function replaceTagBR2LineFeed4Label(inputText) {
if (inputText === undefined || inputText === null) { return ''; }
if (inputText !== '') {
inputText = inputText.replace(/<[Bb][Rr]\s*\/?>/ig, " ");
inputText = inputText.replace(/<[Bb][Rr]\s*\/?>/ig, " ");
// 0025711: Label/Text Calculation display not good on pdf if having special chars
/*
// Replace special characters $, &
inputText = inputText.replace(/&/g, "&");
inputText = inputText.replace(/\$/g, "$");
*/
}
return inputText;
}
/**
* Process unwrap HTML tags
* @param {} inputText
* @returns {}
*/
function unwrapHTMLTags(inputText) {
//do {
// Replace until there no tag inside
inputText = inputText.replace(/<(\w*).*?>(.*?)<\/\s*(\1)>/ig, '$2');
//inputText = inputText.replace(/<(\w*)\s*\/>/ig, '$2');
inputText = inputText.replace(/<.*?\/?>/ig, '');
//} while (true);
try {
// Try to extract text value
return $('
' + inputText + '
').text();
} catch (e) { }
// Replace all tag as
return inputText;
}
/**
* Parse Common HTML tags
* @param {} inputText
* @returns {}
*/
function parseCommonHTMLTags4Header(inputText) {
var result = inputText;
if (result !== '') {
// Replace common HTML tags
// . Black Black
// . Blue Blue
// . Cyan Cyan
// . Gray Gray
// . Green Green
// . Magenta Magenta
// . Orange Orange
// . Pink Pink
// . Red Red
// . White White
// . Yellow Yellow
result = result.replace(/<font color=("|')(black|blue|cyan|gray|green|magenta|orange|pink|red|white|yellow)("|')>(.+?)<\/font>/ig, '$4');
}
return result;
}
/**
* Get original data name by remove all Group Tail (...)
* @param {} dataName
* @returns {}
*/
function getOriginalDataName(dataName) {
return dataName.replace(/(.+?)\(.*/g, '$1');
}
/**
* Process show page number for print page
* @param {} lastTable
* @param {} tableHeight
* @param {} isShowPageNumber
* @returns {}
*/
var pageNumber4PrintPreviewCounter = 1;
function createPageNumber4PrintPage(lastTable, isIncludeDashLine) {
var pageSetting = glbHashObject['print_page_settings'];
var pageNumber = $('');
if (pageSetting.display_page_numbers === true
|| pageSetting.display_page_numbers_total === true) { // CO-3794
pageNumber.text('Page ' + pageNumber4PrintPreviewCounter);
}
// Insert a after last content table data
pageNumber.insertAfter(lastTable);
// Increase page number
pageNumber4PrintPreviewCounter++;
// Add a dash-line, if needed
if (isIncludeDashLine === true) {
var dashLine = $('');
// Insert after the page number content
dashLine.insertAfter(pageNumber);
}
}
/**
* Enable writing log information in JavaScript by setting isNeedWriteLogInfoValueFlg4JavaScript = true
* in HttpSession server
* @returns {}
*/
function enableShowLogInfoInJavaScript() {
try {
// Fix bug 0022726: PDF-Excel Report and Print Preview - Duplicate file when save file from 2 record different
// Get cacheId from current request
var cacheId = getQuerystring('cacheId');
// Getting isNeedWriteLogInfoValueFlg from server session
$.ajax({
url : '/pagesettings',
dataType : 'json',
type : 'POST',
data : {
action : 'set_isNeedWriteLogInfoValueFlg'
// Fix bug 0022726: PDF-Excel Report and Print Preview - Duplicate file when save file from 2 record different
,cacheId : cacheId
},
cache : false,
success : function(response, status) {
// Do nothing
}
});
} catch (e) {}
}
/**
* Execute file JavaScript dynamically
* @param {} jsFilePath
* @returns {}
*/
function loadJavaScriptDynamic(jsFilePath) {
$.getScript(jsFilePath, function(data, textStatus){
console.log(textStatus, data);
// do whatever you want
});
}
/**
* Format number using currency with format ,
* example $12345678.0034
* => $12,543,678.0034
* @returns {}
*/
function formatNumberValue4Currency(value, currency, type, dataName) {
//writeToLogInfo('Process formatNumberValue4Currency : ' + value + ' >> currency : ' + currency + ' >> type : ' + type + ' >> dataName : ' + dataName);
if (value === undefined || value === '') { return ''; }
//if (currency === undefined || currency === '') { return value; }
// Fix bug 0022362: Calculation, number > 1000 display wrong on report - see attach file
// The data has been formatted
if (value.indexOf(',') >= 0) {
return (currency + value);
}
// Validate number value
if (value.indexOf(':') >= 0 || value.indexOf('/') >= 0) { return (currency + value); }
var indexDot = value.indexOf('.');
// Fix bug 0018791: Calculation widget - Result of calculation is not the same on Web app, View data and PDF report
// Special treating with Calculation and using Currency, we will split into 6 digits for Decimal value.
if (indexDot >= 0 && type === CONST_CTRL_TYPE_INPUTCALCULATE && currency !== ''
&& value.length - indexDot > 6) {
// We have to modify the value of Calculation
try {
var newValue = parseFloat(value);
newValue = newValue.toFixed(6);
value = newValue + '';
} catch (e) {}
}
if (indexDot < 0) {
indexDot = value.length - 1;
} else {
indexDot = indexDot - 1;
}
var builder = new Array();
var count = 0;
for (i = indexDot; i >= 0; i--) {
builder.push(value[i]);
count++;
if (count === 3 && i > 0) {
// Break loop in case of i == 1 and value[0] is equal -
if (i === 1 && value[0] === '-') {
builder.push(value[0]);
break;
}
builder.push(',');
count = 0;
}
}
// Reverse string
var strProcess = builder.reverse().join('');
if (value.indexOf('.') >= 0) {
value = strProcess + value.substring(indexDot+1, value.length);
}
else {
value = strProcess;
}
// Special treating with Decimal value, Decimal Calculation,....
var checkIndexDot = value.indexOf('.');
if (type === 'Decimal'
|| checkIndexDot >= 0
|| listAllDecimalFields.indexOf(dataName) >= 0
) {
var numAddZero = 0;
if (checkIndexDot < 0) {
numAddZero = 2;
} else {
if (value.length - checkIndexDot === 2) {
numAddZero = 1;
}
}
// Special treating with calculation number
// Fix bug 0023755: Report - Calculation Number using currency displays wrong format
// => Don't add .0 or .00 after calculation values
if (type === CONST_CTRL_TYPE_INPUTCALCULATE || '' == currency) {
numAddZero = 0;
}
// Process add zero
if (numAddZero === 2) {
value += '.00';
} else if (numAddZero === 1){
value += '0';
}
}
// TODO: We need format number as rule (maximum 6 numbers)
// NumberFormat numberFormat = new java.text.DecimalFormat("#,###,##0.00####");
// value = numberFormat.format(value);
if (value.indexOf('.') > 0) {
// Get maximum 6 numbers
var builderNew = new Array();
var countAfterDot = 0;
var isAfterDot = false;
for (var i = 0; i < value.length; i++) {
var currentChar = value[i];
if (isAfterDot) {
countAfterDot++;
}
if (countAfterDot > 6) {
break;
}
builderNew.push(currentChar);
if ('.' === currentChar) {
isAfterDot = true;
}
}
value = builderNew.join('');
// Fix bug 0022362: Calculation, number > 1000 display wrong on report - see attach file
while (value.indexOf(',,') >= 0) {
value = value.replace(',,', ',');
}
}
return (currency + value);
}
/**
* Process format value of Decimal number in case of NO CURRENCY
* @param value
* @param type
* @param dataName
*/
function formatDecimalNumberWithoutCurrency(value, data, dataName) {
if (value === '') {
return value;
}
var type = data['type'];
var strResult = value;
var isDecimalField = false;
if (type === 'Decimal') {
isDecimalField = true;
} else if (listAllDecimalFields.indexOf(dataName) >= 0) {
// Special treating with Calculation
if (type === CONST_CTRL_TYPE_INPUTCALCULATE) {
// Check if the calculation has format []Percent
// Special treating with Percent value
var isPercentCalc = false;
if (strResult.indexOf('%') === strResult.length - 1) {
strResult = strResult.replace('%', '');
isPercentCalc = true;
}
// Format number for Calculation
try {
// Fix bug 0021690: Suggestion - on Report: Should apply the adding comma signal for thousandths of Calculation field without using currency symbol
var splitValues = strResult.split("\.");
var intValue = splitValues[0];
var dotValue = '';
if (splitValues.length > 1) {
dotValue = splitValues[1];
}
strResult = accounting.formatNumber(intValue, null, null);
if (typeof dotValue !== 'undefined' && dotValue !== '') {
strResult += '.' + dotValue;
}
// CO-2429: PDF Report does not display negative numbers
if(intValue.indexOf('-') == 0 // negative number
&& strResult.indexOf('-') != 0){ // CO-4516
strResult = '-' + strResult;
}
if(false == data['isShowComma']){
strResult = strResult.replace(/,/g, '');
}
} catch (e) {
writeToLogInfo('Exception when format number : ' + e.toString());
}
// Check if the calculation has format []Percent
if (isPercentCalc) {
strResult = strResult + '%';
}
} else {
isDecimalField = true;
}
} else if (type === CONST_CTRL_TYPE_INPUTCALCULATE) {
// Fix bug 0023342: Calculation DateTime displays wrong format in report
// Special treating with Calculation Date/Time
return formatCalculationDateTimeValue(value, type, dataName);
}
if (true === isDecimalField && strResult.indexOf('.') < 0) {
strResult += '.0';
}
return strResult;
}
/**
* Process format calculation Date/Time with thousand separator (commas)
*
* @param value
* @param type
* @param dataName
*/
function formatCalculationDateTimeValue(value, type, dataName) {
if (value === '') {
return value;
}
var strResult = value;
// Special treating with Calculation
if (type === CONST_CTRL_TYPE_INPUTCALCULATE) {
// Format number for Calculation
try {
// Check if the current value is a number or not
// Fix bug 0023736: Email PDF Report - Don't show comma signal (,) for thousandths of Calculation value >= 1000
if (strResult.match(/^\s*-?\s*[\d,\.]+$/)) {
writeToLogInfo('IsNumber TRUE :: ' + strResult);
// Fix bug 0021690: Suggestion - on Report: Should apply the adding comma signal for thousandths of Calculation field without using currency symbol
// Fix bug 0023342: Calculation DateTime displays wrong format in report
var splitValues = strResult.split("\.");
var intValue = splitValues[0];
var dotValue = '';
if (splitValues.length > 1) {
dotValue = splitValues[1];
}
strResult = accounting.formatNumber(intValue, null, null);
if (typeof dotValue !== 'undefined' && dotValue !== '') {
strResult += '.' + dotValue;
}
}
} catch (e) {
writeToLogInfo('Exception when format number : ' + e.toString());
}
}
return strResult;
}
/**
* The error message defined in PRUtils.java
*/
// Unknown
var ERR_MSG_PR_UNKNOWN = "ErrorMessagePRUnknown";
// Can't create StandardPDF
var ERR_MSG_PR_CANT_CREATE_STD_PDF = "CantCreateStandardPdf";
// Not found Excel Template (may be deleted)
var ERR_MSG_PR_EXL_TPL_NOT_FOUND = "ExcelTemplateNotFound";
// Create create Excel Result (2003/2007)
var ERR_MSG_PR_CANT_CREATE_EXCEL = "CantCreateExcelResult";
// Over 10MB Excel Template in case of converting pdf
var ERR_MSG_PR_EXL_TPL_OVER10MB = "ExcelTemplateOver10MB_ConvertPdf";
// Convert PDF : Upload fail (to server Aspose.Cloud)
var ERR_MSG_PR_CNV_PDF_UPLOAD_FAIL = "ConvertPdfUploadFail";
// Convert PDF : Save into PDF fail from Excel Template (in server Aspose.Cloud)
var ERR_MSG_PR_CNV_PDF_SAVE_PDF_FAIL = "ConvertPdfSavePdfFail";
// Convert PDF : Download PDF fail from server Aspose.Cloud
var ERR_MSG_PR_CNV_PDF_DOWNLOAD_FAIL = "ConvertPdfDownloadFail";
var ERR_MSG_PR_CNV_PDF_GENERAL_ERROR = "ConvertPdfGeneralError";
/**
* Process showing PrintReport error message (in Backends)
* @param errorMessage
*/
function showPrintReportInBackendsErrorMsg(errorMessage) {
if (errorMessage === undefined || errorMessage === null) {
jAlert(msg_unknown_error);
return;
}
var msg = msg_unknown_error;
switch (errorMessage) {
// case ERR_MSG_PR_CANT_CREATE_STD_PDF :
// msg = msg_pr_backend_cant_create_std_pdf;
// break;
case ERR_MSG_PR_EXL_TPL_NOT_FOUND :
msg = msg_pr_backend_cant_create_excel_tmpl_notfound;
break;
// case ERR_MSG_PR_CANT_CREATE_EXCEL :
// msg = msg_pr_backend_cant_create_excel;
// break;
case ERR_MSG_PR_EXL_TPL_OVER10MB :
case ERR_MSG_PR_CNV_PDF_UPLOAD_FAIL :
msg = msg_error_convert_excel2pdf_upload_fail;
break;
case ERR_MSG_PR_CNV_PDF_SAVE_PDF_FAIL :
case ERR_MSG_PR_CNV_PDF_GENERAL_ERROR :
msg = msg_error_convert_excel2pdf;
break;
default :
msg = msg_print_report_fail_need_to_resize_image;
break;
}
// Show error message
jAlert(msg);
}
/**
* Process save pdf/excel/convert pdf in Backends
*/
function processSaveFileInBackends(previewTaskInfoKey, isExcelTemplate, isClickMenuPdf, token) {
// Put process save file to servlet : PrintRPHandlerServle.java
waitForDataLoading(true);
// Check dummy processing ExcelTemplate
$.ajax({
url : '/PrintRPHandlerServlet',
dataType : 'json',
type : 'POST',
headers: {
"Authorization": "Bearer " + token
},
data : {
action : 'save_file'
,taskInfoKey : previewTaskInfoKey
,isClickMenuPdf : isClickMenuPdf
,isExcelTemplate : isExcelTemplate
},
cache : false,
complete: function() {
//waitForDataLoading(false);
},
success : function(response, status) {
setTimeout('processCheckingFileAndDownloadInBE("' + response.taskInfoKey + '", "' + token + '")'
, WAITING_TIME_BETWEEN_CHECKING);
},error : function() {
jAlert(msg_unknown_error);
waitForDataLoading(false);
}
});
}
/**
* Process check finish progress and download file (Excel/PDF/Convert PDF)
* @param taskInfoKey
*/
function processCheckingFileAndDownloadInBE(taskInfoKey, token) {
waitForDataLoading(true);
// Check dummy processing ExcelTemplate
$.ajax({
url : '/PrintRPHandlerServlet',
dataType : 'json',
type : 'POST',
headers: {
"Authorization": "Bearer " + token
},
data : {
action : 'check_finish_task'
,taskInfoKey : taskInfoKey
},
cache : false,
complete: function() {
},
success : function(response, status) {
// Check result download
if (response.isFinish === true) {
waitForDataLoading(false);
// Get link download.
// Redirect into download page (using iframe)
//var linkDownload = glbHashObject['url_server'] + response.downloadLink;
var linkDownload = response.downloadLink;
if (linkDownload.indexOf('http://') === 0
|| linkDownload.indexOf('https://') === 0) {
// Link of Aspose's PDF
// => DO NOTHING
} else {
linkDownload = glbHashObject['url_server'] + linkDownload;
}
writeToLogInfoRequired('Link download : ' + linkDownload);
// Check if the task okie or not
if (response.isErrorTaskInfo === true) {
// Error occur, we will show error information
writeToLogInfoRequired('Error in PRTaskInfo : ' + response.errorMessage);
showPrintReportInBackendsErrorMsg(response.errorMessage);
return;
}
// Process download
$('#savePDF_iFrameContent').attr('src', linkDownload);
if(response.taskChilds) {
for(var i = 0; i < response.taskChilds.length; i++) {
setTimeout(function() {
$('#savePDF_iFrameContent').parent().append($('#savePDF_iFrameContent').clone()
.attr('id','').attr('src', response.taskChilds[i].downloadLink));
}, 3000 * i);
}
}
return;
}
// Loop process checking finish task and download file
setTimeout('processCheckingFileAndDownloadInBE("' + taskInfoKey + '", "' + token + '")'
, WAITING_TIME_BETWEEN_CHECKING);
},error : function() {
jAlert(msg_unknown_error);
waitForDataLoading(false);
}
});
}
/**
* Return if we want use Backends in Print Report
* (get value from server Utils.isUsingBackends4PR()
*/
function isUsingBackends4PR() {
// Call AJAX to get flag value from server
return glbHashObject['isUsingBackends4PR'];
}
/**
* Get all HTML of specified control instead of $(control).html()
*/
function getAllControlHTMLWrapperWebSite(objControl) {
var resultHTML = jQuery('').append(objControl).html();
return resultHTML;
}
// The header template 4 label in Grid
var GENERAL_HEADER_TEMPLATE_4_LABEL_IN_GRID = '
#header#
';
/**
* Create general block content
*/
function createLabelBlockInGridPreview(header, hint, dataObject) {
var block = new Array();
var dataName = '';
if (typeof dataObject !== 'undefined' && dataObject !== null) {
dataName = dataObject.name;
}
block.push('
'.replace('#data_name#', dataName));
if (header !== '') {
// Apply Justification for all controls
var strHeaderC = GENERAL_HEADER_TEMPLATE_4_LABEL_IN_GRID.replace('#header#', header);
//block.push(GENERAL_HEADER_TEMPLATE_4_LABEL_IN_GRID.replace('#header#', header));
if (isVersion(VERSION_TOOL_NEW_JUSTIFICATION)) {
// Caption
var jtfClassC = getJustificationClassOfPrint(dataObject.justificationCaption);
if (jtfClassC !== '') {
strHeaderC = strHeaderC.replace('#align_header_class#', jtfClassC);
}
}
block.push(strHeaderC);
}
if (hint !== '') {
// Apply Justification for all controls
var strHints = '';
if(hint.indexOf('http') != -1){
strHints = GENERAL_HINT_IMG_TEMPLATE.replace(/#content#/g, hint); // CO-3332: show image label
} else{
strHints = GENERAL_HINT_TEMPLATE.replace('#hint#', hint);
}
if (isVersion(VERSION_TOOL_NEW_JUSTIFICATION)) {
// Caption
var jtfClassH = getJustificationClassOfPrint(dataObject.justificationHint);
if (jtfClassH !== '') {
strHints = strHints.replace('#align_hint_class#', jtfClassH);
}
}
block.push(strHints);
}
// Special cases with empty header + empty hints
if (header === '' && hint === '') {
block.push(GENERAL_HEADER_TEMPLATE_4_LABEL_IN_GRID.replace('#header#', ' '));
}
block.push('
');
return block.join('');
}
/**
* Special treating apply cell data of Label in Grid
* sample cellValue as :
* @param cellValue
*/
function applyControl4LabelInGridCellPdf(cellValue, dataObject, pageSetting) {
// Validate input value
try {
if (cellValue === '') {
return cellValue;
}
var objCell = $(cellValue);
// Remove bold style
objCell.css('font-weight', 'normal');
// Create Header/Hints
var header = '';
if (dataObject['Caption'] !== undefined && dataObject['Caption'] !== null) {
header = dataObject['Caption'];
}
var hints = '';
// Process show hints based on Report Settings
if (pageSetting.display_hints === true) {
if (dataObject['hint'] !== undefined && dataObject['hint'] !== null) {
var objHint = dataObject['hint'];
if (objHint.eng !== undefined && objHint.eng !== null) {
hints = objHint.eng;
}
}
// CO-3332
if(hints == '' && dataObject['hintLink']){
hints = dataObject['hintLink'];
}
}
var content = createLabelBlockInGridPreview(header, hints, dataObject);
// CO-4458, CO-4463
/*if (dataObject !== 'undefined'
&& dataObject !== null
&& dataObject.name == 'EMPTY$$dummy4Grid') {
objCell.css('display','none');
}*/
// Setting HTML for current cell
objCell.html(content);
cellValue = getAllControlHTMLWrapperWebSite(objCell);
return cellValue;
} catch (e) {
//writeToLogInfo('ERROR ::: ' + e);
}
return cellValue;
}
/**
* Process apply shading for table container (FixedTable/Questionnaire)
*/
function applyShading4TableContainerInPW($table, dataObject) {
//writeToLogInfo('current dataObject : ' + JSON.stringify(dataObject));
// Remove shading rows (with row index 2 or later)
var listRows = $table.find('tr.invoice_table_row_highlight:nth-child(n+2)');
var shadedKind = '';
if (dataObject._tableContainerShadeKind !== undefined && dataObject._tableContainerShadeKind !== null) {
shadedKind = dataObject._tableContainerShadeKind;
}
var isShadedRow = false;
if (dataObject.appearance === LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_APPEARANCE_CUSTOM) {
// Custom apearance
if (dataObject.isShadedRow == true) {
isShadedRow = true;
}
} else {
// Shade rows (build forms)
if (glbBuildFormSettingsWA.isShadedRow === true) {
isShadedRow = true;
}
// // Fwd: Questionnaire (9/2/2015 9:22 PM)
// // Special treating with old form
// // Always apply with isShadedRow == true
// isShadedRow = true;
}
// Check if the current form is new form for using Shading + Border
// With old form for using SHADING + BORDER, we will apply default shading
if (glbBuildFormSettingsWA.isNewForm4UsingShading === false) {
// Always apply with isShadedRow == true with old forms
isShadedRow = true;
}
// Special treating with table
switch(shadedKind) {
case TABLE_CONSTANTS_VALUE_OPTION_BF_TOP_ROW_ONLY :
case TABLE_CONSTANTS_VALUE_OPTION_BF_FIRST_COL_ONLY :
case TABLE_CONSTANTS_VALUE_OPTION_BF_EVERY_OTHER_COL :
isShadedRow = false;
break;
}
if (isShadedRow == false) {
listRows.removeClass('invoice_table_row_highlight');
}
else {
// Process Answer Color for PrintPreview/Standard PDF
// Remove color of AnswerColor in shading rows
var listRowsHighlight = $table.find('tr.invoice_table_row_highlight:nth-child(n+1)');
// CO-332: Add Caption Text Color in Table for Print Preview & Standard PDF reports
//listRowsHighlight.find('span.content_answer_color').removeAttr('style');
}
}
/**
* Process apply shading for table container (FixedTable/Questionnaire)
*/
function applyShading4TableContainerInPW4ColumnFormat($table, shadedKind) {
var shadingClass = '';
var normalClass = '';
// Remove shading rows
$table.find('tr').removeClass('invoice_table_row_highlight');
// Apply class based on table's config
switch (shadedKind) {
case TABLE_CONSTANTS_VALUE_OPTION_BF_TOP_ROW_ONLY :
// Only add the top row
$table.find('tr:first')
.addClass('invoice_table_row_highlight')
// CO-332: Add Caption Text Color in Table for Print Preview & Standard PDF reports
// Remove color of AnswerColor in cell style
//.find('span.content_answer_color').removeAttr('style')
;
// // Special treating with Grid
// if (ctrlType === CONST_CTRL_TYPE_CTRLGRID) {
// $table.find('tr:eq(1)').addClass('oddRow');
// }
break;
case TABLE_CONSTANTS_VALUE_OPTION_BF_FIRST_COL_ONLY :
//co-2969
//$table.find('tr:first').find('th').css('background', '#FFF'); // white
$table.find('tr:first').find('th').addClass('backgroundShading4Container');
// The shading row color will be overwrite the answer color
// Only add the first column
$table.find('tr').find('td:first')
.addClass('invoice_table_row_highlight')
// Remove color of AnswerColor in cell style
// CO-332: Add Caption Text Color in Table for Print Preview & Standard PDF reports
//.find('span.content_answer_color').removeAttr('style')
;
break;
case TABLE_CONSTANTS_VALUE_OPTION_BF_EVERY_OTHER_COL :
//co-2969
//$table.find('tr:first').find('th').css('background', '#FFF'); // white
$table.find('tr:first').find('th').addClass('backgroundShading4Container');
// Add other columns
$table.find('tr').find('td:even,th:even')
.addClass('invoice_table_row_highlight')
// Remove color of AnswerColor in cell style
// CO-332: Add Caption Text Color in Table for Print Preview & Standard PDF reports
//.find('span.content_answer_color').removeAttr('style')
;
break;
}
}
// The global value, only used for Appearance Option in every controls
// PCA-266 Print Preview/PDF support for color option in Grids, questionnaires and Tables
var indexOfAppearanceShadingHeadings = 0;
var builderAppearanceShadingHeadings = new Array();
/**
* Process apply appearance (custom CSS for every controls)
*/
function applyAppearance4ShadingHeadingsPDF(dataObject) {
// Check if we need use the custom appearance
if (dataObject.appearance !== LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_APPEARANCE_CUSTOM) {
return '';
}
// Check shading headings + shading rows
// if (dataObject.isShadeHeadings !== true && dataObject.isShadedRow !== true) {
// return CONTROL_APPEARANCE_NO_SHADING_CHECKBOX;
// }
// Return the unique class CSS
indexOfAppearanceShadingHeadings++;
var customClass = 'customAppearance_' + indexOfAppearanceShadingHeadings;
// Get selected template for current controls
var dataType = '';
if (dataObject.type !== undefined) {
dataType = dataObject.type;
}
var customClassInfo = ' /* Undefined class */ ';
var templateData = '';
// Select the templates
switch (dataType) {
case CONST_CTRL_TYPE_CTRLTABLE :
case CONST_CTRL_TYPE_CTRLGRID :
case CONST_CTRL_TYPE_CTRLSCORETABLE :
templateData = TEMPLATE_SHADE_HEADINGS_PDF_CONTAINER;
break;
}
if (templateData !== '') {
customClassInfo += templateData;
customClassInfo = customClassInfo.replace(/#class_name#/g, customClass);
// Apply shade headings
if (dataObject.isShadeHeadings === true) {
customClassInfo = customClassInfo
.replace(/#background#/g, dataObject.headingColor);
if (browserNameGlobal == 'firefox' && dataObject.textColor.toLowerCase() == '#ffffff') {
var tmp = 'rgba(0, 0, 0, 0) !important; text-shadow: 0 0 0 #fff';
customClassInfo = customClassInfo.replace(/#color#/g, tmp);
}else{
customClassInfo = customClassInfo.replace(/#color#/g, dataObject.textColor);
}
if(dataObject.activeTextColor != undefined){
if (browserNameGlobal == 'firefox' && dataObject.activeTextColor.toLowerCase() == '#ffffff') {
var tmp = 'rgba(0, 0, 0, 0) !important; text-shadow: 0 0 0 #fff';
customClassInfo = customClassInfo.replace(/#active_text_color#/g, tmp);
}else{
customClassInfo = customClassInfo.replace(/#active_text_color#/g, dataObject.activeTextColor);
}
}
// // PCA-393: PDF/Print - Apply changes regarding border option
// if (dataObject.isBorderAroundHeading === false) {
// customClass += ' noBorderSpecial ';
//
// customClassInfo = customClassInfo
// .replace(/#border_color#/g, dataObject.headingColor);
// }
} else {
// Clear background
customClassInfo = customClassInfo
.replace(/#background#/g, CONST_VALUE_INITIAL);
}
// PCA-393: PDF/Print - Apply changes regarding border option
if (dataObject.isBorderAroundHeading === false) {
customClass += ' noBorderSpecial ';
// PCA-393: PDF/Print - Apply changes regarding border option
if (dataObject.isShadeHeadings === true) {
customClassInfo = customClassInfo
.replace(/#border_color#/g, dataObject.headingColor);
} else {
customClassInfo = customClassInfo
.replace(/#border_color#/g, 'transparent');
}
}
// Apply the shade rows
if (dataObject.isShadedRow === true) {
customClassInfo = customClassInfo
.replace(/#background_shade_row#/g, dataObject.rowColor)
.replace(/#color_text_row#/g, dataObject.rowTextColor);
} else {
customClassInfo = customClassInfo
.replace(/#background_shade_row#/g, 'transparent');
}
}
// Put custom class into specified region (more important)
//$('#customStyleAppearance4ShadingControlBackground4PDF').append(customClassInfo);
builderAppearanceShadingHeadings.push(customClassInfo);
return customClass;
}
/**
* Process apply appearance in final action (custom CSS)
*/
function applyAppearance4ShadingHeadingsPDFLastAction() {
// Setting result CSS into #customStyleAppearance4ShadingControlBackground4PDF
if (isVersion(VERSION_SHADINGS_BUTTON_FOR_PDF)) {
var finalAppearance = builderAppearanceShadingHeadings.join("\n\n");
$('#customStyleAppearance4ShadingControlBackground4PDF').html(finalAppearance);
// PCA-299: PDF/Print Preview support for Down/Across option for ChooseOne, SelectMultiple & Score
for (var t = 0; t < listSelectControlsNeedRefreshInPDF.length; t++) {
var itemActPDF = listSelectControlsNeedRefreshInPDF[t];
//if (itemActPDF.type === CONST_CTRL_TYPE_INPUTSELECTMANY)
if (itemActPDF.type === CONST_CTRL_TYPE_INPUTSELECTMANY
|| itemActPDF.type === CONST_CTRL_TYPE_INPUTSELECTONE
|| itemActPDF.type === CONST_CTRL_TYPE_INPUTSCOREONE)
{
var objBlock = itemActPDF.block;
processRecalculateLayoutAcrossOfSelectItems(objBlock);
}
}
}
}
/**
* PCA-174 (PDF/Excel Reports support for New Grid Type)
* Helper function for processing the custom width from Build From config
*
* @param dataObject
*/
function processColumnWidth4ContainerPDF(dataObject
, arrColWidthPercent
, arrColWidthMillis
, totalWidth
, numTableColumns) {
// // Init the width array in millimet (outside)
// var arrColWidthPercent = new Array();
// var arrColWidthMillis = new Array();
var colCountWidth = 0;
var colCount = 0;
var colCountWidthPer = 0;
if(dataObject.columnsSpaceType === CONTAINER_COLUMN_SPACE_TYPE_EQUALLY_SPACE_COLUMNS){
if(dataObject.fixedTableDataNameHeader && dataObject.fixedTableDataNameHeader[0] && dataObject.fixedTableDataNameHeader[0].indexOf('__rowNum')>=0){
colCountWidth = 10; //mm
colCount = 1;
colCountWidthPer = colCountWidth*100/totalWidth;
}
}
var wPercent = (100 - colCountWidthPer) / (numTableColumns - colCount);
var wMillis = (totalWidth - colCountWidth) / (numTableColumns - colCount);
// Adjust column width in case of too small ( < 10mm or < 5mm)
if (wMillis < 10) {
wMillis = wMillis / 2;
} else if (wMillis < 5) {
wMillis = wMillis / 3;
}
if(colCount == 1){
arrColWidthPercent.push(colCountWidthPer);
arrColWidthMillis.push(colCountWidth);
}
for (var t = colCount; t < numTableColumns; t++) {
arrColWidthPercent.push(wPercent);
arrColWidthMillis.push(wMillis);
}
// Process with custom column width
if (dataObject.columnsSpaceType === CONTAINER_COLUMN_SPACE_TYPE_ADJUST_COLUMN_WIDTH
&& dataObject.withFormat4ColumnWeight !== undefined) {
var arrWidth = dataObject.withFormat4ColumnWeight.split('|');
// PCA-406: Report Settings [] show buttons and check boxes in PDF same as PDF
// Special treating with FixedTable, hide empty columns
if (dataObject.type === CONST_CTRL_TYPE_CTRLTABLE && dataObject.withFormat4ColumnWeight_PROCESS !== undefined) {
arrWidth = dataObject.withFormat4ColumnWeight_PROCESS.split('|');
}
var addPercen = 0;
if(numTableColumns < arrWidth.length){
for(var t=numTableColumns; t=0){
colCountWidth = 10; //mm
colCount = 1;
colCountWidthPer = colCountWidth*100/totalWidth;
}
}
var wPercent = (100 - colCountWidthPer) / (numTableColumns - colCount);
var wMillis = (totalWidth - colCountWidth) / (numTableColumns - colCount);
// Adjust column width in case of too small ( < 10mm or < 5mm)
if (wMillis < 10) {
wMillis = wMillis / 2;
} else if (wMillis < 5) {
wMillis = wMillis / 3;
}
if(colCount == 1){
arrColWidthPercent.push(colCountWidthPer);
arrColWidthMillis.push(colCountWidth);
}
for (var t = colCount; t < numTableColumns; t++) {
arrColWidthPercent.push(wPercent);
arrColWidthMillis.push(wMillis);
}
// Process with custom column width
if (dataObject.columnsSpaceType === CONTAINER_COLUMN_SPACE_TYPE_ADJUST_COLUMN_WIDTH
&& dataObject.withFormat4ColumnWeight !== undefined) {
var arrWidth = dataObject.withFormat4ColumnWeight.split('|');
// PCA-406: Report Settings [] show buttons and check boxes in PDF same as PDF
// Special treating with FixedTable, hide empty columns
if (dataObject.type === CONST_CTRL_TYPE_CTRLTABLE && dataObject.withFormat4ColumnWeight_PROCESS !== undefined) {
arrWidth = dataObject.withFormat4ColumnWeight_PROCESS.split('|');
}
var addPercen = 0;
if(settingColumns < arrWidth.length){
for(var t=numTableColumns; t list of children of valueOfGridControls
var listCells = $table.find('tr td');
var listData = valueOfGridControls;
listCells.addClass('withBorderInsideGrid');
for (var t = 0; t < listData.length; t++) {
var item = listData[t];
// Only process dummy label or label
if (item.type !== 'inputLabelDummy4Grid' && item.type !== 'inputLabel') { continue; }
// PCA-386: PDF/Print - Support shaded label in freeform grid
// OLD CODES, will be removed later ...
// // Special treating with Label
// if (item.type === 'inputLabel') {
// var objControl = $(listCells[t]);
// if (glbBuildFormSettingsWA.isShadedheadings === true) {
// objControl
// .css('background', glbBuildFormSettingsWA.headingColor)
// .css('color', glbBuildFormSettingsWA.textColor)
// ;
// } else {
// objControl.addClass('backgroundShading4Container');
// }
//
// continue;
// }
var isShadedHeadings = false;
var headingColor = '';
var textColor = '';
var activeTextColor = '';
var isBorderAroundHeading = true;
// Custom appearance
if (item.apperance === LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_APPEARANCE_CUSTOM) {
if (item.shadedHeadings !== undefined) {
isShadedHeadings = item.shadedHeadings.isShadedHeadings;
if (isShadedHeadings === true) {
headingColor = item.shadedHeadings.headingColor;
textColor = item.shadedHeadings.textColor;
activeTextColor = item.shadedHeadings.activeTextColor;
try{ // CO-3332: #1
if ('#ffffff' == headingColor.toLowerCase()) { // 'inputLabel' === item.type
headingColor = ''; // white color = no background
}
} catch(e){}
}
isBorderAroundHeading = item.shadedHeadings.isBorderAroundHeading;
}
} else {
// Default form setting
isShadedHeadings = glbBuildFormSettingsWA.isShadedheadings;
if (isShadedHeadings === true) {
headingColor = glbBuildFormSettingsWA.headingColor;
textColor = glbBuildFormSettingsWA.textColor;
activeTextColor = glbBuildFormSettingsWA.activeTextColor;
}
isBorderAroundHeading = glbBuildFormSettingsWA.isBorderAroundHeading;
}
// Apply shade color
var objControl = $(listCells[t]);
// PCA-386: PDF/Print - Support shaded label in freeform grid
// // We only get label or dummy label
// var dataName = objControl.find('.general_question').attr('data_name');
// if (dataName.indexOf('$dummy4Grid') < 0 || dataName == 'EMPTY$dummy4Grid') {
// continue; // Do nothing because current cell is not a dummy label cell
// }
// We only get label or dummy label
var isNeedProcessControl = false;
if (item.type === 'inputLabel') {
// OK, we will continue processing
isNeedProcessControl = true;
} else {
// Check the actual dummy label
var dataName = objControl.find('.general_question').attr('data_name');
if (dataName.indexOf('$dummy4Grid') < 0 || dataName == 'EMPTY$dummy4Grid') {
continue; // Do nothing because current cell is not a dummy label cell
}
// PCA-386: PDF/Print - Support shaded label in freeform grid
// OK, we will continue processing
}
if (isShadedHeadings === true) {
// // PCA-393: PDF/Print - Apply changes regarding border option
// if (isBorderAroundHeading !== true) {
// objControl.addClass('noBorder4LabelInGrid');
// }
// objControl.css('background', headingColor).css('color', textColor);
} else {
// Use default shading
if (item.apperance !== LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_APPEARANCE_CUSTOM)
{
objControl.addClass('backgroundShading4Container');
} else {
objControl.addClass('default_highlight_shading_color');
}
}
// PCA-393: PDF/Print - Apply changes regarding border option
if (isBorderAroundHeading !== true) {
objControl.addClass('noBorder4LabelInGrid');
// 0027015: Border bug issue
if (item.type === 'inputLabel' || item.type === 'inputLabelDummy4Grid'
) {
// Only process with the first column
var objCellIndex = objControl.closest('td').attr('cellIndex');
if (typeof(objCellIndex) !== 'undefined' && objCellIndex == 0) {
// Check if we are have border + shading
// Remove padding left by adding class
objControl.addClass('noPaddingLeft4Label');
objControl.addClass('noPaddingRight4Label');
}
}
}
if (browserNameGlobal == 'firefox' && textColor.toLowerCase() == '#ffffff') {
objControl.css('background', headingColor).css('color', 'rgba(0, 0, 0, 0)').css('text-shadow', '0 0 0 #fff');
}else{
objControl.css('background', headingColor).css('color', textColor);
}
}
}
/**
* Process update constants value (only affected on localhost for developing)
*/
function updateConstantsValueOnly4LocalhostFAST() {
// Force constants value into minimum value for fast development & test
try {
var fullUrl = window.location.href.toString();
if (fullUrl.indexOf('localhost:8888') > 0) {
WAITING_TIME_BETWEEN_CHECKING = 100;
WAITING_TIME_BETWEEN_CHECKING_4MULTI_FILES = 100;
}
} catch (e) {
// TODO: handle exception
}
}
/**
* Simulate PDF Report clicking with ReadOnly user + click View menu item
*/
function applyShowViewPrintFromReadOnlyUser() {
//$('.mobileUnitPrint').trigger('click');
if(editting && editting == CONST_VALUE_TRUE_STR){
jAlert(msg_record_editting);
}
// Check encrypted record
if(curEncryptFlg && CONST_VALUE_TRUE_STR == curEncryptFlg){
jAlert(msg_record_encrypted);
return;
}
if(emptyData){
jAlert(msg_no_data_print);
return;
}
var isRequestFromReadOnlyAndView = true;
initializePrintData(currentRowIndex, false, false, isRequestFromReadOnlyAndView);
}
/**
* Apply remove blank page with empty labels (Empty caption/hints/shadings/...)
*/
function applyRemoveBlankPageWithEmptyLabelQuestions(lastTable) {
var isRemoveBlankPage = false;
//writeToLogInfo('numberItems : ' + numberItemsInsideLastTableInOnePage + ' >> numberItemsEmptyLabel : ' + numberEmptyLabelsInsideLastTableInOnePage);
// When total items == total empty labels => we need remove lastTable
if (numberItemsInsideLastTableInOnePage > 0
&& numberItemsInsideLastTableInOnePage === numberEmptyLabelsInsideLastTableInOnePage) {
isRemoveBlankPage = true;
}
// Reset the value of numberItemsInsideLastTableInOnePage
numberItemsInsideLastTableInOnePage = 0;
numberEmptyLabelsInsideLastTableInOnePage = 0;
if (isRemoveBlankPage === true) {
lastTable.remove(); // We have to remove the current table for preventing print error
}
return isRemoveBlankPage;
}
/**
* Init GUI for Email PDF + Email Excel directly ViewData/Dispatch GUI
*/
function initEmailPDFAndExcelDirectlyViewDataDispatchGUI() {
// Show hide menu items : Email PDF/ Email Excel
try {
if (!isVersion(VERSION_EMAIL_PDF_EXCEL_DIRECT_VIEWDATA_DISPATCH)) {
$('.menudiv .mobileUnitPrintEmail').remove();
$('.menudiv .mobileUnitExcelReportEmail').remove();
}
} catch (e) {}
}
/**
* Show Excel/PDF panel GUI for sending email
*/
function showEmailPDFAndExcelDirectlyViewDataDispatchPanel(typePdfOrExcel) {
var recordKey = controlId;
writeToLogInfoRequired('recordKey : ' + recordKey + ' >> \ntypePdfOrExcel : ' + typePdfOrExcel);
$('#ctnRecipientsExcelTemplate1, #ctnEmailExcelTemplate1').val('');
var objPanel = $('.configEmailExcelTemplateExport1');
objPanel.find('.recordKeyItemVD').val(recordKey);
var objTitle = objPanel.find('.excelTemplateTitle1');
var objEmailTo = objPanel.find('.excelMailToHeader');
// In case of process PDF, we will call AJAX for detecting Standard PDF or Convert PDF
if (typePdfOrExcel === 'pdf') {
// Change title of GUI
objTitle.text('Email PDF report');
objEmailTo.text("Email PDF to:");
// Call AJAX
waitForDataLoading(true);
$.ajax({
url : '/PrintRPHandlerServlet?action=check_view_data_email_pdf_excel',
dataType : 'json',
type : 'POST',
data : {
projectKey : selectedProjectKey
,formKey : formId
},
cache : false,
complete : function() {
waitForDataLoading(false);
},
success : function(response, status) {
// Setting hidden fields based on response data
if (response.templateUseWhenCreatePdf === CREATE_PDF_BY_CUSTOM_REPORT_TEMLATE)
{
writeToLogInfo('We are in Convert PDF ...');
if (response.isExistExcelTemplate === true) {
// We are in PDF Report for Excel Template (convert2pdf)
objPanel.find('.isExcelTemplate').val(CONST_VALUE_TRUE_STR);
objPanel.find('.isClickMenuPdf').val(CONST_VALUE_TRUE_STR);
writeToLogInfo('The excel template exists ...');
} else {
writeToLogInfo('NOT FOUND Excel template do not exists ...');
jAlert(msg_select_excel_template_report_required);
return;
}
// TODO: Check the case of failing data ...
} else {
// We are in Standard PDF
objPanel.find('.isExcelTemplate').val(CONST_VALUE_FALSE_STR);
objPanel.find('.isClickMenuPdf').val(CONST_VALUE_TRUE_STR);
writeToLogInfo('We are in Standard PDF ...');
}
$('.configEmailExcelTemplateExport1').jqmShow();
},
error : function() {
jAlert(msg_unknown_error);
}
});
} else {
// We are in Email Excel
objPanel.find('.isExcelTemplate').val(CONST_VALUE_TRUE_STR);
objPanel.find('.isClickMenuPdf').val(CONST_VALUE_FALSE_STR);
writeToLogInfo('We are in Excel ...');
// Change title of Excel GUI
objTitle.text('Email Excel report');
objEmailTo.text("Email Excel to:");
$('.configEmailExcelTemplateExport1').jqmShow();
}
}
/**
* Process send mail of PDF/Excel on View/Dispatch
*/
function processEmailPDFOrExcelOnViewDispatch() {
// Get information
var objPanel = $('.configEmailExcelTemplateExport1');
var recordKey = objPanel.find('.recordKeyItemVD').val();
var isExcelTemplate = objPanel.find('.isExcelTemplate').val();
var isClickMenuPdf = objPanel.find('.isClickMenuPdf').val();
// Combination of isExcelTemplate/isClickMenuPDF : (true/true <=> Convert PDF, true/false <=> Excel,
var mailTo = $('#ctnRecipientsExcelTemplate1').val();
var mailContent = $('#ctnEmailExcelTemplate1').val();
writeToLogInfoRequired('mailTo : ' + mailTo);
writeToLogInfoRequired('mailContent : ' + mailContent);
writeToLogInfoRequired('recordKey : ' + recordKey);
writeToLogInfoRequired('isExcelTemplate : ' + isExcelTemplate);
writeToLogInfoRequired('isClickMenuPdf : ' + isClickMenuPdf);
// Validate email
mailTo = jQuery.trim(mailTo.replace(/,|;/g, ';'));
mailContent = mailContent.replace(/"/g, '"')
.replace(/\n/g," ");
if (mailTo == '') {
jAlert(msg_mail_to_required);
return;
}
// List email address (seperated by ; or ,)
var email_to_list = mailTo.split(';');
for ( var i = 0; i < email_to_list.length; i++) {
var curEmail = jQuery.trim(email_to_list[i]);
if(curEmail == '') { continue; }
// Using function utils.isEmailValid of hqkhanh
//if(/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{1,4})$/.test(curEmail)){
if (isValidEmail(curEmail)) {
// Valid email
}
else{
jAlert(msg_mail_to_not_valid);
return;
}
}
// Put process save file to servlet : PrintRPHandlerServle.java
waitForDataLoading(true);
// Check dummy processing ExcelTemplate
$.ajax({
url : '/PrintRPHandlerServlet',
dataType : 'json',
type : 'POST',
data : {
action : 'save_email_data'
,taskInfoKey : ''
,recordKey : recordKey
,mailTo : mailTo
,mailContent : mailContent
,isClickMenuPdf : isClickMenuPdf
,isExcelTemplate : isExcelTemplate
},
cache : false,
complete: function() {
//waitForDataLoading(false);
},
success : function(response, status) {
setTimeout('processCheckingEmailInBEOnly4ViewDataDispatch("' + response.taskInfoKey + '", "' + response.token + '")'
, WAITING_TIME_BETWEEN_CHECKING);
},error : function() {
jAlert(msg_unknown_error);
waitForDataLoading(false);
}
});
}
/**
* Process check finish progress and download file (Excel/PDF/Convert PDF)
* Ripped from send_email.js, function processCheckingEmailInBE()
* @param taskInfoKey
*/
function processCheckingEmailInBEOnly4ViewDataDispatch(taskInfoKey, token) {
waitForDataLoading(true);
// Check dummy processing ExcelTemplate
$.ajax({
url : '/PrintRPHandlerServlet',
dataType : 'json',
type : 'POST',
headers: {
"Authorization": "Bearer " + token
},
data : {
action : 'check_finish_task_email'
,taskInfoKey : taskInfoKey
},
cache : false,
complete: function() {
},
success : function(response, status) {
// Check result download
if (response.isFinish === true) {
waitForDataLoading(false);
// Show link download
writeToLogInfoRequired('Process Send Mail WEBSITE by Backends ...');
writeToLogInfoRequired('Download link : ' + response.downloadLink);
// Check if the task okie or not
if (response.isErrorTaskInfo === true) {
// Error occur, we will show error information
writeToLogInfoRequired('Error in PRTaskInfo : ' + response.errorMessage);
showPrintReportInBackendsErrorMsg(response.errorMessage);
return;
}
jAlert(msg_print_send_email_task_success);
// Create Email PDF/Email Excel directly on ViewData/Dispatch GUI
$('.configEmailExcelTemplateExport1').jqmHide();
return;
}
// Loop process checking finish task and download file
setTimeout('processCheckingEmailInBEOnly4ViewDataDispatch("' + taskInfoKey + '", "' + token + '")', WAITING_TIME_BETWEEN_CHECKING);
},error : function() {
jAlert(msg_unknown_error);
waitForDataLoading(false);
}
});
}
/**
* Apply remove border with questions inside Grid
* @param cellValue
* @param child
*/
function prt_applyRemoveBorderInGrid(cellValue, child) {
var cValue = cellValue;
try {
if (CONTROL_NOT_APPLY_REMOVE_BORDER_ANSWER_PREVIEW_PDF.indexOf(child.type+',') < 0) {
var isNeedRemoveBorder = false;
if (child.apperance === LABEL_CONSTANTS_VALUE_OPTION_BUILD_FORM_APPEARANCE_CUSTOM) {
if (child.removeAnswerBorder === true) {
isNeedRemoveBorder = true;
}
} else if (glbBuildFormSettingsWA.removeAnswerBorder) {
isNeedRemoveBorder = true;
}
// Check if we need remove border
if (isNeedRemoveBorder) {
cValue = cValue.replace('#remove_border_class#', 'removeBorderAroundAnswerPrt');
}
}
} catch (e) {
}
return cValue;
}
/**
* CO65 - Apply the negative number settings for reports
* @param dataObject
* @return Object {
* negativeRedText (true/false)
* negativeBrackets (true/false)
* }
*/
function prt_getNegativeControlInfo(dataObject, content) {
var result = {
negativeRedText : false
,negativeBrackets : false
}
if (isVersion(VERSION_NUMERIC_NEGATIVE_OPT)) {
var checkType = 'inputNumeric,Integer,Decimal,Percent';
// Only affect with negative value
var isNeedCheckType = false;
// Numeric type
if (checkType.indexOf(dataObject.type) >= 0) {
isNeedCheckType = true;
}
// Calculation Numeric type
else if (dataObject.type === CONST_CTRL_TYPE_INPUTCALCULATE) {
if (dataObject.kind === 'Number' || dataObject.kind === 'Percent') {
isNeedCheckType = true;
}
}
if (isNeedCheckType && content.indexOf('-') >= 0) {
// Including [RedText] + [Bracket]
// Check NegativeRed or NegativeBrackets
// if (dataObject.negativeRedText) {
// result.negativeRedText = dataObject.negativeRedText;
// result.content = '' + content + '';
// }
// if (dataObject.negativeBrackets) {
// result.negativeBrackets = dataObject.negativeBrackets;
// result.content = '(' + content + ')';
// }
// Including [RedText] + [Bracket]
result.content = content;
if (dataObject.negativeBrackets) {
result.negativeBrackets = dataObject.negativeBrackets;
result.content = '(' + result.content + ')';
}
if (dataObject.negativeRedText) {
result.negativeRedText = dataObject.negativeRedText;
result.content = '' + result.content + '';
}
}
}
return result;
}
/*
* CO-2138 break code into function
*
*
*/
function callFormLoadedEvents() {
console.log('doforms-form-loaded');
top.postMessage({
eventType: 'doforms-form-loaded'
}, '*');
}