//==============================================================================
//
// Purpose: Functions common to the other SZ files.
//
//==============================================================================
/*global
cancelEvent
cdBuildTextFieldP
cdBuildTextFieldRowP
ClientDialogBuilder
CommonUtils
consoleLogJ
ContextMenu
czCheckForDialogMnemonics
displayTimedMessage
doCloseOrCancelClientDialog
FilterFrameworkRemoteScriptingCommands_Enum
g_arrAltPageLinks
g_clientDialogStack
g_subdialogStack
getObj
hideContextMenu
hideDialog
hideDialogP
hideSubdialog
htmlEncode
htmlMultilineEncode
isDialogShowing
jsrsExecuteWithErrorP
KnownErrorsCodes_Enum
MWClientTable
MWColumn
processTypeAheadSearchOfJSONArray
showAddIngredient
showDialogP
showInfoDialog
showLocationSearch
submitAddOrUpdateFundingTarget
SummaryOptionsFilter
SZCalendarNotes
SZDogs
SZMileageTracker
SZRecipes
SZRunning
SZWeightTracker
WebPages_Enum
ZuluBackups
fnHandleEscapeKey
g_arrAvailableProductNames
g_dogId
g_shoppingListId
g_userInitial
g_wp
g_zuId
pageRecipe
*/
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//function rsCallbackGetBackupsListHtml(json_) {
// var objBackupRow = getObj('rowBackupList'),
// objBackupCell = objBackupRow.querySelector('td');
// consoleLog('backupListHtml=' + json_.backupListHtml);
// if (objBackupCell) {
// objBackupCell.innerHTML = json_.backupListHtml;
// }
// showInfoDialog(
// json_.backupListHtml,
// 'Backup Info');
//}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//function getBackupsListHtml() {
// jsrsExecuteWithErrorP(
// 'Admin_GetBackupsListHtml', // commandString_
// rsCallbackHandleStandardJSONResponse, // fnJSONCallback_
// 'Getting Backup List Html', // doingWhat_
// {}, // payloadDocument_
// {
// fnOnSuccess: rsCallbackGetBackupsListHtml
// });
//}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//function commonDoKeyUp(event, isEscape_, isTabKey_, keyCode_, isShiftDown_, isAltDown_, isCtrlDown_, objTarget_) {
// if (isAltDown_ && !(isCtrlDown_ || isShiftDown_)) {
// switch (keyCode_) {
// case 68:
// // Alt-D
// break;
//
// case 87:
// // Alt-W
// break;
// }
// }
//}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
RegExp.quote = function (str) {
return (str + '').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
};
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
//function selectFTDialogDate() {
// var objField = getObj('txtFundingTargetDate');
// setFocus(objField);
//}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// eslint-disable-next-line no-unused-vars
var SZCommon = function() {
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbWireUpClientFilterRSCalls() {
SummaryOptionsFilter.setRSCommandToUse({
commandId: FilterFrameworkRemoteScriptingCommands_Enum.ffrscGetFilterControlInfoForPage,
rsCommandString: 'Admin_GetFilterControlInfoForPage'
});
SummaryOptionsFilter.setRSCommandToUse({
commandId: FilterFrameworkRemoteScriptingCommands_Enum.ffrscGetFilterPropertyOptionsForPage,
rsCommandString: 'Admin_GetFilterPropertyOptionsForPage'
});
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbPadDecimals(val_, minDecimals_) {
val_ = val_ + '';
var idxDecimal = val_.lastIndexOf('.'),
tmpStrLen = val_.length;
if(idxDecimal < 0) {
val_ += '.';
idxDecimal = tmpStrLen - 1;
}
while((tmpStrLen - idxDecimal - 1) < minDecimals_) {
val_ += '0';
++tmpStrLen;
}
return val_;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvIsAddOrUpdateFTDialogShowing() {
return CommonUtils.isDialogWithIdShowing('dialog-addOrUpdateFundingTarget');
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbCarefulNavigateToUrl(url_) {
hideDialogP({
callback: function() {
window.location = url_;
}
});
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbProductNameGetTypeAheadData(form_, searchText_) {
var arrProductNames = g_arrAvailableProductNames,
arrFilteredProducts =
arrProductNames.filter(
CommonUtils.buildWordBoundaryFilterFunction(searchText_, function(value_) { return value_; }));
processTypeAheadSearchOfJSONArray(
{
extraHTMLPropertyName: 'totalHTML',//objOriginalOptions.extraHTMLPropertyName,
forceIgnoreCurrentTextForBold: 1,//objOriginalOptions.forceIgnoreCurrentTextForBold,
arrObjects: arrFilteredProducts,
areMoreItems: 0//tmpAreMoreItems
});
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbBuildProductNameRowsWithTypeahead(strFormId, productFieldName_, productName_, autofocus_) {
var strProductNameFieldId = productFieldName_,
strProductIdFieldId = strProductNameFieldId + '.id',
rc = cdBuildTextFieldRowP(
strProductNameFieldId, // fieldName_
'Name', // labelHTML_
{
fieldValue: productName_ || '',
fieldId: strProductNameFieldId,
suppressAutocomplete: 1,
autofocus: autofocus_,
fieldClasses: "input-noButton",
additionalRawFieldAttributes: ' data-1p-ignore ',
typeaheadInfo: {
idFieldName: strProductIdFieldId,
formId: strFormId,
handlingEnter: 1,
stringifiedParams: '{textFieldName: "' + strProductNameFieldId + '",' +
'formId:"' + strFormId + '",' +
'idFieldName:"' + strProductIdFieldId + '",' +
'fnGetTypeAheadData: productNameGetTypeAheadData,' +
'fnHandleExplicitSelection: typeaheadDivHidingExplicitTypeaheadSelectionHandlerV2 }'
}
});
return rc;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvSearchHighlightEncode(rawString_, searchTerm_, multilineEncode_) {
var rc = '',
idxLast = 0,
idxPostTerm,
strLowerTerm = searchTerm_.toLowerCase(),
strLowerRaw = rawString_.toLowerCase(),
idxNext = strLowerRaw.indexOf(strLowerTerm, idxLast),
fnEncode = multilineEncode_ ? htmlMultilineEncode : htmlEncode;
while(idxNext > -1) {
idxPostTerm = idxNext + searchTerm_.length;
rc += fnEncode(rawString_.substring(idxLast, idxNext)) +
'' +
fnEncode(rawString_.substring(idxNext, idxPostTerm)) +
'';
idxLast = idxPostTerm;
idxNext = strLowerRaw.indexOf(strLowerTerm, idxLast);
}
rc += fnEncode(rawString_.substring(idxLast));
return rc;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvRecipeSearchResultColumnRenderer(objRow_) {
var theSearchPromptForm = getObj('frmSearchRecipes'),
strSearchTerm = theSearchPromptForm.searchTerm.value;
consoleLogJ({
what: 'building column',
strSearchTerm: strSearchTerm
});
var objRecipeResult = objRow_,
arrIngredients = objRecipeResult.arrIngredients,
strRecipeDirections = objRecipeResult.recipeDirections,
tmpIngredientCount = arrIngredients.length,
idxIngredient,
objIngredient,
strRecipeLink =
'',
rc = '
Recipe: ' + strRecipeLink + '
';
if(strRecipeDirections) {
rc +=
'' +
pvSearchHighlightEncode(
strRecipeDirections, // rawString_
strSearchTerm,
1) + // multilineEncode_
'
';
}
if(tmpIngredientCount) {
for(idxIngredient = 0; idxIngredient < tmpIngredientCount; ++idxIngredient) {
objIngredient = arrIngredients[idxIngredient];
rc +=
'Ingredient: ' + pvSearchHighlightEncode(objIngredient.ingredientName, strSearchTerm) + '
';
if(objIngredient.ingredientNotes) {
rc +=
'Notes
' +
pvSearchHighlightEncode(objIngredient.ingredientNotes, strSearchTerm);
}
}
}
return rc;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvRSCallbackSearchRecipes(json_, optionsHolder_) {
var arrRecipes = json_.arrRecipes,
objClientDialog =
new ClientDialogBuilder({
formTitle: 'Search Results'
}),
objResultTable =
new MWClientTable({
additionalTableClasses: 'responsiveTable searchResultsTable',
arrColumns: [
new MWColumn({
columnName: '',
additionalCellClasses: 'clsRecipeDescriptionCell',
fnCustomRenderCellContents:
pvRecipeSearchResultColumnRenderer
})
]
});
objClientDialog.addFlexibleFieldRow({
rawLabel: 'Search Term',
rawValue: optionsHolder_.originalPayload.searchTerm,
additionalCellClasses: 'clsNarrowField'
});
objClientDialog.addFlexibleFieldRow({
rawLabel: 'Result Count',
rawValue: arrRecipes.length.toString()
});
objClientDialog.addFlexibleRow({
valueHTML: objResultTable.buildTableForArray(arrRecipes)
});
objClientDialog.showClientDialog();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvSubmitSearchRecipes() {
var theForm = getObj('frmSearchRecipes'),
strSearchTerm = theForm.searchTerm.value;
jsrsExecuteWithErrorP(
'Admin_SearchRecipes', // commandString_
pvRSCallbackSearchRecipes, // fnCallback_
'Searching Recipes', // doingWhat_
{
searchTerm: strSearchTerm,
zuId: g_zuId
}); // payload
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvShowRecipeSearch() {
var objClientDialog =
new ClientDialogBuilder({
formTitle: 'Search Recipes',
formId: 'frmSearchRecipes',
fnSubmit: pvSubmitSearchRecipes,
focusFieldName: 'searchTerm',
suppressDialogConfirmer: 1,
okButtonDisplayText: 'Search'
});
objClientDialog.addFlexibleRow({
valueHTML: cdBuildTextFieldP(
'searchTerm', // fieldName_
{
isSearch: 1,
autofocus: 1
})// params_
});
objClientDialog.showClientDialog();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvRSCallbackSearchShoppingLists(json_, optionsHolder_) {
var arrSearchResults = json_.arrSearchResults,
searchTerm = optionsHolder_.originalPayload.searchTerm,
objClientDialog =
new ClientDialogBuilder({
formTitle: 'Search Results'
}),
objResultTable =
new MWClientTable({
additionalTableClasses: 'responsiveTable searchResultsTable',
arrColumns: [
new MWColumn({
columnName: 'Shopping List Name',
fnCustomRenderCellContents: function (objRow_) {
var rc =
'' +
'
' +
'' +
'Shopping List | ' +
'' +
'' +
pvSearchHighlightEncode(objRow_.shoppingListName, searchTerm) +
'' +
' | ' +
'
';
if (objRow_.productName) {
rc +=
'' +
'Product Name: | ' +
'' +
pvSearchHighlightEncode(objRow_.productName, searchTerm) +
' | ' +
'
';
}
if (objRow_.slpNotes) {
rc +=
'' +
'Notes: | ' +
'' +
pvSearchHighlightEncode(objRow_.slpNotes, searchTerm, 1) +
' | ' +
'
';
}
rc +=
'
' +
'
';
return rc;
}
})
]
});
objClientDialog.addFlexibleRow({
//rawValue: JSON.stringify(json_, null, 2)
valueHTML: objResultTable.buildTableForArray(arrSearchResults)
});
objClientDialog.showClientDialog();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvSubmitSearchShoppingLists() {
var theForm = getObj('frmSearch'),
strSearchTerm = theForm.searchTerm.value;
jsrsExecuteWithErrorP(
'Admin_SearchShoppingLists', // commandString_
pvRSCallbackSearchShoppingLists, // fnCallback_
'Searching Recipes', // doingWhat_
{
searchTerm: strSearchTerm,
zuId: g_zuId,
shoppingListId: typeof g_shoppingListId === 'undefined' ? '' : g_shoppingListId
}); // payload
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvShowShoppingListSearch() {
var objClientDialog =
new ClientDialogBuilder({
formTitle: 'Search Shopping Lists',
formId: 'frmSearch',
fnSubmit: pvSubmitSearchShoppingLists,
focusFieldName: 'searchTerm',
suppressDialogConfirmer: 1,
okButtonDisplayText: 'Search'
});
objClientDialog.addTextFieldRow(
'searchTerm', // fieldName_
{
isSearch: 1,
autofocus: 1
});
objClientDialog.showClientDialog();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbPromptSearch() {
switch(g_wp) {
case WebPages_Enum.wpRecipes:
case WebPages_Enum.wpViewRecipe:
case WebPages_Enum.wpCategories:
pvShowRecipeSearch();
break;
case WebPages_Enum.wpShoppingList:
case WebPages_Enum.wpShoppingLists:
pvShowShoppingListSearch();
break;
case WebPages_Enum.wpLocations:
showLocationSearch();
break;
case WebPages_Enum.wpWeightTracker:
SZWeightTracker.showWeightSearch();
break;
case WebPages_Enum.wpCalendarNotes:
SZCalendarNotes.showCalendarNotesSearch();
break;
default:
showInfoDialog('TODO: SZCommon.promptSearch() - g_wp=' + JSON.stringify(g_wp), 'Search');
break;
}
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvFailedChangePWErrorHandler(json_) {
var tmpErrorCode = json_.error.errorCode;
switch(tmpErrorCode) {
case KnownErrorsCodes_Enum.kecNotLoggedIn:
// No longer logged in, can't change pw...
hideDialog();
window.location.reload();
return 1;
case KnownErrorsCodes_Enum.kecInvalidPassword:
showInfoDialog(htmlMultilineEncode(json_.error.message), 'Failed To Change Password', 1, 'userOldPWForChange');
return 1;
}
return 0; // Let the regular error handler take care of this...
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvRSCallbackDidChangePW(json_) {
if(json_.error) {
pvFailedChangePWErrorHandler(json_);
} else {
hideDialog();
displayTimedMessage('Your password has been changed', 5000);
}
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvSubmitChangePassword() {
var objOldPW = getObj('userOldPWForChange'),
strOldPW = objOldPW.value,
objNewPW = getObj('userNewPWForChange'),
strNewPW = objNewPW.value,
objConfirmPW = getObj('userConfirmPWForChange'),
strConfirmPW = objConfirmPW.value;
if(!strOldPW) {
showInfoDialog('Please enter your old password...', 'Missing Password', 1, objOldPW.name);
return;
}
if(!strNewPW) {
showInfoDialog('Please enter a new password...', 'Missing Password', 1, objNewPW.name);
return;
}
if(strNewPW !== strConfirmPW) {
showInfoDialog('Passwords don\'t match...', 'Missmatched Passwords', 1, objConfirmPW.name);
return;
}
jsrsExecuteWithErrorP(
'Admin_SetPassword', // commandString_
pvRSCallbackDidChangePW, // fnCallback_
'Setting Password', // doingWhat_
{
oldPassword: escape(strOldPW),
newPassword: escape(strNewPW)
}); // payloadDocument_
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbShowChangePasswordDialog() {
var strFormId = 'dialog-changePW',
objClientDialog =
new ClientDialogBuilder({
formTitle: 'Change Password',
formId: strFormId,
fnSubmit: pvSubmitChangePassword,
focusFieldName: 'userOldPWForChange',
okButtonDisplayText: 'Change Password'
});
objClientDialog.addTextFieldRow(
'userOldPWForChange',
{
fieldId: 'userOldPWForChange',
rawLabel: 'Old Password',
isPasswordField: 1
});
objClientDialog.addTextFieldRow(
'userNewPWForChange',
{
fieldId: 'userNewPWForChange',
rawLabel: 'New Password',
isPasswordField: 1
});
objClientDialog.addTextFieldRow(
'userConfirmPWForChange',
{
fieldId: 'userConfirmPWForChange',
rawLabel: 'Confirm New Password',
isPasswordField: 1
});
objClientDialog.showClientDialog();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbShowUserPreferencesDialog() {
var strFormId = 'frmUpdateUserPrefs';
showDialogP(
'| For now, there are no "User Preferences". |
',
strFormId,
{
formTitle: 'TODO: pbShowUserPreferencesDialog()',
hideOkButton: 1
});
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvRSCallbackDidSignOut() {
displayTimedMessage('Refreshing...');
window.location.reload();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbSignOut() {
jsrsExecuteWithErrorP(
'Admin_SignOut', // commandString_
pvRSCallbackDidSignOut, // fnCallback_
'Signing Out'); // doingWhat_
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvCommonDoKeyDown(event, isEscape_, isTabKey_, keyCode_, isShiftDown_, isAltDown_, isCtrlDown_, objTarget_) {
if(isEscape_) {
if(typeof fnHandleEscapeKey === 'function') {
if(fnHandleEscapeKey(objTarget_)) {
return;
}
}
}
if(!isAltDown_ && !(isEscape_ && isDialogShowing())) {
if(isEscape_) {
hideContextMenu();
}
return;
}
//var doCancelEvent = true;
if(isDialogShowing()) {
// Dialog shortcuts
if(isEscape_) {
if((g_clientDialogStack && g_clientDialogStack.length > 0) || (g_subdialogStack && g_subdialogStack.length > 0)) {
if(g_clientDialogStack && g_clientDialogStack.length) {
var objClientDialog = g_clientDialogStack[g_clientDialogStack.length - 1],
tmpFormId = objClientDialog.formId;
doCloseOrCancelClientDialog(tmpFormId, objClientDialog.isSubdialog/*isSubdialog_*/);
} else {
hideSubdialog();
}
} else {
hideDialogP({
callback: function() { }
});
}
cancelEvent(event);
return;
} else {
//doCancelEvent = false;
}
} else {
// Non-dialog event
}
if(isAltDown_ && !(isCtrlDown_ || isShiftDown_)) {
switch(keyCode_) {
case 48:
// Alt-0
if(!isDialogShowing()) {
switch(g_wp) {
case WebPages_Enum.wpRecipes:
SZRecipes.uploadRecipe();
cancelEvent(event);
return 1;
case WebPages_Enum.wpViewRecipe:
showAddIngredient();
cancelEvent(event);
return 1;
case WebPages_Enum.wpCalendarNotes:
SZCalendarNotes.addOrUpdateCalendarNotes();
cancelEvent(event);
return 1;
case WebPages_Enum.wpDogDetail:
SZDogs.showEditDogActivity({
zuId: g_zuId,
dogId: g_dogId,
personName: g_userInitial || ''
});
cancelEvent(event);
return 1;
case WebPages_Enum.wpWeightTracker:
SZWeightTracker.addMeasurement();
cancelEvent(event);
return 1;
case WebPages_Enum.wpRunningActivities:
SZRunning.promptEditActivity();
cancelEvent(event);
return 1;
case WebPages_Enum.wpMileage:
SZMileageTracker.addMileage();
cancelEvent(event);
return 1;
}
}
break;
case 66:
// Alt-B
if(!isDialogShowing()) {
ZuluBackups.promptPerformServerBackup();
cancelEvent(event);
return 1;
}
break;
case 68:
// Alt-D
//if (pvIsAddOrUpdateFTDialogShowing()) {
// selectFTDialogDate();
// cancelEvent(event);
// return 1;
//}
break;
case 69:
// Alt-E
if(!isDialogShowing()) {
showInfoDialog('TODO: ', '');
cancelEvent(event);
return 1;
}
break;
case 83:
// Alt-S
if(!isDialogShowing()) {
pbPromptSearch();
cancelEvent(event);
}
break;
case 85:
//Alt-U
if(pvIsAddOrUpdateFTDialogShowing()) {
submitAddOrUpdateFundingTarget();
cancelEvent(event);
return 1;
}
break;
}
// Check if there are any mnemonics showing on the top-level dialog...
if(czCheckForDialogMnemonics(keyCode_)) {
cancelEvent(event);
return 1;
}
}
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbCommonInitKeyboard() {
//ConsoleLogging.logBlockOpen('SZCommon.pbCommonInitKeyboard()');
CommonUtils.baseInitKeyboard();
CommonUtils.addKeyDownHandler(
'SZCommonInitKeyboardHandler', // name_
pvCommonDoKeyDown); // fnHandler_
//CommonUtils.addKeyUpHandler(
// 'SZCommonInitKeyboardHandler', // name_
// commonDoKeyUp); // fnHandler_
//ConsoleLogging.logBlockClose();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbPromptWithAlternativeLinks(event_) {
var arrLinkInfos = g_arrAltPageLinks,
tmpLinkCount = arrLinkInfos.length,
idxLink,
objMenu = new ContextMenu();
if(tmpLinkCount > 0) {
for(idxLink = 0; idxLink < tmpLinkCount; ++idxLink) {
var objLinkInfo = arrLinkInfos[idxLink],
strRawText = objLinkInfo.rawDisplayText,
tmpIsCurrent = objLinkInfo.isCurrentSelection,
strLinkUrl = objLinkInfo.pageUrl,
strIsCurrentOverrideEditJS =
objLinkInfo.isCurrentOverrideEditJS;
if(tmpIsCurrent) {
if(strIsCurrentOverrideEditJS) {
objMenu.AddMenuItemP({
rawText: '** -- Edit ' + strRawText + ' -- **',
doubleQuoteReadyScript:
htmlEncode(strIsCurrentOverrideEditJS)
});
} else {
objMenu.AddInactiveHTMLTitledItem(
' ' +
'' +
'*' + htmlEncode(strRawText) +
' ');
}
} else {
objMenu.AddHTMLTitledLinkItem(
htmlEncode(strRawText), // htmlTitle_
strLinkUrl); // url_
}
}
}
objMenu.Show(event_);
}
//--------------------------------------------------------------------------
// SZCommon
//--------------------------------------------------------------------------
return {
wireUpClientFilterRSCalls: pbWireUpClientFilterRSCalls,
promptWithAlternativeLinks: pbPromptWithAlternativeLinks,
padDecimals: pbPadDecimals,
carefulNavigateToUrl: pbCarefulNavigateToUrl,
productNameGetTypeAheadData: pbProductNameGetTypeAheadData,
buildProductNameRowsWithTypeahead: pbBuildProductNameRowsWithTypeahead,
promptSearch: pbPromptSearch,
showChangePasswordDialog: pbShowChangePasswordDialog,
showUserPreferencesDialog: pbShowUserPreferencesDialog,
signOut: pbSignOut,
commonInitKeyboard: pbCommonInitKeyboard
};
}();
//------------------------------------------------------------------------------
// TODO: Necessary to support JT/Moraware framework????
// (Experimenting as-of 2025/06/22)
//------------------------------------------------------------------------------
//function showV2SearchDialog() {
// SZCommon.promptSearch();
//}
//==============================================================================
//
// Purpose: Functions common to the other SZ files.
//
//==============================================================================
/* eslint
no-global-assign: "off"
*/
/*global
cancelEvent
cdBuildFAFontIconButton
cdBuildFontIconElem
cdBuildTextAreaFieldRowP
ConsoleLogging
ContextMenu
eventPageX
eventPageY
FontIconId_Enum
g_strSeparatorContent
getObj
getRawFontId
htmlEncode
jsrsExecuteWithErrorP
MJTDictionary
removeNode
rsCallbackHandleStandardJSONResponse
showDialogP
WebPages_Enum
g_dogId
g_recipeId
g_shoppingListId
g_wp
g_zuId
pageDogDetail
pageRecipes
pageRecipe
pageShoppingList
pageZu
*/
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// eslint-disable-next-line no-unused-vars
var SZMyMenu = function () {
var g_lastMyMenuResult,
g_mapRecipeIdToPinStateOverride = new MJTDictionary(),
PINNED_ITEMS_SEPARATOR_ID = 'mnuSepPinned',
RECENT_ITEMS_SEPARATOR_ID = 'mnuSepRecent';
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvOverrideRecipePinState(params_) {
ConsoleLogging.logBlockOpen('pvOverrideRecipePinState()');
var tmpRecipeId = params_.recipeId,
tmpIsPinned = params_.isPinned;
g_mapRecipeIdToPinStateOverride.add(tmpRecipeId, tmpIsPinned);
ConsoleLogging.logObject({
tmpRecipeId: tmpRecipeId,
tmpIsPinned: tmpIsPinned
});
ConsoleLogging.logBlockClose();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvIsRecipeCurrentlyPinned(params_) {
var tmpRecipeId = params_.recipeId,
tmpOriginalIsPinnedValue = params_.originalIsPinnedValue;
return g_mapRecipeIdToPinStateOverride.getItemWithDefaultValue(
tmpRecipeId, // key_
tmpOriginalIsPinnedValue); // default_
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvAddShoppingListsToMenu(theMenu) {
var arrShoppingLists = g_lastMyMenuResult.arrShoppingLists,
objShoppingList,
tmpIsSelected,
strBoldStyle,
i;
for (i = 0; i < arrShoppingLists.length; ++i) {
objShoppingList = arrShoppingLists[i];
tmpIsSelected = (typeof g_shoppingListId !== 'undefined') &&
g_shoppingListId === objShoppingList.id;
strBoldStyle = tmpIsSelected ? 'font-weight:bold;' : '';
theMenu.AddHTMLTitledLinkItem(
'' +
(tmpIsSelected ?
('' + getRawFontId(FontIconId_Enum.fiiCheck) + ';') :
'') +
htmlEncode(objShoppingList.name) +
' (' + objShoppingList.uncheckedItemCount + '/' + objShoppingList.itemCount + ')' +
' (' + htmlEncode(objShoppingList.zuName) + ')' +
'',
pageShoppingList + 'id=' + objShoppingList.id + objShoppingList.storeLinkAddendum);
}
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvAddZusToMenu(theMenu, selectedZuId_) {
var arrZus = g_lastMyMenuResult.arrZus,
objZu,
i,
tmpIsSelected,
strBoldStyle;
for (i = 0; i < arrZus.length; ++i) {
objZu = arrZus[i];
tmpIsSelected = objZu.id === selectedZuId_;
strBoldStyle = tmpIsSelected ? 'font-weight:bold;' : '';
theMenu.AddHTMLTitledLinkItem(
'' +
(tmpIsSelected ?
('' + getRawFontId(FontIconId_Enum.fiiCheck) + ';') :
'') +
htmlEncode(objZu.name) +
'',
pageZu + 'zuId=' + objZu.id);
}
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function ptShowZusSubMenu(event, selectedZuId_) {
var theMenu = new ContextMenu('clsMyMenu');
pvAddZusToMenu(theMenu, selectedZuId_);
theMenu.ShowSubmenu(event, 'zusSubMenu');
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvPinFontIconElementId(recipeId_) {
return 'icoPin.' + recipeId_;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvRecipeMenuItemId(recipeId_) {
return 'mnuRecipe.' + recipeId_;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvAdjustRecipeMenuSeparatorsVisibility(params_) {
var objTableOfMenuItems = params_.tableOfMenuItems,
objLstMenuItemRows = objTableOfMenuItems.rows,
tmpFoundPinnedItem,
tmpFoundRecentItem,
tmpLookingAtRecents,
idxMenuItem,
objMenuItemRow,
strMenuItemRowId,
objSeparatorElemPinned = getObj(PINNED_ITEMS_SEPARATOR_ID),
objSeparatorElemRecent = getObj(RECENT_ITEMS_SEPARATOR_ID);
for (idxMenuItem = 0; idxMenuItem < objLstMenuItemRows.length && !tmpFoundRecentItem; ++idxMenuItem) {
objMenuItemRow = objLstMenuItemRows[idxMenuItem];
strMenuItemRowId = objMenuItemRow.id;
if (strMenuItemRowId === RECENT_ITEMS_SEPARATOR_ID) {
// We've hit the recent-items separator, so from here on, we're
// looking at recent items.
tmpLookingAtRecents = 1;
} else if (strMenuItemRowId !== PINNED_ITEMS_SEPARATOR_ID) {
// Confirm that this is a recipe row. (i.e. check if it has
// a pin-icon child)
if (objMenuItemRow.querySelector('.clsRecentPinButton')) {
if (tmpLookingAtRecents) {
tmpFoundRecentItem = 1;
} else {
tmpFoundPinnedItem = 1;
}
}
}
}
objSeparatorElemPinned.style.display =
tmpFoundPinnedItem ? '' : 'none';
objSeparatorElemRecent.style.display =
tmpFoundRecentItem ? '' : 'none';
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvMoveRecipeMenuItemToTopOfSection(params_) {
var tmpRecipeId = params_.recipeId,
tmpIsPinned = params_.isPinned,
objTargetedRecipeRow = getObj(pvRecipeMenuItemId(tmpRecipeId)),
objTableOfMenuItems = objTargetedRecipeRow.parentNode,
objSeparatorElemPinned = getObj(PINNED_ITEMS_SEPARATOR_ID),
objSeparatorElemRecent = getObj(RECENT_ITEMS_SEPARATOR_ID),
objNewPreviousSibling =
tmpIsPinned ?
objSeparatorElemPinned :
objSeparatorElemRecent;
// First, move the selected item so that it's first in the targeted
// list...
removeNode(objTargetedRecipeRow);
objNewPreviousSibling.insertAdjacentElement(
'afterend', // position
objTargetedRecipeRow); // element
// Next, ensure that the appropriate separators are visible since it's
// possible that either might need to be shown or hidden...
pvAdjustRecipeMenuSeparatorsVisibility({
tableOfMenuItems: objTableOfMenuItems
});
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvRSCallbackUpdatedRecipePin(json_) {
ConsoleLogging.logBlockOpen('pvRSCallbackUpdatedRecipePin()');
var tmpRecipeId = json_.recipeId,
tmpIsPinned = json_.isPinned,
strPinIconElemId =
pvPinFontIconElementId(
tmpRecipeId),
objPinIconElem =
getObj(strPinIconElemId);
if (tmpIsPinned) {
objPinIconElem.classList.remove('rotate90FontIcon');
} else {
objPinIconElem.classList.add('rotate90FontIcon');
}
pvOverrideRecipePinState({
recipeId: tmpRecipeId,
isPinned: tmpIsPinned
});
pvMoveRecipeMenuItemToTopOfSection({
recipeId: tmpRecipeId,
isPinned: tmpIsPinned
});
ConsoleLogging.logBlockClose();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function ptHandlePinClick(event, recipeId_, originalPinnedValue_) {
cancelEvent(event);
var tmpIsRecipeCurrentlyPinned =
pvIsRecipeCurrentlyPinned({
recipeId: recipeId_,
originalIsPinnedValue: originalPinnedValue_
}),
tmpSetPinned = tmpIsRecipeCurrentlyPinned ? 0 : 1;
jsrsExecuteWithErrorP(
'Admin_PinRecentRecipe', // commandString_
rsCallbackHandleStandardJSONResponse, // fnCallback_
tmpSetPinned ? 'Pinning Recent Recipe' : 'Unpinning Recent Recipe',
{
recipeId: recipeId_,
setPinned: tmpSetPinned
}, // payload
{
fnOnSuccess: pvRSCallbackUpdatedRecipePin, // no-op
skipInfoMessage: 1,
skipDisableDialogButtons: 1
}); // options
return false;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvBuildPinUnpinButtonHtml(params_) {
var tmpRecipeId = params_.recipeId,
tmpIsPinned = params_.isPinned,
strOnClick =
"return SZMyMenu.PROTECTED.handlePinClick(" +
"event," +
tmpRecipeId + "," +
tmpIsPinned +
");";
return cdBuildFAFontIconButton({
fontId: FontIconId_Enum.fiiPin_Ionicon,
additionalButtonClasses:
'clsRecentPinButton' +
(tmpIsPinned ? ' clsPinned' : ''),
additionalFontClasses:
'fontSizeXXLarge' +
(tmpIsPinned ? '' : ' rotate90FontIcon'),
fontIconElemId: pvPinFontIconElementId(tmpRecipeId),
doubleQuoteEncodedOnClickJS: strOnClick
});
}
//--------------------------------------------------------------------------
//
// TODO: Add support for row id and hide options in
// ContextMenu.AddSeparator().
//
//--------------------------------------------------------------------------
function pvAddSeparatorToMenu(params_) {
var theMenu = params_.menu,
strRawRowId = params_.rowId,
tmpHideRow = params_.hideRow,
strRowId = '' + (strRawRowId || ''),
strIdAttr =
strRowId ?
' id="' + strRowId + '"' :
'',
strStyleAttr =
tmpHideRow ?
' style="display:none"' :
'',
strOldSeparatorContent = g_strSeparatorContent;
if (strRowId) {
g_strSeparatorContent =
' |
';
}
theMenu.AddSeparator();
g_strSeparatorContent = strOldSeparatorContent;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvDisplayingRecipe(recipeId_) {
if (typeof g_recipeId !== 'undefined') {
return g_recipeId === recipeId_;
}
return false;
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvAddRecipeMenuItems(params_) {
var theMenu = params_.menu,
arrRecipes = params_.arrRecipes,
tmpInitialIsPinnedValue = params_.initialIsPinnedValue,
strMenuSeparatorRowId = params_.menuSeparatorRowId,
tmpHideSeparator = params_.hideSeparator,
tmpRecipeCount = (arrRecipes || []).length,
idxRecipe;
pvAddSeparatorToMenu({
menu: theMenu,
rowId: strMenuSeparatorRowId,
hideRow: tmpHideSeparator
});
if (tmpRecipeCount) {
for (idxRecipe = 0; idxRecipe < tmpRecipeCount; ++idxRecipe) {
var objRecipe = arrRecipes[idxRecipe],
tmpRecipeId = objRecipe.id,
tmpIsRecipeCurrentlyPinned =
pvIsRecipeCurrentlyPinned({
recipeId: tmpRecipeId,
originalIsPinnedValue: tmpInitialIsPinnedValue
}),
strPinUnpinButtonHtml =
pvBuildPinUnpinButtonHtml({
recipeId: tmpRecipeId,
isPinned: tmpIsRecipeCurrentlyPinned
}),
strRecipeUrl = pageRecipe + 'id=' + tmpRecipeId,
tmpDisplayingCurrentRecipe =
pvDisplayingRecipe(tmpRecipeId),
strCheckmarkPrefixHtml =
tmpDisplayingCurrentRecipe ?
cdBuildFontIconElem({
fontId: FontIconId_Enum.fiiCheck,
additionalFontIconClasses: 'marginRightSmall',
terseFontIcon: 1
}) :
'',
strMenuItemHtml =
'' +
'' +
'' +
'| ' +
strCheckmarkPrefixHtml +
htmlEncode(objRecipe.name) +
' | ' +
'' + strPinUnpinButtonHtml + ' | ' +
'
' +
'' +
'
';
theMenu.AddMenuItemP({
menuItemId: pvRecipeMenuItemId(tmpRecipeId),
itemHTML:
"" +
strMenuItemHtml +
"",
doubleQuoteReadyScript: "window.location='" + strRecipeUrl + "';return false;"
});
}
}
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvAddOptionsToRecipeSubMenu(params_) {
ConsoleLogging.logBlockOpen('pvAddOptionsToRecipeSubMenu()');
var theMenu = params_.menu,
tmpZuId = params_.zuId,
objLastMyMenuResult = g_lastMyMenuResult,
//arrZus = objLastMyMenuResult.arrZus,
//objZu = arrZus.find(function (zu_) {
// return zu_.id === tmpZuId;
//}),
arrPinnedRecipes =
objLastMyMenuResult.mapZuToPinnedRecipes[tmpZuId],
tmpPinnedRecipeCount = (arrPinnedRecipes || []).length,
arrRecentRecipes =
objLastMyMenuResult.mapZuToRecentRecipes[tmpZuId],
tmpRecentRecipeCount = (arrRecentRecipes || []).length;
theMenu.AddHTMLTitledLinkItem(
'All Recipes',
pageRecipes + 'zuId=' + tmpZuId);
pvAddRecipeMenuItems({
menu: theMenu,
arrRecipes: arrPinnedRecipes,
initialIsPinnedValue: 1,
menuSeparatorRowId: PINNED_ITEMS_SEPARATOR_ID,
hideSeparator: !tmpPinnedRecipeCount
});
pvAddRecipeMenuItems({
menu: theMenu,
arrRecipes: arrRecentRecipes,
menuSeparatorRowId: RECENT_ITEMS_SEPARATOR_ID,
hideSeparator: !tmpRecentRecipeCount
});
ConsoleLogging.logBlockClose();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function ptShowRecipeSubMenu(event, zuId_) {
var theMenu = new ContextMenu('clsMyMenu');
pvAddOptionsToRecipeSubMenu({
menu: theMenu,
zuId: zuId_
});
theMenu.ShowSubmenu(event, 'zusSubMenu_' + zuId_);
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvAddRecipeSubmenu(params_) {
ConsoleLogging.logBlockOpen('pvAddRecipeSubmenu()');
var objZu = params_.zu,
theMenu = params_.menu,
tmpZuId = objZu.id,
tmpIsSelected =
typeof g_zuId !== 'undefined' &&
g_zuId === tmpZuId &&
(g_wp === WebPages_Enum.wpRecipes || g_wp === WebPages_Enum.wpViewRecipe),
strStyles =
'text-align:right;display:block' +
tmpIsSelected ? ';font-weight:bold' : '',
strSelIconHtml =
tmpIsSelected ?
cdBuildFontIconElem({
fontId: FontIconId_Enum.fiiCheck,
terseFontIcon: 1,
additionalFontIconClasses: 'marginRightSmall'
}) :
'',
strMenuJS =
'SZMyMenu.PROTECTED.showRecipeSubMenu(event,' + tmpZuId + ')';
theMenu.AddMenuItemP({
itemHTML: '' +
strSelIconHtml +
'Recipes (' + htmlEncode(objZu.name) + ' - ' + objZu.recipeCount + ')' +
'',
isSubmenu: 1,
doubleQuoteReadyScript: strMenuJS
});
ConsoleLogging.logBlockClose();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvRSCallbackGetMonthlyTabDelimitedList(json_) {
var strTableHtml = json_.tableHtml;
showDialogP(
cdBuildTextAreaFieldRowP(
'txtTDL',
'',
{
labelAbove: 1,
unencodedText: strTableHtml,
fieldId: 'txtTDL',
autofocus: 1,
textAreaClasses: 'largeTextArea'
}),
'frmTDLMonthly',
{
formTitle: 'Tab-Delimited List of Monthly Funding Targets',
focusFieldName: 'txtTDL',
focusFieldOnMobile: 1,
hideOkButton: 1
});
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function ptBuildMonthlyTabDelimitedList() {
jsrsExecuteWithErrorP(
'Admin_GetMonthlyTabDelimitedList', // commandString_
pvRSCallbackGetMonthlyTabDelimitedList, // fnCallback_
'Getting Menu Details', // doingWhat_
{
zuId: g_zuId
}); // payload
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pvRSCallbackGetMyMenuDetails(json_, optionsHolder_) {
var originalOptions = optionsHolder_.originalOptions,
theMenu = new ContextMenu('clsMyMenu'),
arrZus = json_.arrZus,
tmpIsSelected,
strBoldStyle,
arrDogs = json_.arrDogs,
tmpDogCount = arrDogs.length,
objDog,
objZu,
i;
g_lastMyMenuResult = json_;
theMenu.AddHTMLTitledScriptItem(
'' + getRawFontId(FontIconId_Enum.fiiX) + ';
',
'hideDialog()');
theMenu.AddSeparatorIfNecessary();
if (g_wp === WebPages_Enum.wpAccounting) {
theMenu.AddHTMLTitledScriptItem(
'Tab-Delimitted List Of Monthly Values...',
'SZMyMenu.PROTECTED.buildMonthlyTabDelimitedList()');
theMenu.AddSeparatorIfNecessary();
}
// Add links to Zus with recipes...
for (i = 0; i < arrZus.length; ++i) {
objZu = arrZus[i];
if (objZu.recipeCount) {
pvAddRecipeSubmenu({
zu: objZu,
menu: theMenu
});
}
}
theMenu.AddSeparatorIfNecessary();
for (i = 0; i < tmpDogCount; ++i) {
objDog = arrDogs[i];
tmpIsSelected =
typeof g_dogId !== 'undefined' &&
g_dogId === objDog.dogId;
strBoldStyle = tmpIsSelected ? 'font-weight:bold;' : '';
theMenu.AddHTMLTitledLinkItem(
'' +
(tmpIsSelected ?
'' + getRawFontId(FontIconId_Enum.fiiCheck) + ';' :
'') +
htmlEncode(objDog.dogName) + ' (The Dog)' +
'',
pageDogDetail + '' + objDog.dogId);
}
theMenu.AddSeparatorIfNecessary();
pvAddShoppingListsToMenu(theMenu);
theMenu.AddSeparatorIfNecessary();
theMenu.AddMenuItemP({
rawText: 'Zus',
isSubmenu: 1,
doubleQuoteReadyScript: 'SZMyMenu.PROTECTED.showZusSubMenu(event,' + originalOptions.zuId + ')'
});
theMenu.Show(null/*event*/, originalOptions.menuPos.x/*forcePosX_*/, originalOptions.menuPos.y/*forcePosY_*/);
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbShowNavMyMenu(event, zuId_) {
var objMenuPos = { y: eventPageY(event), x: eventPageX(event) };
jsrsExecuteWithErrorP(
'Admin_GetMyMenuDetails', // commandString_
rsCallbackHandleStandardJSONResponse, // fnCallback_
'Getting Menu Details',
{}, // payload
{
zuId: zuId_,
menuPos: objMenuPos,
fnOnSuccess: pvRSCallbackGetMyMenuDetails
}); // options
}
//--------------------------------------------------------------------------
// SZMyMenu
//--------------------------------------------------------------------------
return {
showNavMyMenu: pbShowNavMyMenu,
//----------------------------------------------------------------------
//----------------------------------------------------------------------
PROTECTED: {
buildMonthlyTabDelimitedList: ptBuildMonthlyTabDelimitedList,
showZusSubMenu: ptShowZusSubMenu,
showRecipeSubMenu: ptShowRecipeSubMenu,
handlePinClick: ptHandlePinClick
}
};
}();
/* eslint no-unused-vars: "off", eqeqeq: "off", no-useless-assignment: "off",
no-empty: "off", no-dupe-else-if: "off", no-use-before-define: "off",
no-eval: "off", no-alert: "off", no-global-assign: "off", no-self-assign: "off",
no-useless-escape: "off", no-dupe-keys: "off", no-constant-condition: "off",
no-unreachable: "off" */
/*global
// ClientFunctions.js
buildRemoveFileLink
enableDialogButtons
formatFileSize
g_arrFileDragDropFileInfos
g_hasFileDragDropError
g_outstandingFileUploads
hideDialog
// ConsoleLogging.js
ConsoleLogging
// SharedClientFunctions.js
htmlMultilineEncode
htmlEncode
// ShopSharedFullFunctions.js
hideTimedMessage
refreshPageAndScrollPos
// ShopSharedFunctions.js
getObj
mjtElemData
*/
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
var SZUploadSupport = function () {
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
/*global
g_disableFileDragDrop
g_nextDragDropFileId
*/
function pvSZAdvanceToNextFileIfNecessary(fnProcessNextFile_, fnCompletedProcessing_) {
ConsoleLogging.logBlockOpen('SZUploadSupport.pvSZAdvanceToNextFileIfNecessary()');
--g_outstandingFileUploads;
ConsoleLogging.logMessage('After decrement, g_outstandingFileUploads=' + g_outstandingFileUploads);
if (g_outstandingFileUploads <= 0) {
// No files left to upload...
ConsoleLogging.logMessage('No files left. Cleaning up.');
g_disableFileDragDrop = false;
if (g_hasFileDragDropError) {
// There was an error, so just re-enable the dialog.
enableDialogButtons();
} else {
// No errors uploading, so cleanup and either refresh the page, or if there's a finalizer, invoke it.
g_arrFileDragDropFileInfos = [];
g_nextDragDropFileId = 1;
g_outstandingFileUploads = 0;
g_hasFileDragDropError = false;
g_disableFileDragDrop = false;
if (!fnCompletedProcessing_) {
ConsoleLogging.logMessage('No fnCompletedProcessing_() function, so just refreshing.');
hideTimedMessage();
hideDialog();
refreshPageAndScrollPos();
}
}
if (typeof fnCompletedProcessing_ === 'function') {
ConsoleLogging.logMessage('There is a finalizer. Invoking it...');
fnCompletedProcessing_();
}
} else if (typeof fnProcessNextFile_ === 'function') {
// Process the next file in the list.
ConsoleLogging.logMessage('Processing the next file in the list.');
fnProcessNextFile_();
}
ConsoleLogging.logBlockClose();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
function pbSZUploadFile(fileInfo_, fnProcessNextFile_, uploadForm_, fnOnSuccess_, fnOnError_, fnCompletedProcessing_) {
ConsoleLogging.logBlockOpen('pbSZUploadFile()');
if (fileInfo_.alreadyHandled) {
pvSZAdvanceToNextFileIfNecessary(fnProcessNextFile_, fnCompletedProcessing_);
ConsoleLogging.logBlockClose('Advanced to next file.');
return;
}
var theForm = uploadForm_,
xhr = new XMLHttpRequest(),
formData = new FormData(),
fileRow = getObj('dragDropFileSection' + fileInfo_.id),
file = fileInfo_.file,
strFieldName,
strFieldValue,
strAttrDataTypes = theForm.attrDataTypes ? theForm.attrDataTypes.value : '',
arrAttrDataTypes = strAttrDataTypes.split('?'),
strAttrTypes = theForm.attrTypes ? theForm.attrTypes.value : '',
arrAttrTypes = strAttrTypes.split(','),
objFormElemData = mjtElemData(theForm, 'formElemData'),
arrSZFileUploadNameValuePairs =
objFormElemData ?
objFormElemData.arrSZFileUploadNameValuePairs :
null,
tmpFormValCount = (arrSZFileUploadNameValuePairs || []).length || 0,
idxFormVal,
objFormVal,
strFormValName,
strFormValValue,
dictAttrInfos = {},
idxAttrType,
strAttrType,
tmpAttrTypeId,
strAttrDataType,
tmpAttrDatatypeId;
// First, build a map of attribute type ids to data type ids.
for (idxAttrType = 0; idxAttrType < arrAttrTypes.length && idxAttrType < arrAttrDataTypes.length; ++idxAttrType) {
strAttrType = arrAttrTypes[idxAttrType];
strAttrDataType = arrAttrDataTypes[idxAttrType];
if (strAttrType && strAttrDataType) {
// Make sure that there is both an attribute type and a corresponding attribute data type.
tmpAttrTypeId = parseInt(strAttrType, 10);
tmpAttrDatatypeId = parseInt(strAttrDataType, 10);
dictAttrInfos['k' + tmpAttrTypeId] = tmpAttrDatatypeId;
}
}
xhr.open('POST', theForm.action, true);
formData.append('fileName', fileInfo_.file);
ConsoleLogging.logObject({
what: 'About to process name/value pairs',
arrSZFileUploadNameValuePairs:
ConsoleLogging.undefinedStringIfUndefined(
arrSZFileUploadNameValuePairs)
});
for (idxFormVal = 0; idxFormVal < tmpFormValCount; ++idxFormVal) {
objFormVal = arrSZFileUploadNameValuePairs[idxFormVal];
formData.append(
objFormVal.formFieldName,
objFormVal.formFieldValue);
ConsoleLogging.logMessage(
'Just added form data #' + idxFormVal + ': ' + JSON.stringify({ name: objFormVal.formFieldName, value: objFormVal.formFieldValue }));
}
// Send the rest of the form data
var inputTypes = ['select', 'input'];
for (var idxFileFormFieldType = 0; idxFileFormFieldType < inputTypes.length; ++idxFileFormFieldType) {
var inputs = theForm.getElementsByTagName(inputTypes[idxFileFormFieldType]),
i;
for (var idxFormField = 0; idxFormField < inputs.length; ++idxFormField) {
if (inputs[idxFormField].type !== 'file') {
strFieldName = inputs[idxFormField].name;
strFieldValue = inputs[idxFormField].value;
//if (strFieldName.indexOf('attrVal') === 0) {
// tmpAttrTypeId = parseInt(strFieldName.substring('attrVal'.length), 10);
// tmpAttrDatatypeId = dictAttrInfos['k' + tmpAttrTypeId];
//
// if (tmpAttrDatatypeId == AttributeDataTypes_Enum.EnterDate) {
// // Canonicalize the date
// strFieldValue = getDateForUrlParam(strFieldValue);
// }
//}
formData.append(strFieldName, strFieldValue);
}
}
}
if (fileRow) {
fileRow.innerHTML = file.name + ' (' + formatFileSize(file.size) + ') Uploading...';
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
ConsoleLogging.logBlockOpen('pbSZUploadFile()::xhr.onreadystatechange()');
var strErrorHTML = '';
if (xhr.status === 200) {
ConsoleLogging.logMessage('status==200');
var strResponse = xhr.responseText,
objRC = null;
try {
objRC = JSON.parse(strResponse);
if (objRC.error) {
strErrorHTML = 'An error occurred uploading the file, "' + htmlEncode(file.name) + '":
\n';
if (objRC.error.message) {
strErrorHTML += htmlMultilineEncode(objRC.error.message);
}
if (objRC.error.stackTrace) {
strErrorHTML += '
\n' + htmlMultilineEncode(objRC.error.stackTrace);
}
} else if (!objRC.success) {
strErrorHTML = htmlMultilineEncode('Upload failed:\n' + strResponse);
}
} catch (e) {
strErrorHTML = htmlMultilineEncode('Upload failed:\n' + strResponse);
}
if (!strErrorHTML) {
if (fnOnSuccess_) {
fnOnSuccess_(file, xhr, objRC);
} else {
// Update the file row
if (fileRow) {
fileRow.innerHTML = file.name + ' (' + formatFileSize(file.size) + ') Upload complete';
// Mark this file as already uploaded so it won't be uploaded again
// if there was an error with another file and the user tries again.
fileInfo_.alreadyUploaded = 1;
}
}
}
} else {
ConsoleLogging.logMessage('Upload failed. status=' + xhr.status);
strErrorHTML = 'Upload failed, please retry.';
}
if (strErrorHTML) {
if (fnOnError_) {
fnOnError_(file, xhr);
} else {
g_hasFileDragDropError = true;
if (fileRow) {
fileRow.innerHTML = file.name + ' (' + formatFileSize(file.size) + ') ' + buildRemoveFileLink(fileInfo_.id) +
'' + strErrorHTML + '
';
}
}
}
//if (!fnOnError_ && !fnOnSuccess_) {
pvSZAdvanceToNextFileIfNecessary(fnProcessNextFile_, fnCompletedProcessing_);
//}
ConsoleLogging.logBlockClose();
}
};
xhr.send(formData);
ConsoleLogging.logBlockClose();
}
//--------------------------------------------------------------------------
//--------------------------------------------------------------------------
return {
szUploadFile: pbSZUploadFile,
PROTECTED: {
}
};
}();