// Passive model should derive from IHS.Model.BaseModel. E.g. any data entity which just hold data, not logic.
im.define('IHS.Model.BaseModel', null,
{
init: function () {
this.parseParameters();
},
parseParameters: function () {
var p = this._params;
for (var i in p) {
if (typeof (this[i]) !== 'undefined') {
this[i] = p[i];
}
}
}
}
);
im.define('IHS.Model.BaseObservableModel', { 'baseClass': IHS.Model.BaseModel }, {
observers: null,
addObserver: function (observer) {
if (this.observers == null) {
this.observers = [];
}
if (!this.isObserverAttached(observer)) {
this.observers.push(observer);
}
},
removeObserver: function (observer) {
if (this.observers) {
for (var i = 0, n = this.observers.length; i < n; i++) {
if (this.observers[i] == observer) {
this.observers.splice(i, 1);
}
}
}
},
notify: function (data) {
if (this.observers) {
if (typeof (data) === 'string')
data = { topic: data };
data.initiator = this;
for (var i = 0, n = this.observers.length; i < n; i++) {
var o = this.observers[i];
if (o) {
o.onNotify(data);
}
}
data.initiator = null;
}
},
onNotify: function (data) {
this.notify(data); // Retranslate
},
isObserverAttached: function (observer) {
for (var i = 0, n = this.observers.length; i < n; i++) {
if (this.observers[i] === observer) return true;
}
return false;
}
});
///
// Active model with logic should derive from IHS.Model.BaseActiveModel.
// Activation/deactivation is used for models which are unit models like Dashboard and FactFinder.
// Unit model switching is implemented in Application model in setActiveModel method which triggers activeModelChanged event to notify Application level controller about active model change.
im.define('IHS.Model.BaseActiveModel', { 'baseClass': IHS.Model.BaseObservableModel },
{
_this: null,
name: '', // Unique name of the model, controllers can be attached to models using this name in im.register
displayName: '', // Can be shown in e.g. browser title
alias: null,
isLoading: null, // Data loading state
isActive: null,
isActivated: false,
isError: null,
error: null,
settings: null,
settingsSectionName: '',
useSettingsCache: false,
init: function () {
this._this = $(this);
IHS.Model.BaseActiveModel.superclass.init.call(this);
},
activate: function (data) { // Loads model data from server or memory
this.isActive = true;
this._this.trigger('onActivate'); // Deprecated
this.notify({ topic: 'onActivate' });
},
deactivate: function () { // Clears model making it act like a proxy when the model object is required but data cleared to save memory usage
this.isActive = false;
this.setIsLoading(false);
this._this.trigger('onDeactivate'); // Deprecated
this.notify({ topic: 'onDeactivate' });
im.resolve('commands').invoke(this.name + '.deactivate');
},
deactivated: function () {
this._this.trigger('onDeactivated'); // Deprecated
this.notify({ topic: 'onDeactivated' });
},
activated: function () {
this.isActivated = true;
this._this.trigger('onActivated'); // Deprecated
this.notify({ topic: 'onActivated' });
},
mergeSettings_fromCache: function (sectionNames) {
var settings = im.resolve("settings");
var parts = this.settingsSectionName.split(';');
for (var i = 0; i < parts.length; i++) {
var sectionName = parts[i].split(".")[0];
var section = settings.getCached(sectionName);
if (!section)
return false; // Section is not in cache. Let's reload it.
var values = parts[i].split(".")[1];
if (values) {
values = values.split(",");
for (var j = 0; j < values.length; j++) {
if (section[values[j]] === undefined)
return false; // Requested value is not in section. Let's reload it.
}
}
if (!this.settings)
this.settings = {};
if (i == 0)
this.settings = section;
if (parts.length > 1) {
if (!this.settings.SettingsSections)
this.settings.SettingsSections = {};
this.settings.SettingsSections[sectionName] = section;
}
}
return true;
},
activateWithSettings: function (data) {
var settings = im.resolve('settings');
if (!settings || !this.settingsSectionName) {
this.activate(data); // Normal activate
}
else {
var o = {};
// Support multisection settings.
var parts = this.settingsSectionName.split(';');
for(var i = 0; i < parts.length; i++) {
// Now it is allowed to pass Settings Keys together with Section separated by '.' and ','.
// For example: settingsSectionName='ITA.Ref_Columns,Pat_Columns'
// This text shall cause to load only 'Ref_Columns' and 'Pat_Columns' keys from 'ITA' section.
var sectionName = parts[i].split('.')[0];
var sectionKeys = parts[i].split('.')[1];
if (sectionKeys)
o[sectionName] = sectionKeys.split(',');
else
o[sectionName] = [];
}
if (this.useSettingsCache && this.mergeSettings_fromCache(this.settingsSectionName)) {
// Settings are already on Client-side. No need to request them and caller thinks this is OK.
// So, let's activate this model without travelling to Server.
this.activate(data);
return;
}
var _this = this;
this.setIsLoading(true);
settings.get(o,
function (settings) {
try {
if (settings && settings.Settings) {
_this.settings = settings.Settings[parts[0].split('.')[0]];
// Support multisection settings.
if (parts.length > 1) {
if (!_this.settings)
_this.settings = {};
_this.settings.SettingsSections = {};
for (var i = 0; i < parts.length; i++) {
if (settings.Settings[parts[i]])
_this.settings.SettingsSections[parts[i]] = settings.Settings[parts[i]];
}
}
}
_this.setIsLoading(false);
_this.activate(data);
}
catch (e) {
im.trace(e.message);
if (im.isRegistered('commands')) im.resolve('commands').invoke('error.command', { e: e });
}
},
function () {
_this.setIsLoading(false);
try {
_this.activate(data);
}
catch (e) {
im.trace(e.message);
if (im.isRegistered('commands')) im.resolve('commands').invoke('error.command', { e: e });
}
}
);
}
},
setIsLoading: function (/*Boolean*/state, force) {
if (this.isLoading !== state || force) {
this.isLoading = state;
this._this.trigger('isLoadingChanged'); // Deprecated
this.notify({ topic: 'isLoadingChanged', state: state });
}
},
setIsError: function (/*Boolean*/state, force) {
if (this.isError !== state || force) {
this.isError = state;
this._this.trigger('isErrorChanged'); // Deprecated
this.notify({ topic: 'isErrorChanged', state: state });
}
},
onSuccess: function () {
this.error = null;
this.setIsError(false);
this.setIsLoading(false);
this.activated();
},
onError: function (jqXHR, textStatus, errorThrown) {
if (textStatus !== 'abort') { // Abort should not call error
this.error = IHS.Model.ErrorFactory.build(jqXHR, textStatus, errorThrown);
this.setIsError(true);
}
else {
this.setIsError(false);
}
this.setIsLoading(false);
this.activated();
},
getState: function () {
return new IHS.Model.State(null, {
// In order to be able to identify the model which has step saved in history,
// base model should assign new hash parameter to the id of the step object
hash: (this._params && (this._params.hash || this._params.hash === 0)) ? this._params.hash : null,
modelAlias: this.alias,
state: {
name: this.name,
isLoading: null,
isActive: this.isActive,
isError: null
}
}, true
);
},
setState: function (state) {
if (!state) throw new IHS.Model.ArgumentException(null, { message: 'state is null' }, true);
if (!this._params) this._params = {};
// In order to be able to identify the model which has step saved in history,
// base model should assign new hash parameter to the id of the step object
this._params.hash = state.hash;
if (state.modelAlias)
this.alias = state.modelAlias;
$.extend(true, this._params, state.state);
this.parseParameters();
},
saveStepInHistory: function (params) {
im.resolve('commands').invoke('history.save', params);
},
unlinkHistoryStep: function () {
if (this._params) {
this._params.hash = null;
}
},
setChildrenState: function (/*IHS.Model.State*/state, /*Function*/onEachChild) {
if (state && state.children) {
for (var i = 0, n = state.children.length; i < n; i++) {
var modelState = state.children[i];
if (modelState && onEachChild) {
onEachChild(modelState);
}
}
}
}
// event isLoadingChanged [when the model busy state is changed, busy state is usually used to notify controller to show progress indicator]
// event isErrorChanged [when the model is in error state or was recovered]
// event onActivated [when the model activation finished]
// event onDeactivated [when the model deactivation finished]
// event onActivate [when the model activation started]
// event onDeactivate [when the model deactivation started]
}
);
///
// Services is a model level abstraction which implement several common level logic like repository, history, state, help, trace and so on.
// The base class for all the services is IHS.Model.BaseService.
// Available services are configured in bootstrapper.
im.define('IHS.Model.BaseService', { 'baseClass': IHS.Model.BaseObservableModel },
{
// The most base members
}
);
///
im.define('IHS.Model.BaseException', { 'baseClass': IHS.Model.BaseModel },
{
message : ''
}
);
im.define('IHS.Model.ErrorFactory', null, null, { 'static': {
build: function (jqXHR, textStatus, errorThrown) {
if (jqXHR && jqXHR.responseText) {
im.trace(jqXHR.responseText);
}
var message = null, errStruct = null;
if (jqXHR && jqXHR.responseText) {
try {
errStruct = $.parseJSON(jqXHR.responseText);
}
catch (e) { }
}
if (errStruct) {
switch (errStruct.errorCode) {
case 802: message = imcon.jsres['AS_QuerySyntaxExceptionCombine'];
break;
}
}
return { message: message || errorThrown || imcon.jsres['InternalClientError'], xhr: jqXHR }
}
}});
///
// Command is a piece of shared functionality which can be replaced from application to application.
// Available commands are configured in bootstrapper.
// The base class for all commands is IHS.Model.Command.
// It is recommented to call commands via CommandService wrapper, not directly.
im.define('IHS.Model.Command', { 'baseClass': IHS.Model.BaseObservableModel },
{
_app: null,
execute: function (params) {
},
canExecute: function (params) {
return false;
},
setApplication: function (app) {
this._app = app;
},
removeApplication: function () {
this._app = null;
}
}
);
im.define('IHS.Model.Commands.ActivationCommand', { 'baseClass': IHS.Model.Command },
{
token: null,
returnValue: null,
doActivation: function(params, appObj)
{
var app = appObj || this._app;
var activateIn = IHS.Model.ActivateIn;
var stateType = IHS.Model.StateType;
var activation = im.resolve('activation');
switch (activation.ofType(this.token)) {
case activateIn.Dialog:
{
// Check if the model needs to be activated in the opened dialog
var d = im.resolve('dialog').getTop();
if (d && app && app.sandboxName === 'dialog' && d.sandboxName === app.sandboxName) {
// Activate in exisitng dialog
app.activateModel(activation.map(this.token), params);
}
else {
// Activate in new dialog
im.resolve('dialog').activate($.extend(true, { 'modelToActivate': this.token, 'returnValue': this.returnValue }, params));
}
break;
}
default:
{
var alias = activation.map(this.token);
switch (activation.ofState(this.token)) {
case stateType.Shared:
// If state sharing is enabled, it means that when you want to activate a model
// activation service will try to find existing state for the model with the same alias
var history = im.resolve('history');
if (!history) throw new IHS.Model.ArgumentException(null, { message: 'Shared activation type requires History Service' }, true);
var hash = history.findByAlias(alias);
if (hash || hash === '') {
history.onHistoryChange(hash, true);
}
else {
// Or activate as usual if no state was found
if (app.unlinkHistoryStep) {
app.unlinkHistoryStep();
}
app.activateModel(alias, params);
}
break;
default:
if (app.unlinkHistoryStep) {
app.unlinkHistoryStep();
}
app.activateModel(alias, params);
break;
}
}
}
},
execute: function (params) {
if (this.canExecute(params)) {
var simos = im.resolve('simosService');
var appObj = this._app;
var activation = im.resolve('activation');
if (simos &&
(!appObj.activeModel || appObj.activeModel.alias !== activation.map(this.token) || appObj.activeModel.appActivationToken != this.token) // avoid re-check(IN/OUT) if model is already active
)
{
simos.activateTool
(
this.token,
$.proxy
(
function(){this.doActivation(params, appObj);}, // successfull check-out
this
)
);
}
else
this.doActivation(params);
}
},
canExecute: function () {
return this._app && im.resolve('activation').hasMap(this.token);
}
}
);
im.define('IHS.Model.Commands.SetAlert', { 'baseClass': IHS.Model.Command },
{
token: null,
execute: function (params) {
if (this.canExecute(params)) {
var p = {
Assignees: params.qzState.Assignees,
Query: params.qzState.Query,
originElement: params.originElement
};
if (typeof (this._app.activeModel._prepareParams) === "function") {
var itaQuery = this._app.activeModel._prepareParams(true);
if (itaQuery && typeof (itaQuery.toResearcherRequest) === "function")
p.Request = itaQuery.toResearcherRequest();
p.FullQuery = params.qzState.FullQuery;
p.Tool = p.Request.ParentTool;
}
p.Pgn = params.qzState.Pgn;
p.Request.KnowledgeBases = p.Request.Scope.Items.Where({ field: "Type", value: 1 }).Select({ field: "Id" });
delete p.Request.Scope;
delete p.Request.Query;
delete p.Request.Lang;
p.Request.CState = { Page: [{ Count: 5, From: 0 }] };
p.Request.RenewCache = 1;
p.Request.ExpandSnippet = {
ByFields: {
Count: 10,
Fields: ["ET0", "AU", "DP", "ORGAU", "JRN", "CPR", "PA", "ISEDS", "DOCCLASS", "ISEN"] //, "ISEGID", "AB"
}
};
im.resolve("ewbApp").$rootScope.$emit('onSaveQueryAlertDialogRequested', p);
}
},
canExecute: function (params)
{
return true;
}
}
)
im.define('IHS.Model.Commands.TranslationCommand', { 'baseClass': IHS.Model.Command },
{
execute: function (params) {
im.resolve("dialog").activate({ modelToActivate: "translation-model", paramsToActivate: params });
},
canExecute: function (params) {
return true;
}
}
);
im.define('IHS.Model.Commands.FilterFinderCommand', { 'baseClass': IHS.Model.Command },
{
map: {
'DATE-FILTER' : { type: 10, model: "calendar-model", mergeBy: " - ", not_split_input: true }
},
models: null,
// params is a structure with the following fields:
// filter structure that shall have
// name name of Filter: 'MUC', 'UC', 'MC', etc. Must be defined.
// value current value that shall be passed to dialog. Optional.
// mergeBy shall be used for merging values. If not specified, it assumed as " ".
// onReturn callback method that will be invoked with results.
// res structure with results
// raw results from dialog without processing. Usually a list of strings.
// merged results merged into one string divided by mergeBy parameter.
execute: function (params) {
var f = params.filter;
var fe = this.map[f.command.mapKey] || this.map[f.name];
var mergeBy = params.mergeBy != null ? params.mergeBy : (fe.mergeBy ? fe.mergeBy : " ");
var q = f.value || '';
// Use first item in list for search
if (q && q.length > 0 && fe.not_split_input != true)
q = q.split(mergeBy)[0];
//ga analytics
this.sendAmalytics(fe.type);
// Bug DE24467. Dialog closed by hashchange.imcon event.
// We should define small timeout.
var _this = this;
setTimeout(function () {
im.resolve('dialog').activate(
{
modelToActivate: fe.model,
originElement: params.originElement,
paramsToActivate: {
searchData: {
Type: fe.type,
Query: q,
allowBackButton: params.allowBackButton
},
wizardState: params.wizardState
},
models: _this.models,
onReturn: function (r) {
if (params.onReturn) {
var res = { raw: r, filter: f };
if (r && r.length != undefined)
res.merged = r.join(mergeBy);
params.onReturn(res);
}
},
returnValue: "returnData"
});
}, 100);
},
canExecute: function (params) {
return (params && params.filter && ((params.filter.command && this.map[params.filter.command.mapKey]) || this.map[params.filter.name]));
},
sendAmalytics: function (type) {
// fe.type <= 1 see ITAFilterCommand
if (type <= 1) {
this.analyticsFindAssigneeGroup();
}
},
analyticsFindAssigneeGroup: function() {
im.resolve('commands').invoke("track-activity",
{
Context: imcon.jsres.AnalyticsCategorySelectAssigneeDialog,
Action: imcon.jsres.AnalyticsActionInvokeSelectAssigneeDialog
});
}
}
);
im.define('IHS.Model.Commands.SaveHistoryStepCommand', { 'baseClass': IHS.Model.Command },
{
execute: function (params) {
if (this.canExecute(params)) {
var history = im.resolve('history');
return history.saveStepInHistory(params);
}
},
canExecute: function (params) {
return this._app && im.isRegistered('history');
}
}
);
im.define('IHS.Model.Commands.RestoreHistoryStepCommand', { 'baseClass': IHS.Model.Command },
{
execute: function (params) {
if (this.canExecute(params)) {
var state = params.state;
if (state) {
try {
this._app.setState(state);
}
catch (e) {
im.trace('RestoreHistoryStepCommand: can\'t set step ' + e.message);
if (im.isRegistered('commands')) im.resolve('commands').invoke('error.command', { e: e });
}
}
}
},
canExecute: function (params) {
return this._app && im.isRegistered('history');
}
}
);
im.define('IHS.Model.Commands.SelectKBsCommand', { 'baseClass': IHS.Model.Command },
{
execute: function (params) {
var extra = $.extend(true, {},
{
modelToActivate: "selectkbs-model",
paramsToActivate: params
});
im.resolve("dialog").activate(extra);
},
canExecute: function (params) {
return true;
}
}
);
///
im.define('IHS.Model.Services.Command', { 'baseClass': IHS.Model.BaseService },
{
defaultSandbox: 'app',
invoke: function (name, params, sandboxName) {
var c = im.resolve(name, null, params);
if (c) {
var p = params || {};
try {
c.setApplication(IHS.Model.Sandbox.get(sandboxName || this.defaultSandbox) || IHS.Model.Sandbox.get(this.defaultSandbox));
if (c.canExecute(p)) {
c.addObserver(this);
c.execute(p);
c.removeObserver(this);
}
c.removeApplication();
}
catch (e) {
im.trace(e.message);
if (im.isRegistered('commands')) im.resolve('commands').invoke('error.command', { e: e });
}
}
},
canInvoke: function (name, params, sandboxName) {
var c = im.resolve(name, null, params);
if (c) {
var p = params || {};
try {
c.setApplication(IHS.Model.Sandbox.get(sandboxName || this.defaultSandbox) || IHS.Model.Sandbox.get(this.defaultSandbox));
var b = c.canExecute(p);
c.removeApplication();
}
catch (e) {
im.trace(e.message);
if (im.isRegistered('commands')) im.resolve('commands').invoke('error.command', { e: e });
}
return b;
}
return false;
},
onNotify: function (d) {
$(this).trigger(d.topic, d.data); // Deprecated
IHS.Model.Services.Command.superclass.onNotify.call(this, d);
}
}
);
///
im.define('IHS.Model.ArgumentException', { 'baseClass': IHS.Model.BaseException },
{
}
);
im.define('IHS.Model.Commands.DeactivationCommand', { 'baseClass': IHS.Model.Command },
{
token: null,
execute: function (params) {
if (this.canExecute(params)) {
var ActivateIn = IHS.Model.ActivateIn;
var activation = im.resolve('activation');
switch (activation.ofType(this.token)) {
case ActivateIn.Dialog:
im.resolve('dialog').deactivate();
break;
default:
break;
}
}
},
canExecute: function (params) {
return this._app && im.resolve('activation').hasMap(this.token);
}
}
);
im.define('IHS.Model.Commands.ErrorCommand', { 'baseClass': IHS.Model.Command },
{
isDebug: false,
execute: function (params) {
if (this.canExecute(params)) {
if (this.isDebug && params.e) {
if (!params.e.rethrown) {
params.e.rethrown = true;
throw params.e;
}
else {
return; // Ignore rethrown exception
}
}
// Close dialogs because it can be JavaScript error inside dialog
if (im.isRegistered('dialog')) {
var d = im.resolve('dialog');
for (var i = 0, n = d.getLength(); i < n; i++) {
d.deactivate();
}
}
this._app.activeModel.error = params.e ? params.e : { message: imcon.jsres['InternalClientError'] };
this._app.activeModel.setIsError(true);
this._app.activeModel.setIsLoading(false);
if (im.isRegistered('log-loader')) {
im.resolve('log-loader').post(this._app.activeModel.error.message);
}
}
},
canExecute: function (params) {
return this._app && this._app.activeModel && params && params;
}
}
);
im.define('IHS.Model.Commands.ExportArtifacts', { 'baseClass': IHS.Model.Command },
{
token: null,
execute: function (params) {
var data;
if (!params.Patent) {
data = {
rawReq: {
QueryInfo: {
Untyped: JSON.stringify({
queryZoneState: this._app.queryZone.activeState.toState()
}),
Ita: params.Model.buildRequest(params.Model.query.toRequest(), params.Model.query, true)
},
Name: params.Name,
Tags: [
{ Type: 0, Id: 2 /* ITAModule */ },
{ Type: 1, Id: params.SubModule },
{ Type: 2, Id: params.SubType },
{ Type: 3, Id: params.SubMode }
],
Range: params.Range,
HorizontalResolution: im.Scroll.getDPI().x,
VerticalResolution: im.Scroll.getDPI().y
},
Model: params.Model,
Svg: params.Svg,
SingleItem: params.SingleItem,
type: params.type,
originElement: params.originElement
};
} else {
data = {
rawReq: {
QueryInfo: {
Ita: params.Model.query
? params.Model.query.toRequest ? params.Model.query.toRequest() : params.Model.query
: null
},
SipId: params.SipId,
BiblioOnly: params.type == 'biblio',
isPatent: true,
Sentences: params.Model.query ? params.Model.query.Sentences : null
},
SingleItem: true,
originElement: params.originElement
};
}
im.resolve("ewbApp").$rootScope.$broadcast('openExportItaDialog', data);
//im.resolve('dialog').activate(
// {
// 'modelToActivate': 'ita-export-model',
// 'paramsToActivate': data
// });
},
canExecute: function () {
return true;
}
}
);
im.define('IHS.Model.Commands.HelpCommand', { 'baseClass': IHS.Model.Command },
{
map: {},
execute: function (params) {
if (this.canExecute(params)) {
im.resolve('help').showHelp(this._getHelpId(this._getModelName()));
}
},
canExecute: function (params) {
return this.map && this._getHelpId(this._getModelName()) && im.isRegistered('help');
},
_getModelName: function () {
// Frist, request dialog service if currently active dialog has a special Help ID.
var topDialog = im.resolve("dialog").getTop();
if (topDialog && topDialog.activeModel && this.map[topDialog.activeModel.name])
return topDialog.activeModel.name;
// If no dialog or does not have Help ID, then proceed with underlying active view.
if (this._app && this._app.activeModel) {
return this._app.activeModel.getHelpId ? this._app.activeModel.getHelpId() || this._app.activeModel.name : this._app.activeModel.name;
}
return null;
},
_getHelpId: function (modelName) {
return this.map[modelName]; // TODO: set correct help ids for each model name in bootstrapper
}
}
);
im.define('IHS.GHC.Commands.ITASaveArtefactCommand', { 'baseClass': IHS.Model.Command },
{
execute: function (params) {
im.resolve("ewbApp").$rootScope.$broadcast('openSaveArtefactDialog', params);
},
canExecute: function (params) {
//return params && this._app && this._app.queryZone && this._app.queryZone.activeState;
return true;
}
}
);
im.define('IHS.Model.Commands.LogOffCommand', { 'baseClass': IHS.Model.Command },
{
execute: function (params) {
if (this.canExecute(params)) {
var data = {};
/*
var simos = im.resolve('simosService');
if (simos)
simos.deactivateTool('open-item-ita-command');
*/
var simos = im.resolve('simosCheckIn');
if (simos)
simos.post("");
var f = function()
{
var loginpost = [];
if(imcon.postdata)
loginpost = imcon.postdata.split('&');
if (imcon.method == 'POST' && loginpost.length)
{
var form = window.document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", imcon.urls.logout);
var addParam = function(name, value) {
var ff = window.document.createElement("input");
ff.value = value;
ff.type = 'hidden';
ff.name = name;
form.appendChild(ff);
};
$.each(loginpost, function (index, field)
{
if(field.split('=').length > 1)
addParam(field.split('=')[0], decodeURIComponent(field.split('=')[1].replace(/\+/g, ' ')));
});
document.body.appendChild(form);
form.submit();
return;
}
else
window.location = imcon.urls.logout;
};
im.resolve('commands').invoke('history.clear', { onSuccess: f, onError: f });
}
},
canExecute: function (params) {
return true;
}
}
);
im.define('IHS.Commands.OpenFulltextCommand', { 'baseClass': IHS.Model.Command },
{
mode: null,
execute: function (params) {
// ... params.QueryId;
if (this.canExecute(params)) {
var req = this.getRequest(params);
var queryId = params.QueryId;
var index = params.Index + 1;
if (this._app.queryZone && this._app.queryZone.activeState) {
req.Untyped = {
queryZoneState: this._app.queryZone.activeState.toState(),
queryZoneSettings: this._app.queryZone.getQZState ? this._app.queryZone.getQZState() : undefined
};
req.SubModule = params.SubModule;
req.SubMode = params.SubMode;
req.savedDataType = params.savedDataType;
req.SubType = params.SubType;
}
else
req.Untyped = { queryZoneState: params.state };
var params = IHS.Commands.OpenFulltextCommand.createDocumentFromItem(params.item, this.mode, req, queryId, index);
if (this.mode === 'pdf') {
var url = '#/patentview/' + params.Document.DocId,
originalTitle = params.Document.Number + ' ' + (params.Document.Title.Translated || params.Document.Title.Original),
translatedTitle = params.Document.Number + ' ' + params.Document.Title.Original;
angular.element('body').injector().get("RecentDocsService").SavePdfHistory(url, originalTitle, translatedTitle);
}
window.open($.views.helpers.openLink(params.Document.Url), '_blank');
//im.resolve('documentOpener').showDocument(IHS.Commands.OpenFulltextCommand.createDocumentFromItem(params.item, this.mode, req));
}
},
getRequest: function (params) {
var q = this._app && this._app.activeState ? this._app.activeState.query : null;
if (q) {
if (params.Model && params.Model.buildRequest)
return params.Model.buildRequest(q.toRequest(), q);
return q.toRequest();
}
return params.query || {};
},
canExecute: function (params) {
return params && params.item;
}
},
{
'static': {
createDocumentFromItem: function (dataItem, mode, request, queryId, index) {
var url;
switch (mode) {
case 'pdf':
url = IHS.Model.Data.Loader.makeEwbWaitUrl('api/patentview/checkpdf/' + dataItem.SipId + "-" + dataItem.id);
break;
case 'print':
url = IHS.Model.Data.Loader.makeUrl('patview', '' + dataItem.SipId + "," + dataItem.id) + "/print";
break;
case 'summary':
url = IHS.Model.Data.Loader.makeEwbUrl('patentview/' + dataItem.SipId, true);
break;
default:
url = IHS.Model.Data.Loader.makeEwbUrl('patentview/' + dataItem.SipId + '?qid=' + queryId + '&sr=ip-' + index + '-' + request.PageFilter.Count, true);
break;
}
return {
// 4 - SourceKind.GfiPatents
// 3 - DocumentTypes.Patent
Id: "4|{0}|{1}|3".netFormat(dataItem.SipId, dataItem.DocLanguage),
Document: {
DocId: dataItem.SipId,
Language: dataItem.DocLanguage,
Type: 3, // See DocumentOpener.js, getContentCategory()
Url: url,
Number: dataItem.PN,
Title: {
Original: dataItem.TTL,
Translated: dataItem.TTL_TRANS
}
},
Request: request
// TODO: add properties which allow to save and export from summary dialog
};
}
}
}
);
im.define('IHS.Model.Commands.OpenHelpCommand', { 'baseClass': IHS.Model.Command },
{
execute: function (params) {
im.resolve("ewbApp").$rootScope.$broadcast('rcaModalOpenHelp', params);
},
canExecute: function (params) {
return true;
}
}
);
im.define('IHS.Commands.OpenPrintPatentCommand', { 'baseClass': IHS.Model.Command }, {
execute: function (params) {
if (this.canExecute(params)) {
im.resolve('commands').invoke("document.open", {
'uri': IHS.Model.Data.Loader.makeUrl('patview', '' + params.item.SipId + "," + params.item.id) + "/print"
});
}
},
canExecute: function (params) {
return params && params.item;
}
});
im.define('IHS.Model.Commands.OpenUriCommand', { 'baseClass': IHS.Model.Command },
{
uri: '',
target: '',
name: 'openUri',
execute: function (params) {
this.notify({ topic: this.name, data: { 'target': this.target, 'uri': this.uri } });
},
canExecute: function (params) {
return !!this.uri;
}
}
);
im.define('IHS.Model.Commands.SelectCategory', { 'baseClass': IHS.Model.Command },
{
execute: function (data) {
im.resolve("ewbApp").$rootScope.$broadcast('selectCategory', data);
},
canExecute: function (params) {
return true;
}
}
);
im.define('IHS.Model.Commands.ShowPriceCommand', { 'baseClass': IHS.Model.Command },
{
execute: function (element) {
im.resolve("ewbApp").$rootScope.$broadcast('showPrice', element);
},
canExecute: function (params) {
return true;
}
}
);
im.define('IHS.Model.Commands.TrackActivityCommand', { 'baseClass': IHS.Model.Command },
{
execute: function (params) {
im.resolve("ewbApp").$rootScope.$broadcast('gaTrackEvent', params);
},
canExecute: function (params) {
return true;
}
}
);
im.define('IHS.Model.CalendarModel', { 'baseClass': IHS.Model.BaseActiveModel }, {
returnData: null,
firstDate: '01/01/1971',
lastDate: '12/31/' + new Date().getFullYear(),
// defFirstYear: '1980',
// defLastYear: '2000',
datePrefixFirst: '01/01/',
datePrefixLast: '12/31/',
dateFormat: "mm/dd/yy",
supportedFormats: [/^\d{1,2}[/]\d{1,2}[/]\d{2,4}$/, /^\d{4}$/],
callParent: function() {
arguments.callee.toString();
},
init: function () {
IHS.Model.CalendarModel.superclass.init.call(this);
},
activate: function (params) {
IHS.Model.CalendarModel.superclass.activate.call(this);
this.parseDate(params);
},
saveResults: function (startDate, endDate) {
var toLocale = function(date) {
return date ? IHS.Model.DateLocale.parseDateFromEnUS(date, IHS.Model.DateLocale.getShortDateFormat()) : date;
}
startDate = toLocale(startDate);
endDate = toLocale(endDate);
if (startDate && endDate)
this.returnData = [startDate, endDate];
if (startDate && endDate == undefined)
this.returnData = startDate;
if (endDate && startDate == undefined)
this.returnData = endDate;
},
setCurDate: function () {
this.datePrefixFirst = this.firstDate.slice(0, 6);
this.datePrefixLast = this.lastDate.slice(0, 6);
},
refreshDateRange: function (dateRange) {
var fv = this.dateFormat;
var ld = $.datepicker.parseDate(fv, this.firstDate);
var rd = $.datepicker.parseDate(fv, this.lastDate);
var lv = $.views.helpers.formatDate(ld, imcon.defaults.longDate);
var rv = $.views.helpers.formatDate(rd, imcon.defaults.longDate);
var newVal = lv + " - " + rv;
$(dateRange).html(newVal);
},
correctDate: function(data){
var _query = data;
var target = '/';
var pos = -1;
while ((pos = _query.indexOf(target, pos+1)) != -1) {
if (pos == 1 ) {
var text = _query.slice(0, pos);
var textLength = text.length;
if (textLength == 1){
_query = _query.replace(text,'0'+text);
}
} else {
var text = _query.slice(0, pos);
var textLength = text.length;
if (textLength == 4){
var _text = text.slice(0,-1);
var num = text.slice(-1);
var replText = _text+'0'+num;
_query = _query.replace(text, replText);
}
}
}
return _query;
},
validDate: function(_query){
var pos = -1;
var target = '/';
var valid = true;
var month = _query.slice(0, 2);
var day = _query.slice(3, 5);
while((pos = _query.indexOf(target, pos+1)) != -1){
if(pos == 2 && month > 12 && _query.length > 5){
valid = false;
}
if(pos == 5 && day > 31) {
valid = false;
}
if(pos && _query.length < 6){
var _month = _query.slice(pos + 1);
var _day = _query.slice(0,pos);
if(_month.length > 2 || _day.length > 2 || _month > 12 || _day > 31){
valid = false;
}
}
}
return valid;
},
_checkInput: function (_query) {
var q = [];
var sep = _query.search(/->/);
var sep2 = _query.search(/-/);
if (sep !== -1)
q = _query.split('->');
else if (sep2 !== -1)
q = _query.split('-');
else
q.push(_query);
if (q.length > 2 || q.length == 0) return false;
var correct = true;
var n = this.supportedFormats.length;
var _this = this;
q.ForEach(function (e) {
e = $.trim(e);
for (var i = 0; i < n; i++) {
if (e.match(_this.supportedFormats[i])) {
return;
}
}
correct = false;
});
return correct;
},
parseDate: function (params) {
var _query = params.searchData.Query;
if (!this._checkInput(_query)) return false;
var sepMore = _query.search(/->/);
var dash = _query.search(/-/);
var today = new Date();
var year = today.getFullYear();
if (params && sepMore == -1 && dash == -1 && _query.length < 21) {
if (_query.slice(-4) < 1971 || _query.slice(-4) > year || !this.validDate(_query)){
return false;
} else {
var a = this.correctDate(_query);
this.singleDate(a);
}
} else if (_query.length > 21) {
if (!this.validDate(_query)){
return false;
} else {
if (dash > 0) {
var a = this.correctDate($.trim(_query.slice(0, dash)));
var b = this.correctDate($.trim(_query.slice(dash + 2)));
if (a.slice(-4) < 1971 || b.slice(-4) < 1971 || a.slice(-4) > year || b.slice(-4) > year || !this.validDate(a) || !this.validDate(b)){
return false;
} else {
_firstDate = a;
_lastDate = b;
}
this.firstDateSwitch(_firstDate);
this.lastDateSwitch(_lastDate);
}
}
} else {
var _firstDate;
var _lastDate;
if (dash > 0) {
a = this.correctDate($.trim(_query.slice(0, dash)));
b = this.correctDate($.trim(_query.slice(dash + 1)));
if (a.slice(-4) < 1971 || b.slice(-4) < 1971 || a.slice(-4) > year || b.slice(-4) > year || !this.validDate(a) || !this.validDate(b)){
return false;
} else {
_firstDate = a;
_lastDate = b;
}
}
if (sepMore > 0) {
a = this.correctDate($.trim(_query.slice(0, sepMore)));
b = this.correctDate($.trim(_query.slice(sepMore + 2)));
if (a.slice(-4) < 1971 || b.slice(-4) < 1971 || a.slice(-4) > year || b.slice(-4) > year || !this.validDate(a) || !this.validDate(b)){
return false;
} else {
_firstDate = a;
_lastDate = b;
}
}
this.firstDateSwitch(_firstDate);
this.lastDateSwitch(_lastDate);
}
},
singleDate: function (_query) {
switch (_query.length) {
case 4:
this.firstDate = this.datePrefixFirst + _query;
this.lastDate = this.datePrefixLast + _query;
break;
case 10:
this.firstDate = _query;
this.lastDate = _query;
break;
case 8:
var _year = _query.slice(-2);
var today = new Date;
var a = today.getFullYear().toString();
if (_year > 70 && _year < 100) {
this.datePrefixFirst = _query.slice(0, 6);
this.firstDate = this.datePrefixFirst + '19' + _year;
this.lastDate = this.datePrefixFirst + '19' + _year;
} else if (a.slice(-2) < _year && _year < 70) {
return false;
} else {
this.datePrefixFirst = _query.slice(0, 6);
this.firstDate = this.datePrefixFirst + '20' + _year;
this.lastDate = this.datePrefixFirst + '20' + _year;
}
break;
case 7:
var _datePrefixFirst = _query.slice(0, 2);
this.datePrefixFirst = _datePrefixFirst.slice(0, 2) + '/' + this.datePrefixFirst.slice(0, 2) + '/';
this.firstDate = this.datePrefixFirst + _query.slice(-4);
this.lastDate = this.datePrefixFirst + _query.slice(-4);
break;
case 5:
var today = new Date();
this.datePrefixFirst = _query.slice(-2) + '/' + _query.slice(0, 2) + '/';
this.firstDate = this.datePrefixFirst + today.getFullYear();
this.lastDate = this.datePrefixFirst + today.getFullYear();
break;
}
},
firstDateSwitch: function (_firstDate) {
switch (_firstDate.length) {
case 4:
this.firstDate = this.datePrefixFirst + _firstDate;
break;
case 7:
var _datePrefixFirst = _firstDate.slice(0, 3);
this.datePrefixFirst = _datePrefixFirst + this.datePrefixFirst.slice(0, 2) + '/';
this.firstDate = this.datePrefixFirst + _firstDate.slice(-4);
break;
case 10:
this.firstDate = _firstDate;
break;
case 8:
var _year = _firstDate.slice(-2);
if (_year > 70 && _year < 100) {
this.datePrefixFirst = _firstDate.slice(0, 6);
this.firstDate = this.datePrefixFirst + '19' + _year;
} else {
this.firstDate = this.datePrefixFirst + '20' + _year;
}
break;
case 5:
var curYear = new Date().getFullYear();
this.datePrefixFirst = _firstDate.slice(-2) + '/' + _firstDate.slice(0, 2) + '/';
this.firstDate = this.datePrefixFirst + curYear;
break;
}
},
lastDateSwitch: function (_lastDate) {
switch (_lastDate.length) {
case 4:
this.lastDate = this.datePrefixLast + _lastDate;
break;
case 7:
var _datePrefixLast = _lastDate.slice(0, 3);
this.datePrefixLast = _datePrefixLast + this.datePrefixLast.slice(0, 2) + '/';
this.lastDate = this.datePrefixLast + _lastDate.slice(-4);
break;
case 10:
this.lastDate = _lastDate;
break;
case 8:
var _year = _lastDate.slice(-2);
if (_year > 70 && _year < 100) {
this.datePrefixLast = _lastDate.slice(0, 6);
this.lastDate = this.datePrefixLast + '19' + _year;
} else {
this.datePrefixLast = _lastDate.slice(0, 6);
this.lastDate = this.datePrefixLast + '20' + _year;
}
break;
case 5:
var curYear = new Date().getFullYear();
this.datePrefixLast = _lastDate.slice(-2) + '/' + _lastDate.slice(0, 2) + '/';
this.lastDate = this.datePrefixLast + curYear;
break;
}
}
});
im.define('IHS.Model.TranslationModel', { 'baseClass': IHS.Model.BaseActiveModel }, {
_translationCopy: null,
activate: function (data) {
this.data = data;
IHS.Model.TranslationModel.superclass.activate.call(this, data);
this.activated();
},
getTranslationSettings: function () {
if (this._translationCopy == null) {
this._translationCopy = $.extend(true, {}, this.data.getTranslationSettings(), { modified: 0 });
delete this._translationCopy.isInitial;
if (!this._translationCopy.TargetLanguage)
this._translationCopy.TargetLanguage = 0;
// If current Translation is None, then set source list to all avaiable languages.
if (this._translationCopy.TargetLanguage == 0)
this._translationCopy.SourceLanguages = this.data.getLangList().Select(function (i) { return i.Id });
}
return this._translationCopy;
},
getTarget: function () {
return this.getTranslationSettings().TargetLanguage || 0;
},
setTarget: function (target) {
this.getTranslationSettings().TargetLanguage = target;
this.getTranslationSettings().modified++;
$(this).trigger("target");
},
getSources: function () {
return this.getTranslationSettings().SourceLanguages || [];
},
setSource: function (id, mode) {
var sources = this.getTranslationSettings().SourceLanguages;
var index = sources.IndexOf(function (i) { return i == id });
if (mode == undefined || mode == "toggle")
mode = index == -1;
if (mode) {
if (index == -1)
sources.push(id);
}
else {
if (index != -1)
sources.splice(index, 1);
}
this.getTranslationSettings().modified++;
$(this).trigger("sources");
},
apply_toSource: function () {
var oldTrans = this.data.getTranslationSettings();
var trans = this.getTranslationSettings();
if (trans.modified > 0 && (!oldTrans || !oldTrans.SourceLanguages || trans.TargetLanguage != oldTrans.TargetLanguage || trans.SourceLanguages.Distinct(oldTrans.SourceLanguages).length > 0)) {
var mode = $('div.ITAModes.selected').attr('modeid');
im.resolve('commands')
.invoke("track-activity",
{
logicName : "ita-translate-results",
id: trans.TargetLanguage
});
// Cut off target language from list of sources.
this.setSource(trans.TargetLanguage, false);
trans.modified = 1;
im.resolve("translation-settings").put(trans);
trans.modified = 0;
this.data.setQZ("TranslationSettings", trans);
$(this.data).trigger("TranslationChanged");
}
},
getLangList: function (fixChinese, isNative) {
var self = this;
if (!this.data) return [];
// hide russian language DE75323
var res = this.data.getLangList().Where(function (i) { return i.Id !== 1049 }).Select(function (i) {
var r = $.extend({}, i);
r.Name = im.getLangNameById(r.Id, isNative, fixChinese);
return r;
});
return res;
}
});
im.define('IHS.Model.Services.TranslationSettings', { 'baseClass': IHS.Model.BaseService }, {
_localHash: null,
/*Deferred*/get: function () {
var df = $.Deferred();
// Already in cache ? Then, return stored data.
if (this._localHash)
df.resolve(this._localHash);
else {
// Not in cache. Request settings from Server via Settings.QueryZone Controller to provide
// language selection logic.
var self = this;
im.resolve("settings").getQueryZone(null, function (qz) {
if (qz && qz.TranslationSettings) {
self.put(qz.TranslationSettings, true);
df.resolve(self._localHash);
}
});
}
return df;
},
getLast: function () {
if (this._localHash == null) {
// Not loaded yet. Let's extract from default settings acquired via login.
var r = (imcon.defaults.userSettings && imcon.defaults.userSettings.Translation) || {};
if (typeof (r.SourceLanguages) === "string")
r.SourceLanguages = JSON.parse(r.SourceLanguages);
return r;
}
return this._localHash;
},
put: function (/*Object*/data, skipSaving) {
this._localHash = $.extend(true, { TargetLanguage: 0, SourceLanguages: [] }, data);
if (typeof (this._localHash.SourceLanguages) === "string")
this._localHash.SourceLanguages = JSON.parse(this._localHash.SourceLanguages);
if (skipSaving == true)
return;
im.resolve('settings').put({ Translation: { TargetLanguage: this._localHash.TargetLanguage, SourceLanguages: JSON.stringify(this._localHash.SourceLanguages) } });
}
});
///
im.define('IHS.Model.Data.LoaderTypes', null, null, { static:
{
API: 'api',
CONNECT: 'connect', // Usage should be eliminated
EW: 'ew', // Usage should be eliminated
GHC: 'ghc' // Usage should be eliminated
}
});
// Loader is a wrapper over $.ajax encapsulating Goldfire WEB API uri building and security logic. Each loader is configured in bootstrapper.
im.define('IHS.Model.Data.Loader', { 'baseClass': IHS.Model.BaseService },
{
_loads: null,
uri: '',
options: null,
type: IHS.Model.Data.LoaderTypes.API,
parameters: null,
action: null,
_batchItems: null,
extHeaderData: null,
init: function () {
IHS.Model.Data.Loader.superclass.init.call(this);
this._loads = [];
},
injector: function() {
if (this._injector !== null) {
var app = im.resolve("ewbApp");
this._injector = app && app.$injector;
if (!this._injector) {
this._injector = im.getItemValue(window, "ewbApp.mainInjector");
}
if (!this._injector)
this._injector = null;
}
return this._injector;
},
tokenMs: function() {
if (this._tokenMs !== null) {
var injector = this.injector();
if (injector) {
this._tokenMs = injector.get("TokenMS");
}
if (!this._tokenMs) this._tokenMs = null;
}
return this._tokenMs;
},
_getUri: function (batchUri, batchparameters) {
if (this._params && this._params.isMs && this.uri) return this.uri;
if ((!this.uri) && (!batchUri)) return '';
var Loader = IHS.Model.Data.Loader;
var uriParts = batchUri ? batchUri.split('|') : this.uri.split('|');
var controller = uriParts[0];
var action = uriParts[1] || this.action || null;
if (uriParts.length > 2)
action = uriParts.slice(1);
switch (this.type) {
case IHS.Model.Data.LoaderTypes.API:
return Loader.makeApiUrl(controller, action, batchparameters || this.parameters);
default:
return Loader.makeUrl(controller, action, batchparameters || this.parameters);
}
},
_extendParams: function (params) {
var uri = this._getUri();
if (params.type === 'POST') { // Fix for POST request caching by Safari and others
var a = [];
a.push(uri);
if (uri.indexOf('?') > -1) {
a.push('&');
}
else {
a.push('?');
}
a.push('time=');
a.push((new Date()).getTime());
uri = a.join('');
}
var o = {
url: uri,
dataType: 'json',
contentType: 'application/json'
};
if (this._params && this._params.timeout) {
o.timeout = this._params.timeout;
}
if (params) {
$.extend(o, params);
}
if (this._id) {
o.loaderId = this._id;
}
if (this.options) {
$.extend(o, this.options);
}
if (this.extHeaderData) {
for (var p in this.extHeaderData) {
if (p && this.extHeaderData.hasOwnProperty(p)) {
if (!o.headers)
o.headers = {};
o.headers[p] = this.extHeaderData[p];
}
}
}
return o;
},
send: function (type, data, success, error) {
var params = this._extendParams({ data: data, type: type, success: success, error: error });
return $.ajax(params);
},
post: function (data, success, error) {
return this.send('POST', JSON.stringify(data), success, error);
},
get: function (data, success, error) {
return this.send('GET', data, success, error);
},
put: function (data, success, error) {
return this.send('PUT', JSON.stringify(data), success, error);
},
'delete': function (data, success, error) {
return this.send('DELETE', data, success, error);
},
patch: function (data, success, error) {
return this.send('PATCH', JSON.stringify(data), success, error);
},
batch: function(data, completeForEach, error) {
if (!data || data.length <= 0) {
if (completeForEach) {
completeForEach.call(this, "", 0, []);
}
return;
}
var _this = this;
for (var i = 0, l = data.length; i < l; i++) {
var item = data[i];
item.url = _this._getUri(item.url) + (item.urlPostfix || '');
}
var generateCallback = function( callbackForEach ) {
return (callbackForEach)
? function(xnr, status) {
if (callbackForEach) _this._batchUtil.unpack(xnr, status, callbackForEach)
}
: null;
}
var boundary = new Date().getTime().toString();
var params = this._extendParams({
data: this._batchUtil.pack( data, boundary ),
type: 'POST',
contentType: 'multipart/mixed; boundary="' + boundary + '"',
complete: generateCallback(completeForEach),
error: error,
dataType: 'text'
});
params.url = IHS.Model.Data.Loader.makeApiUrl('') + 'batch/GF';
return $.ajax(params);
},
batchLoaders: function (completeForEach, error) {
if (!this._batchItems || this._batchItems.length <= 0) {
if (completeForEach) {
completeForEach.call(this, "", 0, []);
}
return;
}
var batchItems = [];
for (var i = 0, l = this._batchItems.length; i < l; i++) {
var p = this._batchItems[i];
batchItems.push({ url: p.loader._getUri(), type: p.type, data: p.req, extHeaderData: p.loader.extHeaderData });
}
this._batchItems = null;
var self = this;
var generateCallback = function (callbackForEach) {
return (callbackForEach)
? function (xnr, status) {
if (callbackForEach) self._batchUtil.unpack(xnr, status, callbackForEach)
}
: null;
}
var boundary = new Date().getTime().toString();
var params = this._extendParams({
data: this._batchUtil.pack(batchItems, boundary),
type: 'POST',
contentType: 'multipart/mixed; boundary="' + boundary + '"',
complete: generateCallback(completeForEach),
error: error,
dataType: 'text'
});
params.url = IHS.Model.Data.Loader.makeApiUrl(this.uri);
return $.ajax(params);
},
addLoader: function (loader, type, req) {
if (!this._batchItems)
this._batchItems = [];
this._batchItems.push({ loader: loader, type: type, req: req });
},
_batchUtil: {
/**
* Packs the given requests into the batch and returns batch contents.
* @param {Array} data Data to pack.
* @param {string} boundary Muti-part boundary mark.
*/
pack: function (data, boundary) {
var body = [];
for (var i = 0, l = data.length; i < l; i++) {
var d = data[i];
var t = d.type.toUpperCase(), noBody = ['GET', 'DELETE'];
body.push('--' + boundary);
body.push('Content-Type: application/http; msgtype=request', '');
var url = d.url;
var hasBody = noBody.indexOf(t) < 0;
if (!hasBody && d.data) {
// extend URL with parameters for non-body methods
url = (url.indexOf('?') > 0 ? url + '&' : url + '?') + $.param(d.data, true);
}
body.push(t + ' ' + url + ' HTTP/1.1');
/* Don't care about content type for requests that have no body. */
if (hasBody) {
body.push('Content-Type: ' + (d.contentType || 'application/json; charset=utf-8'));
}
if (d.extHeaderData) {
for (var p in d.extHeaderData) {
if (p && d.extHeaderData.hasOwnProperty(p)) {
body.push(p + ': ' + d.extHeaderData[p]);
}
}
}
body.push('Host: ' + location.host);
body.push('', (hasBody && d.data) ? JSON.stringify(d.data) : '');
}
body.push('--' + boundary + '--', '');
return body.join('\r\n');
},
/**
* Unpacks the given response and passes the unpacked data to the original callback.
* @param {object} xhr jQuery XHR object.
* @param {string} status Response status.
* @param {Function} complete A callback to be executed upon unpacking the response.
*/
unpack: function (xhr, status, complete) {
var lines = xhr.responseText.split('\r\n'),
boundary = lines[0], data = [], d = null;
for (var i = 0, len = lines.length; i < len; i++) {
var l = lines[i];
if (!l.length)
continue;
if (l.indexOf(boundary) == 0) {
if (d)
data.push(d);
d = {};
continue;
}
if (!d)
continue;
if (!d.status) {
d.status = parseInt((function (m) {
return m || [0, 0];
})(/HTTP\/1.1 ([0-9]+)/g.exec(l))[1], 10);
continue;
}
if (!d.data) {
try {
d.data = $.parseJSON(l);
// in IE7 no exception is thrown, just null is returned
if ((!d.data) && IHS.Controllers.Browser.getUserAgent() == IHS.Controllers.Browser.IE7)
throw "IE7";
}
catch (ex) {
// Retrived line is not a JSON. Probably, it is a Header.
if (l.match(/\b\S+:/)) {
var splitSeparator = l.indexOf(":");
if (splitSeparator > 0) {
if (!d.headers)
d.headers = {};
d.headers[l.substr(0, splitSeparator)] = $.trim(l.substr(splitSeparator + 1));
}
}
}
}
}
complete.call(this, xhr, status, data);
}
},
loadExclusive: function (load) {
this.breakLoad();
this._loads.push(load);
return load;
},
auxLoad: function (load) {
this._loads.push(load);
return load;
},
exclusivePost: function (data) {
return this.loadExclusive(this.post(data));
},
exclusiveGet: function (data) {
return this.loadExclusive(this.get(data));
},
breakLoad: function (load) {
var newLoads = [];
var found = false;
for (var i = 0; i < this._loads.length; ++i) {
if (this._loads[i]) {
if (!load || load === this._loads[i]) {
this._loads[i].abort();
if (!found)
found = true;
}
else
newLoads.push(this._loads[i]);
}
}
this._loads = newLoads;
return found;
}
},
{
static: {
baseUrl: null,
module: null,
aft: null,
onError: null,
stateHeaderName: 'ewcs',
stateHeaderValue: '',
makeUrl: function (controller, action, parameters, module) {
var ret = [];
if (this.baseUrl) {
ret.push(this.baseUrl);
if (this.baseUrl.substr(this.baseUrl.length - 1) !== '/') {
ret.push("/");
}
var t = IHS.Model.Data.LoaderTypes;
if (!module /*|| module !== t.API || module !== t.CONNECT || module !== t.EW || module !== t.GHC*/) {
module = this.module;
}
//Ignore empty module
if (module) {
ret.push(encodeURIComponent(module));
ret.push("/");
}
ret.push(encodeURIComponent(controller));
if (action) {
if ($.isArray(action)) {
action.ForEach(function(a) {
ret.push("/");
ret.push(encodeURIComponent(a));
});
}
else {
ret.push("/");
ret.push(encodeURIComponent(action));
}
}
//Add current parameters by default
if (true === parameters) {
parameters = {};
var prmarr = window.location.search.substr(1).split("&");
prmarr.forEach(function (item) {
var tmparr = item.split("=");
parameters[tmparr[0]] = tmparr[1];
});
}
if (parameters) {
ret.push("?");
for (var k in parameters) {
if (parameters.hasOwnProperty(k)) {
ret.push(encodeURIComponent(k));
ret.push("=");
ret.push(encodeURIComponent(parameters[k]));
ret.push("&");
}
}
}
}
return ret.join('').replace(/[\?\&]+$/, "");
},
makeEwbUrl: function(path, addParams) {
var ret = [];
ret.push(this.baseUrl);
if (this.baseUrl.substr(this.baseUrl.length - 1) !== '/') {
ret.push("/");
}
if (addParams) {
var parameters = {};
var prmarr = window.location.search.substr(1).split("&");
if (prmarr.length) {
prmarr.forEach(function (item) {
var tmparr = item.split("=");
if (tmparr[0]) {
parameters[tmparr[0]] = tmparr[1];
}
});
if (Object.keys(parameters).length) {
ret.push("?");
for (var k in parameters) {
if (parameters.hasOwnProperty(k)) {
ret.push(encodeURIComponent(k));
ret.push("=");
ret.push(encodeURIComponent(parameters[k]));
ret.push("&");
}
}
}
}
}
return ret.join('').replace(/[\?\&]+$/, "") + '#/' + path.replace(/^[\?\/]+/, "");
},
makeEwbWaitUrl: function(path) {
var ret = this.baseUrl;
if (this.baseUrl.substr(this.baseUrl.length - 1) !== '/') {
ret += '/';
}
return ret + 'open.aspx?url=' + encodeURIComponent(path);
},
makeApiUrl: function (controller, action, parameters) {
return this.makeUrl(controller, action, parameters, 'api');
},
makeAbsUrl: function (relativeUrl, skipBase) {
// DE103628: Do not use absolute address.
// All extra processing is inside unauthorizedHandler.
return relativeUrl;
var baseUri = skipBase ? '/' : this.baseUrl || '/';
if (baseUri[baseUri.length - 1] === '/' && relativeUrl && relativeUrl[0] === '/') {
relativeUrl = relativeUrl.substr(1);
}
return [location.protocol, "//", location.host, baseUri, relativeUrl || ''].join('');
},
setBaseUrl: function (baseUrl) {
// DE103628: Set base address for all Loaders to '/'.
// All extra processing is inside unauthorizedHandler.
this.baseUrl = "/";
return;
// Here we need to check if passed URL is relative or absolute.
// In case of absolute we have to cut off location.
if (baseUrl && (baseUrl.StartsWith("http://") || baseUrl.StartsWith("https://"))) {
var ind = baseUrl.indexOf('/') + 2;
for (var i = 0; i < window.location.host.length; i++, ind++) {
if (baseUrl.charAt(ind) != window.location.host.charAt(i))
break;
}
baseUrl = baseUrl.substr(ind);
}
this.baseUrl = baseUrl;
},
setModule: function (module) {
this.module = module;
},
setAft: function (aft) {
this.aft = aft;
},
setErrorHandler: function (onError) {
this.onError = onError;
},
handleResponseHeaders: function (xmlHttp) {
var state = xmlHttp.getResponseHeader(this.stateHeaderName);
if (state) {
this.stateHeaderValue = state;
}
},
checkNewVersionError: function (data) {
if (!data)
return null;
if (!$.isArray(data))
data = [data];
var ret = null;
for (var i = 0, l = data.length; i < l; i++) {
var errorCode;
if (data[i].data && data[i].data.errorCode) {
errorCode = data[i].data.errorCode;
}
else if (data[i].responseText) {
var err = im.ViewModelBase.fromString(data[i].responseText);
if (err)
errorCode = err.errorCode;
}
if (data[i].status == 412 && errorCode == 118) {
ret = { status: 412, errorCode: 118 };
break;
}
}
return ret;
},
setup: function () {
$(document).ajaxError(function (e, jqxhr, settings, exception) {
var f = IHS.Model.Data.Loader.onError;
if (f) {
f(e, jqxhr, settings, exception);
}
});
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var url = options.url;
var Loader = IHS.Model.Data.Loader;
var headers = { appType: Loader.module };
if (IHS.Model.Data.Loader.stateHeaderValue) {
headers[Loader.stateHeaderName] = Loader.stateHeaderValue;
}
if (url.indexOf("api/") === 0 || url.indexOf("/api/") !== -1)
headers["RID"] = im.generateId();
options.headers = $.extend({}, options.headers, headers);
if (options.type === "POST") {
options.headers["Cache-Control"] = "no-cache";
}
if (options.addPrefLang) {
var settings = im.resolve("settings");
var langPref = settings.getLangPreference();
var data = JSON.parse(options.data);
data.LanguagePreferences = langPref;
options.data = JSON.stringify(data);
}
// $(document).ajaxSuccess do not work for nested requests as success event appear only after explicit success handler
// so we substitute explicit success handler (if any) and remember possible loaderId if specified.
// Some handlers need to distinguish loaders by their IDs. MyDataService for example.
var loaderId = options.loaderId;
var successCallback = options.success;
var errorCallback = options.error;
var transformResponse = options.transformResponse;
options.error = function (jqXHR, textStatus, errorThrown) {
IHS.Model.Data.Loader.handleResponseHeaders(jqXHR);
var f = IHS.Model.Data.Loader.onError;
var _handled = false;
if (f) {
_handled = f(null, jqXHR);
}
if (!_handled && errorCallback) {
errorCallback(jqXHR, textStatus, errorThrown, loaderId, options);
}
}
options.success = function (data, textStatus, jqXHR) {
IHS.Model.Data.Loader.handleResponseHeaders(jqXHR);
var f = IHS.Model.Data.Loader.onError;
if (f) {
f(null, jqXHR);
}
if (transformResponse) {
data = transformResponse(data, textStatus, jqXHR, loaderId);
}
if (successCallback) {
successCallback(data, textStatus, jqXHR, loaderId, options);
}
};
});
}
}
}
);
///
im.define('IHS.Model.Services.Help', { 'baseClass': IHS.Model.BaseService },
{
_baseUrl: null,
setBaseUrl: function (baseUrl)
{
this._baseUrl = baseUrl;
},
showHelp: function (id)
{
var ur = this._baseUrl ? this._baseUrl.replace('{0}', encodeURIComponent(id)) : IHS.Model.Data.Loader.makeUrl("app", "help", { id: id });
if (this._baseUrl && id == 'IDH_Advanced_search')
{
ur = this._baseUrl.replace('Results/Overview_of_search_results.htm', 'Query/Advanced_search.htm');
}
im.resolve('commands').invoke
(
'help-command',
{ uri: ur }
);
}
}
);
///
im.define('IHS.Model.Services.Dialog', { 'baseClass': IHS.Model.BaseService },
{
sandbox: [],
defaultTitle: '',
alert: function (/*String*/text, /*String*/title, /*Object*/params) {
this.activate({ modelToActivate: 'alert-dialog-model', paramsToActivate: $.extend({ text: text || '', title: title || imcon.jsres[this.defaultTitle] }, params || {}) });
},
confirm: function (/*String*/text, /*String*/title, /*Function*/onClick, params) {
this.activate({ modelToActivate: 'confirm-dialog-model', paramsToActivate: $.extend({ text: text || '', title: title || imcon.jsres[this.defaultTitle], onClick: onClick}, params || {}) });
},
input: function (/*String*/text, /*String*/title, /*Function*/onInput, params) {
this.activate({ modelToActivate: 'input-dialog-model', paramsToActivate: $.extend({ text: text || '', title: title || imcon.jsres[this.defaultTitle], onInput: onInput }, params || {}) });
},
chooseResults: function (/*String*/text, /*String*/title, /*Object*/params) {
this.activate({ modelToActivate: 'choose-results-dialog-model', paramsToActivate: $.extend({ text: text || '', title: title || imcon.jsres[this.defaultTitle] }, params || {}) });
},
activate: function (appParams) {
if(!this.getLength())
$(window).bind("hashchange.imcon", $.proxy(this.deactivateAll, this));
this.sandbox.push(this._build(appParams));
},
deactivateAll: function(){
while (this.getLength()){
this.deactivate();
}
},
deactivate: function () {
if (this.sandbox.length > 0) {
var o = this.sandbox.pop();
if (o) {
this.dialogOnCloseAction(o);
$(o).unbind('dialogDeactivated');
o.destroy();
}
if (this.sandbox.length > 0) {
o = this.sandbox[this.sandbox.length - 1];
if (o) {
o._checkViewPort();
$(window).bind('resize orientationchange', o._resizeHandlerToken);
$(window).bind('scroll', o._resizeHandlerToken);
}
} else
$(window).unbind("hashchange.imcon", $.proxy(this.deactivateAll, this));
}
},
getLength: function () {
return this.sandbox.length;
},
getTop: function () {
return this.sandbox.length > 0 ? this.sandbox[this.sandbox.length - 1].model : null;
},
dialogOnCloseAction: function(o){
if (o && o.model && o.model.activeModel) {
if (o.model._params.onReturn) {
o.model._params.onReturn(o.model.activeModel[o.model._params.returnValue || "returnValue"]);
}
if (o.model._params.paramsToActivate && o.model._params.paramsToActivate.onReturn) {
o.model._params.paramsToActivate.onReturn(o.model.activeModel[o.model._params.paramsToActivate.returnValue || o.model._params.returnValue || "returnValue"]);
}
}
},
getTop: function () {
return this.sandbox.length > 0 ? this.sandbox[this.sandbox.length - 1].model : null;
},
_build: function (appParams) {
if (typeof (appParams) == 'undefined') {
appParams = {};
}
if (appParams.modelToActivate === '') { // Generic dialog call
appParams.modelToActivate = 'alert-dialog-model';
}
var p = { _useCorrectActivateNotification: false };
if (appParams.models) {
p.sandboxName = 'dialog'; // To be able to activate models inside dialogs
}
var sandbox = new IHS.Controllers.Dialog(null, { // TODO: _useCorrectActivateNotification is temporary used until all dialogs fixed for model activation
model: new IHS.Model.Sandbox(null, $.extend(p, appParams), true),
path: '/js/views/Error.htm',
template: '#generic-dialog-jsrender-error'
}, true); // Run dialog
var self = this;
$(sandbox).bind('dialogDeactivated', function () { im.resolve('dialog').deactivate(); });
return sandbox;
}
}
);
///
im.define('IHS.Model.MessageServiceTypes', null, null, {
static:
{
SIMPLE: 'simple',
STYLED: 'styled'
}}
);
im.define('IHS.Model.Services.Message', { 'baseClass': IHS.Model.BaseService },
{
alert: function(title, text, type) {
$(this).trigger('messageAlert', { 'title': title, 'text': text, 'type': type || IHS.Model.MessageServiceTypes.SIMPLE });
},
confirm: function (obj) {
$(this).trigger('messageConfirm', obj);
}
}
);
///
im.define('IHS.Model.Services.Title', { 'baseClass': IHS.Model.BaseService },
{
titleResId: '',
update: function (text) {
this.notify({ topic: 'changetitle', data: this.get(text) });
},
get: function (text) {
return (text ? (text + ' - ' + imcon.jsres[this.titleResId]) : imcon.jsres[this.titleResId]);
}
}
);
im.define('IHS.Model.State', { 'baseClass': IHS.Model.BaseModel }, {
hash: null,
modelAlias: '',
state: null,
children: null,
isActive: false,
number: -1,
time: 0,
displayName: null,
init: function () {
this.children = [];
var p = this._params;
for (var i in p) {
this[i] = p[i];
}
}
});
///
im.define("IHS.Model.ActivateIn", null, null, {
'static': {
Content: 0,
Dialog: 1
}
});
im.define("IHS.Model.StateType", null, null, {
'static': {
Normal: 0,
Shared: 1
}
});
im.define('IHS.Model.Services.Activation', { 'baseClass': IHS.Model.BaseService },
{
map: function (ticket) {
if (this.hasMap(ticket)) return this._params[ticket].name;
return null;
},
hasMap: function (ticket) {
return this._params && this._params[ticket];
},
ofType: function (ticket) {
if (this.hasMap(ticket)) return this._params[ticket].type || IHS.Model.ActivateIn.Content;
return IHS.Model.ActivateIn.Content;
},
ofState: function (ticket) {
if (this.hasMap(ticket)) return this._params[ticket].state || IHS.Model.StateType.Normal;
return IHS.Model.StateType.Normal;
},
ticketsByName: function (name) {
var ret = [];
if (this._params)
{
for (var t in this._params)
{
if (this._params[t] && this._params[t].name == name)
ret.push(t);
}
}
return ret;
},
getDefault: function () {
if (this._params && this._params['_default']) return this._params['_default'].name;
return null;
}
}
);
/*!
* Cookie storage provider. Implemets provider interface:
String getItem(String key);
String setItem(String key, String value, Int age);
void removeItem(String key);
*/
im.define('IHS.Model.Services.CookieStorageProvider', { 'baseClass': IHS.Model.BaseService },
{
'_defaultAge': 365 * 2, //2 years
'_defaultPath': '/',
'getItem': function (/*String*/key) {
if (!key) return null;
return this._accessor(key);
},
'setItem': function (/*String*/key, /*String*/value, /*Int*/age) {
if (!key) return null;
var path = this._defaultPath;
var expires = age || this._defaultAge;
return this._accessor(key, value, { 'expires': expires, 'path': path });
},
'removeItem': function (/*String*/key) {
if (!key) return null;
var path = this._defaultPath;
return this._accessor(key, '', { 'path': path, 'expires': -1 });
},
'_accessor': function (name, value, options) {
if (name && !value && value !== '') {
var cookies = document.cookie;
if (cookies.indexOf(name) > -1) {
var cArr = cookies.split(';');
for (var i = 0, n = cArr.length; i < n; i++) {
if (cArr[i].indexOf(name) > -1) {
var found = cArr[i].replace(new RegExp('\s+', 'g'), '').split('=');
if (found.length == 2 && found[1]) {
return found[1];
}
}
}
}
}
if (name && (value || value === '')) {
var a = [name, '=', value];
if (options.expires) {
if (typeof (options.expires) === 'number') {
var days = options.expires;
options.expires = new Date();
options.expires.setDate(options.expires.getDate() + days);
}
a.push('; expires=');
a.push(options.expires.toUTCString());
}
if (options.path) {
a.push('; path=');
a.push(options.path);
}
if (options.domain) {
a.push('; domain=');
a.push(options.domain);
}
if (options.secure) {
a.push('; secure');
a.push(options.secure);
}
document.cookie = a.join('');
}
}
}
);
im.define('IHS.Model.KBTreeItem', null, {
Id: "",
Parent: "",
Name: "",
Author: "",
Flags: 0,
Languages: [],
Note: "",
InfoUrl: null,
Available: false,
Tooltip: "",
Children: [],
init: function () {
this.Languages = [];
this.Children = [];
},
toString: function () {
return "Id: " + this.Id + ", Parent: " + this.Parent + ", Name:'" + this.Name + "'";
}
},
{
static:
{
makeLangTooltip: function (item) {
if (item.Languages && item.Languages.length == 1)
item.LangTT = imcon.jsres['KBLang' + item.Languages[0] + 'TT'];
else
item.LangTT = imcon.jsres.MixedContent;
return item;
},
makeDisabled: function (item) {
item.Disabled = ((item.Flags & IHS.Model.KBFlags.Disabled) != 0 ||
item.Available == false);
return item;
},
makeDisabledByAdmin: function (item) {
item.DisabledByAdmin = (item.Flags & IHS.Model.KBFlags.DisabledByAdmin) != 0;
}
}
}
);
im.define("IHS.Model.KBFlags", null, null,
{
static:
{
/// Not specified
Nothing: 0,
/// This is folder - can have children items
Folder: 1,
/// Has browsing data created
HasBrowsingData: 2,
/// Disable for search
Disabled: 4,
/// Failed
Fail: 8,
/// Fake item. Such as "Loading..." or "Data not available."
Fake: 16,
/// Disabled by Admin
DisabledByAdmin: 8192
}
});
im.define('IHS.Model.SelectKBsModel', { 'baseClass': IHS.Model.BaseActiveModel }, {
_Root: null,
_Loader: null,
_pcnLoader: null,
_QZState: null,
isMultiLang: true,
resx: null,
selected: null,
settingSection: null,
onClose: null,
onReturn: null,
showSearchIn: false,
wpSrv: "",
isCorporateAvailable: true,
defaultKBs: ["|1", "2,0|1", "2|1", "3|1", "4|1", "6|1"],
movedToStandardsIds: {},
categoryRoots: {
Root: "|1",
Personal: "1|1",
Corporate: "2|1",
Effects: "3|1",
IMB: "4|1",
Articles: "4,4|1",
Patents: "4,3|1",
Content: "4,5|1",
EBooks: "4,7|1",
Collections: "6|1",
Standards: "4,5,x1|1"
},
KbFlags: {
// Not specified
Nothing: 0x0,
// This is folder - can have children items
Folder: 0x1,
// Has browsing data created
HasBrowsingData: 0x2,
// Disable for search
Disabled: 0x4,
// Failed
Fail: 0x8,
Fake: 0x10,
// Checked for search
UnCheckedByDef: 0x1000,
// Disabled by Admin
DisabledByAdmin: 0x2000,
// Cann't be disabled
ReadOnly: 0x4000
},
init: function () {
this.resx = imcon.jsres;
this._QZState = new IHS.Model.QueryZone.State(null, null, true);
this._QZState.Source = "KBSelectDlg";
this._Root = new IHS.Model.KBTreeItem(null, null, true);
this._Root.Id = "|1";
this._Loader = im.resolve("kbtree-loader");
this._pcnLoader = im.resolve("pcn-loader");
IHS.Model.SelectKBsModel.superclass.init.call(this);
},
activate: function (data) {
if (data) {
this.set_State(data.state, data.isMultiLang);
this.selected = data.selected;
this.onClose = data.onClose;
this.onReturn = data.onReturn;
IHS.Model.SelectKBsModel.superclass.activate.call(this, data);
}
else if (this._params.httpParams) {
var qzstate = $.parseJSON(this._params.httpParams.qzstate);
this.set_State(qzstate, true);
this.showSearchIn = this._params.httpParams["kbs-mode"] == "1" ? true : false;
this.wpSrv = this._params.httpParams["srv"];
//this.selected = data.selected;
IHS.Model.SelectKBsModel.superclass.activate.call(this, this._params.httpParams);
}
},
load_InitialTree: function () {
var data =
{
selected: this.get_CheckedItems(),
expanded: (this.defaultKBs || []).concat(this.get_ExpandedItems())
};
if ((IHS.Model.Data.Loader.module == "ew" || IHS.Model.Data.Loader.module == "kc") && $.grep(data.selected, function (x) { return x == '6|1'; }).length == 0)
data.selected.push(this.categoryRoots.Collections); // always add KB Collections root ta have it loaded
this._Loader.post(data, $.proxy(this.onInitialLoaded, this), $.proxy(this.onInitialFailed, this));
if (IHS.Model.FeatureSwitcherService.featureSupported("USECATSDOCUMENTSMS")) {
// no any reason to call server to receive of hasCorporateKnowledgeBase flag state
this.onCorporateAvailable(imcon.defaults.fpcns.hasCorporateKnowledgeBase, "success");
} else {
this._pcnLoader.get(null,
$.proxy(this.onCorporateAvailable, this),
$.proxy(this.onCorporateAvailable, this));
}
},
load_SubTree: function (id, depth, onErrorCallback) {
var loader = im.resolve("kbtree-loader");
loader.options = { url: "api/" + loader.uri.replace(/\|/g, '/') + '/' + id + '/' + depth };
var self = this;
loader.get({}, function (res) { self.onBranchLoaded(id, res, onErrorCallback); }, onErrorCallback);
},
onInitialLoaded: function (items) {
this._Root.isInitialized = true;
items = items.filter(function (item) { return item.Available === true; });
var expiredData = $.grep(items, function (el, i) {
return el.Name && el.Name.indexOf('expired') > -1;
});
var self = this;
var unavailableText = this._getUnavailableText();
var stRoot = null;
items.ForEach(function (i) {
//replace "Unavailable" server message
if ((i.Flags & self.KbFlags.Fail) && (i.Name.indexOf('unavailable') > -1)) {
i.Name = unavailableText;
}
if (i.Parent == self.categoryRoots.Content && IHS.Model.QueryZone.State.MoveToStandardsPrimaryIds.IndexOf(i.PrimaryId) != -1) {
// Create a virtual root
if (!stRoot) {
stRoot = new IHS.Model.KBTreeItem();
stRoot.Id = self.categoryRoots.Standards;
stRoot.Parent = "|1";
stRoot.Name = imcon.jsres.CodesAndStandards;
}
if ($.isEmptyObject(self.movedToStandardsIds)) {
self.movedToStandardsIds = {};
}
self.movedToStandardsIds[i.Id] = i;
i.Parent = stRoot.Id;
i.ParentChanged = true;
}
//change node for expired content
if (expiredData.length > 0) {
var expEl = expiredData.First(function (el) { return el.Id == i.Id; });
if (expEl && i.Id == i.Parent) {
i.Parent = self.categoryRoots.Root;
}
if (expEl && i.Id == self.categoryRoots.IMB || i.Id == self.categoryRoots.Effects) {
i.Name = expEl.Name;
i.Flags = expEl.Flags;
}
}
});
if (stRoot) {
items.push(stRoot);
this._recheckStandards();
}
if (this._QZState.IsMultiSite === undefined) {
this._QZState.IsMultiSite = items.Where({ field: "Parent", value: "2|1" }).length > 1;
}
if (this._QZState.IsMultiSite != true) {
// GFIN08_SFS_212_03_0524_GFHC
// Skip first level of Corporate KBs in case of single Server.
var corporateRoot = items.First({ field: "Parent", value: "2|1" });
if (corporateRoot) {
self._checkedItems.ForEach(function (i, index) {
if (i == corporateRoot.Id)
self._checkedItems[index] = corporateRoot.Parent;
});
items.ForEach(function (i) {
if (i.Parent == corporateRoot.Id) {
i.Parent = corporateRoot.Parent;
i.ParentChanged = true;
}
});
items.DeleteIf(function (i) {
return i == corporateRoot;
});
}
}
this.prepare_Items(items);
this.build_SubTree(this._Root, items, null, function (info) {
if (info.level != 0 || info.complete)
return;
info.complete = true;
var corpRoot = this.get_SubRoot(this.categoryRoots.Corporate);
if (corpRoot) {
corpRoot.Name = imcon.jsres.KBCorporateTitle;
if (!this.isCorporateAvailable) {
this._makeCorporateUnavailable(false);
}
}
// Multi-site: need to sort Servers
if (corpRoot && corpRoot.Children && corpRoot.Children.length > 1 && this._QZState.IsMultiSite == true) {
corpRoot.Children.sort(function (a, b) {
// Application Server shall go first in the list.
if (a.Id == "2,0|1")
return -1;
if (b.Id == "2,0|1")
return 1;
// Sort other Servers alphabetically, case insensitive.
var an = a.Name.toUpperCase();
var bn = b.Name.toUpperCase();
if (an < bn)
return -1;
if (an > bn)
return 1;
return 0;
});
}
var _this = this;
setTimeout(function () {
_this.apply_LoadingToFolders(items);
_this._this.trigger("isLoadingChanged");
}, 1);
});
},
onCorporateAvailable: function (data, status) {
if (status == "success")
this.isCorporateAvailable = im.parseBool(data);
else
this.isCorporateAvailable = false;
if (!this.isCorporateAvailable) {
this._makeCorporateUnavailable(true);
} else {
this._QZState.CorporateCheckFlags = 0;
}
},
_makeCorporateUnavailable: function (notify) {
var corp = this._find_SubRoot(this._Root, this.categoryRoots.Corporate);
if (!corp)
return;
/*
corp.Children = [
{
Id: this.categoryRoots.Corporate + "_fake",
Parent : this._Root.Id,
Flags: this.KbFlags.Fail,
Name: this._getUnavailableText(),
Disabled: true,
Available: false,
Languages: null,
Children : []
}
];
corp.Available = false;
corp.Disabled = true;
corp.Flags = this.KbFlags.Fail;
*/
corp.Children = [];
this._Root.Children.DeleteIf({ field: "Id", value: corp.Id });
this._QZState.CorporateCheckState = 0;
this._QZState.CorporateCheckData = null;
this._QZState.CorporateCheckFlags = 2;
this._checkedItems.DeleteIf(function (it) {
return it.StartsWith("2"); // Remove all Corporate items from checked.
});
if (notify && this._Root.isInitialized) {
this._this.trigger("isLoadingChanged", corp.Id);
}
},
prepare_Items: function (items) {
items.ForEach(function (i) {
if (i.Parent === "|1")
i.Flags = (i.Flags || 0) | 1;
if (i.Children == null)
i.Children = [];
if (i.LangTT == null)
IHS.Model.KBTreeItem.makeLangTooltip(i);
if (i.Disabled == null)
IHS.Model.KBTreeItem.makeDisabled(i);
// KC client. Kbs can be disabled by Admin.
if (IHS.Model.Data.Loader.module == "kc" && i.DisabledByAdmin == null)
IHS.Model.KBTreeItem.makeDisabledByAdmin(i)
});
},
onInitialFailed: function (err) {
this._Root.isInitialized = true;
var unavailableText = this._getUnavailableText();
this._Root.Children = [];
if (this.categoryRoots.Articles) {
this._Root.Children.push(
{
Id: this.categoryRoots.Articles,
Parent: this._Root.Id,
Flags: this.KbFlags.Fail,
Name: "",
Languages: [],
Children:
[
{
Id: this.categoryRoots.Articles + "_fake",
Parent: this.categoryRoots.Articles,
Flags: this.KbFlags.Fail,
Name: unavailableText,
Children: []
}
]
}
);
}
if (this.categoryRoots.EBooks) {
this._Root.Children.push(
{
Id: this.categoryRoots.EBooks,
Parent: this._Root.Id,
Flags: this.KbFlags.Fail,
Name: "",
Languages: [],
Children:
[
{
Id: this.categoryRoots.EBooks + "_fake",
Parent: this.categoryRoots.EBooks,
Flags: this.KbFlags.Fail,
Name: unavailableText,
Children: []
}
]
}
);
}
if (this.categoryRoots.Patents) {
this._Root.Children.push(
{
Id: this.categoryRoots.Patents,
Parent: this._Root.Id,
Flags: this.KbFlags.Fail,
Name: "",
Languages: [],
Children:
[
{
Id: this.categoryRoots.Patents + "_fake",
Parent: this.categoryRoots.Patents,
Flags: this.KbFlags.Fail,
Name: unavailableText,
Children: []
}
]
}
);
}
if (this.categoryRoots.Content) {
this._Root.Children.push(
{
Id: this.categoryRoots.Content,
Parent: this._Root.Id,
Flags: this.KbFlags.Fail,
Name: "",
Languages: [],
Children:
[
{
Id: this.categoryRoots.Content + "_fake",
Parent: this.categoryRoots.Content,
Flags: this.KbFlags.Fail,
Name: unavailableText,
Children: []
}
]
}
);
}
if (this.categoryRoots.Corporate) {
this._Root.Children.push(
{
Id: this.categoryRoots.Corporate,
Parent: this._Root.Id,
Flags: this.KbFlags.Fail,
Name: "",
Languages: [],
Children:
[
{
Id: this.categoryRoots.Corporate + "_fake",
Parent: this.categoryRoots.Corporate,
Flags: this.KbFlags.Fail,
Name: unavailableText,
Children: []
}
]
}
);
}
if (this.categoryRoots.Collections) {
this._Root.Children.push(
{
Id: this.categoryRoots.Collections,
Parent: this._Root.Id,
Flags: this.KbFlags.Fail,
Name: "",
Languages: [],
Children:
[
{
Id: this.categoryRoots.Collections + "_fake",
Parent: this.categoryRoots.Collections,
Flags: this.KbFlags.Fail,
Name: unavailableText,
Children: []
}
]
}
);
}
this._this.trigger("isLoadingChanged");
this.activated();
},
onBranchLoaded: function (id, items, onErrorCallback) {
var root = this.get_SubRoot(id);
if (root == null)
return;
// Special case. If returned array contains one item with the same Id as requested
// and Flags contains 8, then we have to switch to error handler.
if (items.length == 1 && items[0].Id == id && (items[0].Flags & 8) != 0) {
if (onErrorCallback)
onErrorCallback.call(this, items[0]);
return;
}
root.Children = [];
this.prepare_Items(items);
this.build_SubTree(root, items, null, function (info) {
if (info.level == 0 && !info.complete) {
info.complete = true;
this.apply_LoadingToFolders(items);
this.setIsError(false);
this._this.trigger("isLoadingChanged", id);
}
});
},
apply_LoadingToFolders: function (items) {
var emptyCKB = null;
for (var i = 0, l = items.length; i < l; i++) {
var item = items[i];
// Not a folder or folder already contains something. Skip.
if ((item.Flags & 1) == 0 || item.Children.length > 0)
continue;
// Item is failed and it is a subroot of Content root.
// It shall be disabled
if ((item.Flags & 8) != 0 && this._is_RootId(item.Id)) {
continue;
}
// Special case for empty Corporate KBs.
if (item.Id === "2|1") {
if (emptyCKB === null)
emptyCKB = items.First(function (it) { return it.Parent === "2|1" }) == null;
if (emptyCKB)
continue;
}
item.Children.push({
Id: item.Id + "_fake", Parent: item.Id, Name: imcon.jsres.RCALoadingEllipsis, Flags: 0x14
});
}
},
_rootIDs_cache: null,
_is_RootId: function (id) {
if (this._rootIDs_cache === null) {
this._rootIDs_cache = {};
for (var i in this.categoryRoots) {
this._rootIDs_cache[this.categoryRoots[i]] = i;
}
}
return this._rootIDs_cache[id] != null;
},
_cutOffCount: null,
build_SubTree: function (root, allItems, subItems, callBack, info) {
if (this._cutOffCount === null)
this._cutOffCount = IHS.Controllers.Browser.isOldIE() ? 100 : 1000;
if (!info)
info = { total: allItems.length, level: 0, complete: false };
info.level++;
// Search only inside items that are straight children of 'root'.
if (!subItems)
subItems = allItems.Where(function (i) { return i.Parent == root.Id && i.Id != "|1" });
for (var i = subItems.length - 1, count = this._cutOffCount; i >= 0; i-- , count-- , info.total--) {
var item = subItems[i];
// Root did not have 'Children' array before ?
if (root.Children == null) {
// Then, create it with single item.
root.Children = [item];
}
else {
// 'Children' array already exist. Let's find an item inside it.
var alreadyExist = root.Children.First(function (it) { return it.Id == item.Id });
if (alreadyExist == null) {
// Not found. Just insert it to list at the beginning.
root.Children.unshift(item);
}
else {
// Overwrite existing item with new data arrived.
$.extend(alreadyExist, false, item);
}
}
var cutOff = (count == 0);
if (item.Flags & 1) {
this.build_SubTree(item, allItems, null, callBack, info);
if (callBack)
callBack.call(this, info);
}
if (cutOff && i > 0) {
info.level++;
var _this = this;
subItems = subItems.slice(0, i);
setTimeout(function () {
info.level--;
_this.build_SubTree(root, allItems, subItems, callBack, info);
if (callBack)
callBack.call(_this, info);
}, 1);
break;
}
}
info.level--;
if (callBack)
callBack.call(this, info);
return false;
},
save_State: function () {
var settings = im.resolve("settings");
var data = $.extend(true, {}, this.get_State());
data.UpdateSearchIn = true;
data.settingsection = this.settingsection;
settings.putQueryZone(data);
},
set_State: function (state, isMultiLang) {
this._QZState = $.extend(this._QZState, true, state);
this.isMultiLang = isMultiLang;
this._this.trigger('stateUpdated');
},
get_State: function (synchStandards) {
// Special case to recalculate 'Contents' based on 'Standards'
if (synchStandards) {
this._recalcStandards();
}
return this._QZState;
},
get_Root: function () {
return this._Root;
},
_find_SubRoot: function (root, rootId) {
if (root == null || root.Id == rootId)
return root;
if (root.Children) {
for (var i = 0; i < root.Children.length; i++) {
var subRoot = this._find_SubRoot(root.Children[i], rootId);
if (subRoot != null)
return subRoot;
}
}
return null;
},
cache_CheckIds: function (category) {
if (this._QZState[category + "CheckState"] == 1) {
this._checkedItems.push(this.categoryRoots[category]);
}
else
if (this._QZState[category + "CheckState"] == 2) {
var ids = (this._QZState[category + "CheckData"] || "").split(";");
for (var i = 0; i < ids.length; i++)
this._checkedItems.push(ids[i]);
}
// Special case for 'Content' and 'Standards'
if (category == "Standards") {
if (this._QZState["StandardsCheckState"] == 1) {
this._QZState["StandardsCheckData"] = null;
this._checkedItems.push(this.categoryRoots[category]);
}
else {
if (this._QZState["ContentCheckState"] == 2 && this._QZState["ContentCheckData"]) {
// Will be recalculated below in _recheckStandards()
this._QZState["StandardsCheckState"] = 0;
this._QZState["StandardsCheckData"] = null;
}
}
}
},
_recheckStandards: function () {
if (this._QZState["ContentCheckState"] == 2 && this._QZState["ContentCheckData"]) {
this._QZState["StandardsCheckState"] = 0;
this._QZState["StandardsCheckData"] = null;
var source_checks = this._QZState["ContentCheckData"].split(';');
var movedChecked = 0, movedUnchecked = 0, movedCount = 0;
var checks = [];
for (var m in this.movedToStandardsIds) {
if (this.movedToStandardsIds.hasOwnProperty(m)) {
movedCount++;
if (source_checks.IndexOf(m) != -1) {
movedChecked++;
checks.push(m);
}
else {
movedUnchecked++;
}
}
}
if (movedChecked == movedCount && movedUnchecked == 0) {
// All Standards check.
this._QZState["StandardsCheckState"] = 1;
this._QZState["StandardsCheckData"] = null;
this._checkedItems.push(this.categoryRoots["Standards"]);
}
else {
if (movedUnchecked > 0 && movedChecked > 0) {
// Partially checked.
this._QZState["StandardsCheckState"] = 2;
this._QZState["StandardsCheckData"] = checks.join(';');
this._checkedItems = this._checkedItems.concat(checks);
}
}
}
},
_recalcStandards: function () {
var adds = [];
switch (this._QZState["StandardsCheckState"]) {
case 1:
adds = Object.keys(this.movedToStandardsIds);
break;
case 2:
adds = this._QZState["StandardsCheckData"].split(';');
break;
default:
break;
}
switch (this._QZState["ContentCheckState"]) {
case 1:
// If 'Standards' and 'Content' are both fully checked, then 'Content' should stay checked (1).
if (this._QZState["StandardsCheckState"] != 1) {
this._QZState["ContentCheckState"] = 2;
var fullChecks = this._find_SubRoot(this._Root, this.categoryRoots.Content)
.Children
.Where({ field: "Disabled", value: true, not: true })
.Select({ field: "Id" });
this._QZState["ContentCheckData"] = fullChecks.join(';');
if (adds.length > 0) {
this._QZState["ContentCheckData"] += ';' + adds.join(';');
}
}
break;
case 2:
// Partially checked. Just add partial checks from Standards.
if (adds.length > 0) {
var partChecks = this._QZState["ContentCheckData"].split(';').concat(adds);
this._QZState["ContentCheckData"] = partChecks.join(';');
}
break;
case 0:
// 'Content' is turned off, so we add 'Standards' as selected.
if (adds.length > 0) {
this._QZState["ContentCheckState"] = 2;
this._QZState["ContentCheckData"] = adds.join(';');
}
break;
}
},
_checkedItems: null,
get_CheckedItems: function () {
if (this._checkedItems == null) {
this._checkedItems = [];
for (var cat in this.categoryRoots) {
if (typeof (cat) == 'string')
this.cache_CheckIds(cat);
}
}
return im.copyObject(this._checkedItems);
},
// KC client only.
updateQZStateFlags: function (id, state) {
if (!this._is_RootId(id)) return;
for (var cat in this.categoryRoots) {
if (this.categoryRoots[cat] == id && !(this._QZState[cat + "CheckFlags"] & 4)) {
this._QZState[cat + "CheckFlags"] = state;
}
}
},
set_CheckedItems: function (items) {
this._checkedItems = items.Where(function () { return true; });
for (var cat in this.categoryRoots) {
if (typeof (cat) == 'string') {
if (this._QZState[cat + "CheckState"] != undefined) {
this._QZState[cat + "CheckData"] = null;
this._QZState[cat + "CheckState"] = 0;
}
}
}
for (var i = 0; i < this._checkedItems.length; i++) {
var id = this._checkedItems[i];
if (this._is_RootId(id))
continue;
var rootId = null;
if (id.indexOf("2") == 0)
rootId = "2|1";
else if (id.indexOf("6") == 0)
rootId = "6|1";
else {
var item = this._find_SubRoot(this._Root, id);
if (item != null)
rootId = item.Parent;
}
for (var cat in this.categoryRoots) {
if (this.categoryRoots[cat] == rootId) {
this._QZState[cat + "CheckState"] = 2;
if (this._QZState[cat + "CheckData"] == null)
this._QZState[cat + "CheckData"] = id;
else
this._QZState[cat + "CheckData"] = this._QZState[cat + "CheckData"] + ";" + id;
}
}
}
for (var cat in this.categoryRoots) {
if (typeof (cat) == 'string') {
if (this._QZState[cat + "CheckState"] != undefined) {
var id = this.categoryRoots[cat];
var index = this._checkedItems.IndexOf(id);
if (index != -1) {
this._QZState[cat + "CheckState"] = 1;
this._QZState[cat + "CheckData"] = null;
}
}
}
}
},
_expandedItems: null,
get_ExpandedItems: function () {
if (this._expandedItems == null) {
if (this._QZState.ExpandedItems)
this._expandedItems = this._QZState.ExpandedItems.split(";");
else
this._expandedItems = [];
var settings = im.resolve("settings");
this._expandedItems = this._expandedItems.Union((settings.getLocal("ExpandedKBItems") || "").split(";"));
}
return im.copyObject(this._expandedItems);
},
save_ExpandedItems: function () {
if (this._expandedItems == null)
return;
im.resolve("settings").putLocal("ExpandedKBItems", this._expandedItems.join(";"));
},
set_ExpandedItems: function (items) {
this._expandedItems = items.Where(function () { return true });
this._QZState.ExpandedItems = this._expandedItems.join(";");
},
get_SubRoot: function (rootId) {
return this._find_SubRoot(this._Root, rootId);
},
_getUnavailableText: function () {
// if (imcon.jsres.IsEnterprise) {
var adminInfo = im.resolve("settings").getAppData("adminEmail") || "";
return imcon.jsres.txtGFWContentUnavailable.replace('{0}', adminInfo);
// } else {
// return imcon.jsres.txtContentUnavailable;
// }
},
onWPClose: function () {
window.close();
},
onWPOk: function (res) {
if (res != null && res.length > 0) {
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", this.wpSrv + "_layouts/GoldfireSharePointWebParts/ParametersPage.aspx");
form.setAttribute("target", "shframe");
var hiddenField = document.createElement("input");
hiddenField.setAttribute("name", "data");
hiddenField.setAttribute("value", decodeURIComponent("IDLANG=" + this._QZState.Lang + "&searchin" + this._QZState.Lang + "=" + res));
form.appendChild(hiddenField);
var hiddenField2 = document.createElement("input");
hiddenField2.setAttribute("name", "wname");
hiddenField2.setAttribute("value", window.name);
form.appendChild(hiddenField2);
var hiddenField3 = document.createElement("input");
hiddenField3.setAttribute("name", "msite");
hiddenField3.setAttribute("value", this.isMultiLang);
form.appendChild(hiddenField3);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return;
}
else {
window.close();
}
},
notifyCheckChange: function () {
this.notify({ topic: 'srchin.checkChanged' });
},
destroy: function () {
this._Loader = null;
IHS.Model.SelectKBsModel.superclass.destroy.call(this);
}
});
/*ignore coverage*/
if (im.getItemValue(IHS, "Model.KbsFilter") === undefined) {
// Inject service and request KbList
function requestKbs() {
var app = im.resolve("ewbApp");
var injector = app && app.$injector;
if (!injector) {
injector = im.getItemValue(window, "ewbApp.mainInjector");
}
if (injector) {
var qzService = injector.get("QueryZoneService");
if (qzService) {
qzService.KnowledgeBases();
qzService.HasCorporateKnowledgeBase();
}
}
}
if (imcon.defaults.DebugMode === 2) {
var timerTick = setInterval(function () {
if (im.getItemValue(window, "ewbApp.mainInjector")) {
clearInterval(timerTick);
requestKbs();
}
}, 1000);
}
else {
requestKbs();
}
}
im.define('IHS.Model.QueryZoneModel', { 'baseClass': IHS.Model.BaseActiveModel }, {
QZState: null,
langList: [],
historyQuery: "",
historyItems: [],
historyLoader: null,
historyTimer: null,
historyEnabled: false,
baseHistoryItems: [],
baseHistoryQuery: "",
baseHistoryUpdatedAt: 0,
baseHistoryCacheExpire: 300, // History cache will expire in 5 minutes.
synLoader: null,
iseLoader: null,
browserLangLoader: null,
SMData: null,
DetectedLangName: {
'Name': "",
'Id': 0
},
originalSyns: {},
_isModified: 0,
_doNotSaveQZ: false,
_updatedOutside: false,
_maxHistoryItems: 10,
_allowKbTreeLoader: true,
_displayModeTypes:
{
HideAll: 0,
ShowFramework: 1,
ShowQueryZone: 2,
ShowResearchGuide: 4,
ShowSearchIn: 8
},
displayMode: 15,// ShowFramework | ShowQueryZone | ShowResearchGuide | ShowSearchIn,
enableKcFilter: false,
tool: null,
init: function () {
window.qzModel = this;
this.resx = imcon.jsres;
IHS.Model.QueryZoneModel.superclass.init.call(this);
this.warns = [];
this.clear_SMData();
this.QZState = IHS.Model.QueryZone.State.getDefaultState();
this.QZState.Source = "Dashboard";
this.QZState.TranslationSettings = { modified: 0, TargetLanguage: 0, SourceLanguages: [], isInitial: true/*initialization flag, true if not changed since creation*/ };
// GFIN09_SFS_275_03_0381 - send request for availability of ITA data
/*
if (this._allowKbTreeLoader)
{
im.resolve("kbtree-loader").post({ "selected": [""], "expanded": ["|1", "4|1", ""] },
$.proxy(this.onKbTreeResponse, this),
$.proxy(this.onKbTreeResponseError, this)
);
}
*/
this.synLoader = im.resolve('synonyms-loader');
this.iseLoader = im.resolve('ise-loader');
this.browserLangLoader = im.resolve('browser-lang-loader');
},
find: function (smType, isSpellOnly) {
this.updateKbScopeState();
this._extendedScope = null;
if (this.canFind()) {
this.resetWarngs();
this._this.trigger('Warnings');
this.load_ISE_ID();
this.updateQZState(smType);
this.load_SynSpellData(isSpellOnly);
this.save_Settings();
this.notify({
topic: 'activateModel',
data:
{
name: 'activate-from-queryzone',
params: this.paramsForFind()
}
});
// If timer is alive send history request.
if (this.historyTimer) {
clearTimeout(this.historyTimer);
this.historyTimer = 0;
this.requestHistoryFromServer();
}
}
},
setExtendedScope: function (scope) {
this._extendedScope = scope;
},
updateKbScopeState: function (scope) {
scope = scope || this._extendedScope;
if (!scope) return;
var qz = this.QZState;
var _ = function (prefix, data) {
if (qz[prefix + "CheckState"] == 1 || (qz[prefix + "CheckFlags"] & 0x0002) == 0x0002)
return;
qz[prefix + "CheckState"] = 2;
if (qz[prefix + "CheckData"] == null)
qz[prefix + "CheckData"] = data.join(';');
else {
var d = qz[prefix + "CheckData"].split(';').Where(function (id) { return id != null && id != ''; });
qz[prefix + "CheckData"] = data.Union(d).join(';');
}
}
for (p in scope) {
if (scope.hasOwnProperty(p) && scope[p].length > 0) {
_(p, scope[p].Where(function (id) { return id != null && id != ''; }))
}
}
if (scope)
this._this.trigger("QZState");
},
modifySearchIn: function () {
this.notify({ topic: 'modifySearchIn' });
},
paramsForFind: function () {
var p = $.extend(true, {}, this.getQZState());
// Special case. 'Corporate' source is mandatory hidden for "EWC".
if (IHS.Model.Data.Loader.module == "ew" || IHS.Model.Data.Loader.module == "kc") {
p.CorporateCheckFlags = (p.CorporateCheckFlags || 0) | 0x0002;
}
// DE32865. Personal KBs are not availble for new clients.
p.PersonalCheckFlags = (p.PersonalCheckFlags || 0) | 0x0002;
if (imcon.isOffLine) {
p.PatentsCheckFlags = 0x0002;
p.ArticlesCheckFlags = 0x0002;
p.EBooksCheckFlags = 0x0002;
p.ContentCheckFlags = 0x0002;
}
// Walk thru members which end with "CheckState"
for (var i in p) {
if (typeof i != 'string')
continue;
var index = i.indexOf("CheckState");
if (index == -1)
continue;
var prefix = i.substr(0, index);
// and turn state off if corresponding xxxFlags contains hidden (0x0002).
if ((p[prefix + "CheckFlags"] & 0x0002) == 0x0002) {
p[prefix + "CheckState"] = 0;
p[prefix + "CheckData"] = null;
}
}
return p;
},
updateAccordingToInitState: function () {
this.load_SynSpellData();
},
make_ISE_ID_Query: function () {
var data =
{
Query: this.QZState.Query
};
return data;
},
process_ISE_ID: function (res) {
if (res == null || res.DocId == null || res.DocId == "")
return;
var warnData =
{
id: IHS.Model.FactFinderData.ClientWarningCodes.ISEWarning,
type: IHS.Model.FactFinderData.WarningTypes.Client,
content: imcon.jsres.ISESearchWarning.replace('{0}', res.DocId).replace('{1}', encodeURI(res.URL))
};
this.setWarningsNewAPI([warnData]);
},
load_ISE_ID: function () {
var self = this;
var app = IHS.Model.Data.Loader.module;
if (app == "ew" || app == "kc")
return this.iseLoader
.exclusivePost(self.make_ISE_ID_Query())
.done(function (res) { self.process_ISE_ID(res); })
.fail(function () { /*self.ISE_ID = null;*/ })
.always(function () { /*self._this.trigger("Warnings");*/ });
},
preprocessSyn: function (synResponse, synRequest) {
var _this = this;
this.originalSyns = {};
if (!synResponse || !synRequest || !synRequest.SMData) {
return;
}
function setSelectedItem(sourceItem) {
_this.originalSyns[sourceItem.Synonyms[0].SMData] = true;
sourceItem.Synonyms.First(function (synItem, index) {
if (-1 != synRequest.SMData.IndexOf(synItem.SMData)) {
sourceItem.SelectedItem = index;
return true;
}
});
};
if (synResponse.MoreGeneralTerms) {
synResponse.MoreGeneralTerms.ForEach(setSelectedItem);
}
if (synResponse.MoreSpecificTerms) {
synResponse.MoreSpecificTerms.ForEach(setSelectedItem);
}
if (synResponse.Synonyms) {
synResponse.Synonyms.ForEach(setSelectedItem);
}
},
load_SynSpellData: function (isSpellOnly) {
//im.trace('load_SynSpellData');
if (this.QZState.Query == "" && isSpellOnly) {
this.getBrowserLang();
}
if (this.QZState.Query == "" && this.QZState.SMData == null)
return;
var self = this;
this.isSpellingFromServer = true;
var startTime = new Date().getTime();
//console.log('[model: start] start time: ' + startTime);
var postData = isSpellOnly
? this.make_SpellQuery()
: this.make_SynOntoSpellQuery();
if (self.SynSpellData == null)
self.SynSpellData = {};
self.SynSpellData.IsUpdating = true;
return this.synLoader
.post(postData)
.done(function (res) {
self.preprocessSyn(res, postData);
if (isSpellOnly) {
if (self.SynSpellData == null)
self.SynSpellData = {};
self.SynSpellData.SpellWords = res.SpellWords;
self.SynSpellData.BrowserLang = res.BrowserLang;
self.SynSpellData.ModifiedQuery = res.ModifiedQuery;
}
else
self.SynSpellData = res;
//var endTime = new Date().getTime() - startTime;
//console.log('[model: done] spell data received. ' + endTime + 'ms' + '. Spell Data is: ' + res.SpellWords + '. spell only: ' + isSpellOnly);
})
.fail(function () {
self.SynSpellData = {};
self.SynSpellData.BrowserLang = "";
})
.always(
function () {
if (!isSpellOnly) {
if (self.SynSpellData != null && self.SynSpellData.ModifiedQuery != null)
self.setQuery(self.SynSpellData.ModifiedQuery);
}
self._this.trigger("SynData_Loaded", isSpellOnly);
});
},
getBrowserLang: function () {
/*
var self = this;
return this.browserLangLoader
.get()
.done(function(res) {
if (self.SynSpellData == null || self.SynSpellData == undefined)
self.SynSpellData = {};
self.SynSpellData.BrowserLang = res;
})
.fail(function() {
self.SynSpellData = {};
self.SynSpellData.BrowserLang = "";
})
.always(function() {
self._this.trigger("SynData_Loaded");
});
*/
// No need to walk to Server to know browser language. It is on Client-side.
if (!this.SynSpellData)
this.SynSpellData = {};
this.SynSpellData.BrowserLang = im.getItemValue(imcon.defaults, "langDefSearch.lang") || 1033;
},
getSynonymsRender: function () {
if (this.SynSpellData == null)
return null;
return {
Caption: imcon.jsres.SynonymsCaption,
Items: [
{ Title: imcon.jsres.Synonyms, Item: this.SynSpellData.Synonyms },
{ Title: imcon.jsres.MoreGeneral, Item: this.SynSpellData.MoreGeneralTerms },
{ Title: imcon.jsres.MoreSpecific, Item: this.SynSpellData.MoreSpecificTerms }
]
};
},
updateSynSelection: function (index, selected) {
this.SynSpellData.Synonyms[index].SelectedItem = selected;
},
emulateClick_onCtrl: function (/* HTMLElement */anyCtrl, /* callBack */onClick) {
$(anyCtrl).bind(Modernizr.touch ? "touchstart" : "mousedown", this,
function (e) {
$(anyCtrl).attr("emulate-click", 1);
anyCtrl.isPressed = true;
anyCtrl.focus();
$(document).bind(Modernizr.touch ? "touchend" : "mouseup", { self: e.data, callback: onClick }, e.data.handle_EmulatedEnd);
$(document).bind("touchcancel", { self: e.data, callback: null }, e.data.handle_EmulatedEnd);
});
},
update_SMData: function (/* int */line) {
// Update "clicked" map.
if (line >= 5) {
for (var i = 0; i < 5; i++)
this.SMData[i] = [];
if (line >= 10)
this.SMData[line - 5] = [];
else
this.SMData[line + 5] = [];
this._this.trigger("QZState.SMDataChanged");
}
return this.SMData;
},
setSMData: function (i, data) {
if (this.SMData) {
this.SMData[i] = data;
this._this.trigger("QZState.SMDataChanged");
}
},
clear_SMData: function () {
if (this.SMData == null)
this.SMData = new Array(15);
for (var i = 0; i < this.SMData.length; i++)
this.SMData[i] = [];
this._this.trigger("QZState.SMDataCleared");
},
getSynData: function () {
return this.SynSpellData;
},
isSynDataAvailable: function () {
return (this.SynSpellData != null && (this.SynSpellData.Synonyms != null
|| this.SynSpellData.MoreGeneralTerms != null
|| this.SynSpellData.MoreSpecificTerms != null));
},
make_SpellQuery: function () {
return {
Query: this.getDisplayQuery(), //this.QZState.Query,
Lang: this.QZState.Lang,
QueryType: this.QZState.QType,
SpellOnly: 1
}
},
make_SynOntoSpellQuery: function () {
var data =
{
Query: IHS.Model.ResearcherFilterManager.toInternalName(this.getDisplayQuery(), false),
Lang: this.QZState.Lang,
QueryType: this.QZState.QType,
SMData: this.QZState.SMData,
SearchScope: {
Items: IHS.Model.QueryZone.State.qzState2SearchScope(this.QZState).Items
},
SynonymsType: 2
};
return data;
},
updateQZState: function (smType) {
this.QZState.SMType = smType || 0;
switch (this.QZState.SMType) {
case IHS.Model.QueryZone.SMType.SynonymsQuerySource:
case IHS.Model.QueryZone.SMType.OntologyMoreGeneralQuerySource:
case IHS.Model.QueryZone.SMType.OntologyMoreSpecificQuerySource:
if (this._originalQuery != null && this._originalQuery.length > 0) {
this.QZState.SynQuery = this.QZState.Query;
this.QZState.Query = this._originalQuery;
}
if (this.QZState.SMData == null)
this.QZState.SMData = this.SMData;
break;
default:
this._originalQuery = this.QZState.Query;
this.QZState.SMData = null;
this.clear_SMData();
break;
}
},
updateQZStateExternalSMData: function (rq) {
this._originalQuery = rq.Query;
this.SMData = rq.SMData;
this.QZState.SMData = this.SMData;
},
_getTitlesDefault: function () {
if (imcon.defaults.searchInTitles)
return parseInt(imcon.defaults.searchInTitles);
return 0;
},
_getMySubscriptionDefault: function () {
if (imcon.defaults.searchMySubscription)
return parseInt(imcon.defaults.searchMySubscription);
return 0;
},
returnContentClasses: function () {
return im.resolve('settings').returnContentClasses();
},
processQuery: function (state) {
var res = 0;
var st = state || this.QZState;
if (st && st.MySubscriptionCheckState && !this.mySubscriptionSet) {
this.mySubscriptionSet = true;
this.setQZ("MySubscriptionCheckState", 1);
}
if (this.titleStateSet || !st || !st.Query || this._getTitlesDefault() == 0) return;
var query = st.Query;
if ((query.match(//gim) || []).length > 1) return;
var regEx = new RegExp('(\\s*\\s*ET\\s*$)', 'gim');
if (regEx.test(query)) {
res = 1;
query = $.trim(query.replace(regEx, ''));
if (query.indexOf('(') == 0 && query.indexOf(')') == query.length - 1)
query = query.substring(1, query.length - 1);
st.Query = query;
this.titleStateSet = true;
}
},
initMySubscriptionSearch: function () {
var defValue = this._getMySubscriptionDefault();
var res;
switch (defValue) {
case 0:
// this._defaultMySubscriptionCheckFlags = res = 0x0002; Prevent disabling the flags
res = defValue;
this.setQZ("MySubscriptionCheckFlags", res);
break;
case 1:
case 2:
if (this.mySubscriptionSet) return;
res = defValue - 1;
this.setQZ("MySubscriptionCheckState", res);
break;
};
},
canFind: function () {
var SMType = IHS.Model.QueryZone.SMType;
var SMTypeVal = this.getQZ("SMType");
return this.isValidChecks() &&
(
this.isValidQuery() ||
SMTypeVal == SMType.SynonymsQuerySource ||
SMTypeVal == SMType.OntologyMoreGeneralQuerySource ||
SMTypeVal == SMType.OntologyMoreSpecificQuerySource
);
},
getHistoryList: function () {
var displayHistoryItems = [];
for (var i = 0; i < this.historyItems.length; i++) {
displayHistoryItems.push(IHS.Model.ResearcherFilterManager.toDisplayName(this.historyItems[i]));
}
return displayHistoryItems;
},
isValidChecks: function () {
var isCollectionMode = IHS.Model.QueryZone.State.isCollectionsMode(this.QZState);
return (!isCollectionMode &&
(
(this.QZState.ContentCheckState != 0 && (this.QZState.ContentCheckFlags & 0x0002) != 0x0002) ||
(this.QZState.PatentsCheckState != 0 && (this.QZState.PatentsCheckFlags & 0x0002) != 0x0002) ||
(this.QZState.ArticlesCheckState != 0 && (this.QZState.ArticleCheckFlags & 0x0002) != 0x0002) ||
(this.QZState.EBooksCheckState != 0 && (this.QZState.EBooksCheckFlags & 0x0002) != 0x0002) ||
(this.QZState.CorporateCheckState != 0 && (this.QZState.CorporateCheckFlags & 0x0002) != 0x0002 && IHS.Model.Data.Loader.module == "ghc") ||
(this.QZState.StandardsCheckState != 0 && (this.QZState.StandardsCheckData & 0x0002) != 0x0002)
)
) ||
(isCollectionMode && this.QZState.CollectionsCheckState != 0 && (this.QZState.CollectionsCheckFlags & 0x0002) != 0x0002);
},
isValidQuery: function () {
return $.trim(this.QZState.Query).length > 0;
},
getQZState: function () {
return this.QZState;
},
mergeCheckState: function (state) {
if (IHS.Model.Data.Loader.module !== "kc") return;
var resetCollectionsKbs = !this.enableKcFilter && (state.CollectionsCheckState != 0 && (state.CollectionsCheckFlags & 0x0002) != 0x0002) && (IHS.Model.KBUsageToolType.ITA != this.tool);
var data = im.resolve('settings').getQueryZone();
if (state && data) {
state.ContentCheckFlags = data.ContentCheckFlags;
if (data.ContentCheckFlags & 0x0001)
state.ContentCheckState = 0;
else if (resetCollectionsKbs)
state.ContentCheckState = 1;
state.PatentsCheckFlags = data.PatentsCheckFlags;
if (data.PatentsCheckFlags & 0x0001)
state.PatentsCheckState = 0;
else if (resetCollectionsKbs)
state.PatentsCheckState = 1;
state.ArticlesCheckFlags = data.ArticlesCheckFlags;
if (data.ArticlesCheckFlags & 0x0001)
state.ArticlesCheckState = 0;
else if (resetCollectionsKbs)
state.ArticlesCheckState = 1;
state.EBooksCheckFlags = data.EBooksCheckFlags;
if (data.EBooksCheckFlags & 0x0001)
state.EBooksCheckState = 0;
else if (resetCollectionsKbs)
state.EBooksCheckState = 1;
state.CorporateCheckFlags = data.CorporateCheckFlags;
if (data.CorporateCheckFlags & 0x0001)
state.CorporateCheckState = 0;
}
if (resetCollectionsKbs) {
state.CollectionsCheckFlags = state.CollectionsCheckState = 0;
state.CollectionsCheckData = null;
}
},
setQZState: function (newState, updatedOutside) {
this._updatedOutside = this._updatedOutside || !!updatedOutside;
this._isModified++;
$.extend(this.QZState, true, newState);
if (this._defaultMySubscriptionCheckFlags != undefined)
this.QZState.MySubscriptionCheckFlags = this._defaultMySubscriptionCheckFlags;
this.mergeCheckState(this.QZState);
this.processQuery();
this.fixLangs();
this._this.trigger("QZState");
if (updatedOutside)
this.notify({ topic: "QZState.UpdatedOutside" });
},
getQZ: function (fieldName, defValue) {
if (this.QZState[fieldName] != undefined)
return this.QZState[fieldName];
return defValue;
},
setQZ: function (fieldName, newValue, normalizeQuery) {
if (fieldName !== "Query" && fieldName !== "TranslationSettings")
this._isModified++;
if (fieldName === "Query" && newValue) {
newValue = IHS.Model.ResearcherFilterManager.toInternalName(newValue, normalizeQuery);
}
this.QZState[fieldName] = newValue;
// Special case. If some xxxxCheckState is changed to 0 or 1,
// then we have to reset corresponding xxxxCheckData to null.
var index = fieldName.indexOf("CheckState");
if (index != -1 && (newValue === 0 || newValue === 1)) {
this.QZState[fieldName.substr(0, index) + "CheckData"] = null;
}
if (fieldName == "StandardsCheckState") {
if (newValue === 0) {
//Remove standards from Content
IHS.Model.QueryZone.State.excludeStandards(this.QZState);
} else if (newValue === 1) {
//Add standards to Content
IHS.Model.QueryZone.State._recalcStandards(this.QZState);
}
}
IHS.Model.QueryZone.State.recheckStandards(this.QZState, []);
// Notify via old mechanism.
this._this.trigger("QZState." + fieldName);
// Notify via new mechanism.
this.notify({ topic: "QZState." + fieldName, field: fieldName, value: newValue });
//if (fieldName == "Query" && this.isHistoryEnabled())
// this.startRefreshHistory();
},
//isHistoryEnabled: function () {
// return this.historyEnabled;
//},
//enableHistory: function (on) {
// this.historyEnabled = on;
//},
//startRefreshHistory: function () {
// var newQuery = this.getQuery();
// if (newQuery)
// newQuery = newQuery.RemoveDuplicates(' ').TrimLeft(' ');
// if (this.historyQuery == newQuery)
// return;
// this.historyQuery = newQuery;
// this.historyItems = [];
// if (this.historyTimer)
// clearTimeout(this.historyTimer);
// if (this.historyQuery && this.historyQuery.length > 0) {
// if (this.replaceFromBaseHistory())
// return;
// var self = this;
// this.historyTimer = setTimeout(function () { self.requestHistoryFromServer() }, 100);
// }
// else
// this.historyTimer = 0;
// this._this.trigger("History");
//},
//replaceFromBaseHistory: function () {
// // No valid history cache. Let's send a request to Server.
// if (this.baseHistoryQuery == "" || this.baseHistoryItems.length >= this._maxHistoryItems || this.baseHistoryItems.length == 0)
// return false;
// // Data in history cache expired. Need to send a new request.
// if (new Date().valueOf() - this.baseHistoryUpdatedAt >= 1000 * this.baseHistoryCacheExpire)
// return false;
// // New query could correspond to previous request.
// if (this.historyQuery.StartsWith(this.baseHistoryQuery, true)) {
// var self = this;
// var trimmedQuerty = self.historyQuery.TrimRight(' ');
// this.historyItems = this.baseHistoryItems.Where(function (i) {
// return i.StartsWith(self.historyQuery, true) ||
// i.EqualsNoCase(trimmedQuerty);
// });
// this._this.trigger("History");
// return true;
// }
// // New query does not correspond to previous request.
// return false;
//},
//requestHistoryFromServer: function () {
// this.historyTimer = 0;
// if (this.historyLoader == null) {
// if ((this.historyLoader = im.resolve('history-query-suggestions')) == null)
// return;
// }
// var origText = this.historyQuery;
// var data = { text: origText.TrimRight(' '), limit: this._maxHistoryItems };
// if (!data.text)
// return;
// var self = this;
// this.historyLoader.get(data,
// function (r) {
// self.onHistoryArrived(origText, r)
// },
// function (e) {
// self.onError(e)
// });
//},
//onHistoryArrived: function (q, r) {
// this.baseHistoryQuery = q;
// this.baseHistoryItems = this.historyItems = r;
// this.baseHistoryUpdatedAt = new Date().valueOf();
// this._this.trigger("History");
//},
selectHistory: function (query) {
//// Select item in list or default query if -1.
//var newQuery = (index >= 0 && index < this.historyItems.length) ? this.historyItems[index] : this.historyQuery;
//this.QZState.Query = IHS.Model.ResearcherFilterManager.toInternalName(newQuery, true);
//this._this.trigger("QZState.Query");
// Select item in list or default query if -1.
this.QZState.Query = IHS.Model.ResearcherFilterManager.toInternalName(query, false);
this._this.trigger("QZState.Query");
},
//resetHistory: function () {
// this.baseHistoryQuery = "";
// this.baseHistoryItems = [];
// this.historyQuery = "";
// this.historyItems = [];
//},
getQuery: function () {
return this.getQZ("Query");
},
getDisplayQuery: function () {
return IHS.Model.ResearcherFilterManager.toDisplayName(this.getQuery());
},
setQuery: function (value, normalize) {
this.notify({ topic: "onSetQuery", newVal: value });
this.setQZ("Query", value, normalize);
},
/* ----------------- Warnings new API --------------- */
_checkIsWarningExists: function (warning) {
return (!!this.warns.First(function (entry) {
return (entry.id === warning.id && entry.type === warning.type);
}));
},
removeQueryLangDetectedWarning: function () {
this.notify({ topic: IHS.Model.FactFinderData.QueryZone.Events.QueryLangDetectedWarningRemoved });
},
setWarningsNewAPI: function (warnings) {
warnings.ForEach($.proxy(function (entry) {
if (!this._checkIsWarningExists(entry)) {
this.warns.push(entry);
}
}, this));
this._this.trigger('Warnings');
},
/* ----------------- End Warnings new API --------------- */
setWarnings: function (warnData) {
if (!this.checkWarnData(warnData))
return;
var showPkbWarning = false; //display warning about PKB
if (warnData.Type == 'Timeout' || warnData.Type == 'UnexpectedError' || warnData.Type == 'ConnectionError' || warnData.Type == 'NotAccessibleTarget') // KB did not respond, need parse list not responded sources, GFIN076.32760 - fix with ConnectionError
{
var sources = $.grep([].concat(warnData.Sources), function (x) { return !!x; });
if (sources.length != (warnData.Sources || []).length)
im.trace('Some warning sources are null or empty');
if (sources == null || sources.length == 0)
warnData.Text = imcon.jsres.TimeoutWarning.replace('{0}', "Goldfire").replace('{1}', im.resolve('settings').getSupportInfoLink());
else {
for (var i = sources.length - 1; i > -1; i--) {
var srcId = sources[i];
//check for duplicates in all warnings
var srcExists = false;
for (var j = 0; j < this.warns.length; j++)
if (this.warns[j].sources && this.warns[j].sources.find(function (src) { return src == srcId; })) {
srcExists = true;
break;
}
if (srcExists) {
sources.splice(i, 1);
continue;
}
if (srcId == 1) {
showPkbWarning = true;
sources.splice(i, 1);
}
if (srcId == 2 || parseInt(srcId.charAt(0)) == 2)
sources[i] = imcon.jsres.CorporateKnowledge;
if (srcId == 3)
sources[i] = imcon.jsres.ScientificEffects;
if (srcId == 4)
sources[i] = imcon.jsres.PatentsArticlesIHSEBooks; //imcon.jsres.PatentsArticles;
if (srcId == "4,3")
sources[i] = imcon.jsres.QZPatents;
if (srcId == "4,4")
sources[i] = imcon.jsres.QZArticles;
if (srcId == "4,5")
sources[i] = imcon.jsres.QZContent;
if (srcId == "4,7")
sources[i] = "eBooks"; /*imcon.jsres.QZContent; */
}
// delete duplicates in sources
sources.sort();
for (var i = sources.length - 1; i > 0; i--)
if (sources[i] == sources[i - 1])
sources.splice(i, 1);
if (sources.length > 0)
warnData.Text = imcon.jsres.TimeoutWarning.replace('{0}', sources.join(", "))
.replace('{1}', im.resolve('settings').getSupportInfoLink());
warnData.Sources = sources;
}
}
if (warnData.Type == 'WarningKeywordExpression')
warnData.Text = imcon.jsres.WarningKeywordExpression;
if (warnData.Type == 'XQuestionNotFound')
warnData.Text = imcon.jsres.XQuestionNotFound;
if (warnData.Type == 'XQuestionBoolStructureIncorrect')
warnData.Text = imcon.jsres.XQuestionBoolStructureIncorrect;
if (warnData.Type == 'XQuestionBoolOperIncorrect')
warnData.Text = imcon.jsres.XQuestionBoolOperIncorrect;
if (warnData.Text) {
this.warns.push({ content: warnData.Text, id: this.warns.length });
}
if (showPkbWarning) {
this.warns.push({ content: imcon.jsres.NotAccessibleTarget, id: this.warns.length });
}
this._this.trigger('Warnings');
},
checkWarnData: function (warnData) {
if (warnData.Type == 'ConnectionError') {
var qzs = $.parseJSON(JSON.stringify(this.paramsForFind())); //copy
var isCollectionMode = IHS.Model.QueryZone.State.isCollectionsMode(qzs);
if (warnData.Sources.length > 0) {
for (var i = 0; i < warnData.Sources.length; ++i) {
if (warnData.Sources[i] == 1 && qzs["PersonalCheckState"]) {
qzs["PersonalCheckState"] = 0;
}
else if (warnData.Sources[i] == 2 && qzs["CorporateCheckState"]) {
qzs["CorporateCheckState"] = 0;
}
else if ((warnData.Sources[i] == 3 || warnData.Sources[i] == 4) &&
(qzs["IMBCheckState"] ||
qzs["ArticlesCheckState"] ||
qzs["EBooksCheckData"] ||
qzs["PatentsCheckState"] ||
qzs["ContentCheckState"] ||
qzs["StandardsCheckState"]
)) {
qzs["IMBCheckState"] =
qzs["ArticlesCheckState"] =
qzs["EBooksCheckState"] =
qzs["PatentsCheckState"] =
qzs["StandardsCheckState"] =
qzs["ContentCheckState"] = 0;
}
else if ((warnData.Sources[i] == 6) && qzs["CollectionsCheckState"]) {
qzs["CollectionsCheckState"] = 0;
}
}
}
if (
(!isCollectionMode && !(qzs["PersonalCheckState"] ||
qzs["CorporateCheckState"] ||
qzs["IMBCheckState"] ||
qzs["ArticlesCheckState"] ||
qzs["EBooksCheckState"] ||
qzs["PatentsCheckState"] ||
qzs["StandardsCheckState"] ||
qzs["ContentCheckState"]
)) ||
(isCollectionMode && !qzs["CollectionsCheckState"])
)
return false;
}
return true;
},
resetWarngs: function () {
this.warns = [];
},
removeWarning: function (id, type) {
type = parseInt(type, 10);
this.warns.DeleteIf(function (entry) {
return (id == entry.id && ((type) ? type == entry.type : true));
});
this.notify({ topic: IHS.Model.FactFinderData.QueryZone.Events.WarningRemoved, data: { id: id, type: type } });
},
getWarnings: function () {
return { messages: this.warns };
},
setDoNotSaveSettings: function (v) {
this._doNotSaveQZ = v;
},
save_Settings: function () {
// Do not save settings. Owner is responsible for this. See CEFinderModel for example.
if (this._doNotSaveQZ)
return;
var settings = im.resolve("settings");
if (this._isModified == 0 && !settings.storeQueryZoneSp)
return;
this._isModified = 0;
var data = this.paramsForFind();
data.UpdateSearchIn = true;
settings.putQueryZone(data);
},
load_fromSettings: function (applyAll) {
var self = this;
var settings = im.resolve("settings");
settings.getQueryZone(null, function (qz) {
self.apply_fromSettings(qz, applyAll);
});
},
apply_fromSettings: function (qz, applyAll) {
qz.Query = this.getQuery(); // Reset query text because we do not need to remember last query in settings.
this.setLangList(qz.Languages);
if (qz.IsMultiSite)
this.setMultiSite(qz.IsMultiSite);
// Now TranslationSettings could be also overridden by incomming request.
// So, we put it under scope of next "if".
if (applyAll) {
if (!this._updatedOutside) {
if (qz.TranslationSettings) {
this.setTranslationSettings(qz.TranslationSettings);
}
// skip State flags setup: API does not regulate flags
qz.CorporateCheckFlags = undefined;
qz.PersonalCheckFlags = undefined;
qz.CollectionsCheckFlags = undefined;
qz.MySubscriptionCheckFlags = undefined;
// right now API regulates gfi.com flags
// qz.PatentsCheckFlags = undefined;
// qz.ArticlesCheckFlags = undefined;
// qz.ContentCheckFlags = undefined;
this.setQZState(qz);
}
else {
// Initialize first translation settings
var t = this.getQZ("TranslationSettings");
if (t && t.isInitial === true && qz.TranslationSettings) {
this.setTranslationSettings(qz.TranslationSettings);
}
}
}
this._isModified = 0;
var brLang = qz.BrowserMainLanguage;
if (brLang && brLang.length > 0) {
this.setQZ("BrowserLanguage", brLang);
}
this._this.trigger("QZState.Loaded");
this.notify({ topic: "QZState.Loaded" });
},
setMultiSite: function (val) {
this.QZState.IsMultiSite = val;
},
isMultiLang: function () {
return this.getLangList().length != 1;
},
setLangList: function (langList) {
this.langList = langList ? langList.slice(0) : [];
this.fixLangs();
},
fixLangs: function () {
var l = this.getLangList();
var qzState = this.getQZState();
if (l && l.length && qzState && l.First({ field: 'Id', value: qzState.Lang }) == undefined) {
qzState.Lang = 1033;
}
},
getLangList: function () {
return this.langList;
},
getTranslationSettings: function () {
return this.getQZ("TranslationSettings");
},
setTranslationSettings: function (t) {
this.setQZ("TranslationSettings", t);
im.resolve("translation-settings").put(t, true);
},
setMySubscription: function (v, dontSave) {
v = parseInt(v);
this.setQZ("MySubscriptionCheckState", v);
dontSave || im.resolve("settings").put({
Common: {
qz_mysubscr_old: v
}
});
},
getState: function () {
var state = IHS.Model.QueryZoneModel.superclass.getState.call(this);
var qzState = this.getQZState();
state.state.scope = IHS.Model.QueryZone.State.qzState2SearchScope(qzState);
state.state.query = qzState.Query;
state.state.lang = qzState.Lang;
state.state.collectionsSearchInMode = (qzState.CollectionsCheckFlags & 4) == 4;
if (this.getQZ("MySubscriptionCheckFlags") != 2)
state.state.mySubscr = qzState.MySubscriptionCheckState;
return state;
},
setState: function (state) {
IHS.Model.QueryZoneModel.superclass.setState.call(this, state);
var qzState = IHS.Model.QueryZone.State.searchScope2QZState(state.state.scope);
this._originalQuery = qzState.Query = state.state.query || qzState.Query;
qzState.Lang = state.state.lang || qzState.Lang;
if (state.state.collectionsSearchInMode)
qzState.CollectionsCheckFlags |= 4;
this.setQZState(qzState);
this.initMySubscriptionSearch();
var newVal = parseInt(state.state.mySubscr);
if (!isNaN(newVal)) {
if (this.getQZ("MySubscriptionCheckFlags") != 2) {
this.setQZ("MySubscriptionCheckState", newVal);
}
}
},
translationChanged: function () {
this.notify({ topic: 'translationChange', data: this.getTranslationSettings() });
},
subscriptionChanged: function () {
this.notify({ topic: 'subsctiptionChange', data: { value: this.getQZ("MySubscriptionCheckState") } });
},
isShowDetectedLangTooltip: function (langId) {
var langs = this.getLangList();
var targetLang = langs.First(function (i) { return i.Id == langId; });
var currentLang = this.getQZState().Lang;
//if detected lang doesn't exist in lang List
if (targetLang == null || !targetLang.Name) {
this.hideLangTooltip();
return;
}
this.DetectedLang = {
'Name': im.getLangNameById(langId),
'Id': langId
};
if (targetLang && targetLang.Id != currentLang) {
this.notify({ topic: 'qz.showDetectedLangTooltip', data: targetLang }); // for ITA mode
this._this.trigger('QueryLanguageDetected'); // for Researcher mode
}
else {
this.hideLangTooltip();
}
},
hideLangTooltip: function () {
this.notify({ topic: 'qz.HideQueryLanguageDialog' }); // for ITA mode
this._this.trigger('HideQueryLanguageDialog'); // for Researcher mode
},
getDetectedLang: function () {
return this.DetectedLang;
}
});
im.define('IHS.Model.QueryZone.State', null, {
/*string*/Query: "",
/*uint */Lang: 1033,
/*uint */QType: 0, // IM.Logic.Search.Model.ExpressionType
/*uint ? */CorporateCheckState: 1,
/*uint ? */PersonalCheckState: 0,
/*uint ? */PatentsCheckState: 1,
/*uint ? */ArticlesCheckState: 1,
/*uint ? */EBooksCheckState: 1,
/*uint ? */ContentCheckState: 1,
/*uint ? */StandardsCheckState: 1,
/*uint ? */CollectionsCheckState: 2,
/*uint ? */MySubscriptionCheckState: 1,
/*string */CorporateCheckData: null,
/*string */PersonalCheckData: null,
/*string */PatentsCheckData: null,
/*string */ArticlesCheckData: null,
/*string */EBooksCheckData: null,
/*string */ContentCheckData: null,
/*string */StandardsCheckData: null,
/*string */CollectionsCheckData: "6|2",
/*string */MySubscriptionCheckData: null,
/*int ? */CorporateCheckFlags: 0,
/*int ? */PersonalCheckFlags: 0,
/*int ? */PatentsCheckFlags: 0,
/*int ? */ArticlesCheckFlags: 0,
/*int ? */EBooksCheckFlags: 0,
/*int ? */ContentCheckFlags: 0,
/*int ? */StandardsCheckFlags: 0,
/*int ? */CollectionsCheckFlags: 0,
/*int ? */MySubscriptionCheckFlags: 0,
/*string */ExpandedItems: null,
/*bool */HasUDSCheck: false,
/*string */UDSName: null,
/*string */UDSType: null,
/*string */ResearchGuideId: null,
/*SynonymsData SynData: null*/
/*im.Logic.SMType*/SMType: 0,
/*Byte[15][]*/SMData: null,
init: function ()
{
if (imcon.isOffLine)
{
this.PatentsCheckFlags = 0x0002;
this.ArticlesCheckFlags = 0x0002;
this.EBooksCheckFlags = 0x0002;
this.ContentCheckFlags = 0x0002;
this.StandardsCheckFlags = 0x0002;
this.EBooksCheckFlags = 0x0002;
}
this.CorporateCheckFlags = IHS.Model.KbsFilter.HasCorporateKb ? 0 : 0x0002;
if (!(IHS.Model.Data.Loader.module == "ew" || IHS.Model.Data.Loader.module == "kc"))
{
this.CollectionsCheckData = "";
this.CollectionsCheckFlags = 0;
this.CollectionsCheckState = 0;
}
if (this._params) {
for (var p in this._params) {
if (typeof (this._params[p]) !== "function" && typeof (this[p]) !== "function") {
this[p] = this._params[p];
}
}
}
}
},
{
static:
{
CategoryRoots: {
Personal: "1|1",
Corporate: "2|1",
IMB: "4|1",
Articles: "4,4|1",
Patents: "4,3|1",
Content: "4,5|1",
EBooks: "4,7|1",
Collections: "6|1",
MySubscription: "crms",
Standards: "4,5,x1|1"
},
MoveToStandardsPrimaryIds: imcon.defaults.CodesAndStandardsKb.PrimaryIds,
CollectionsModeFlag: 0x4,
IsRootId: function (id) {
for (var i in this.CategoryRoots)
if (this.CategoryRoots[i] == id)
return true;
return false;
},
qzStateResetCheckData: function(qzState) {
qzState.CorporateCheckData = null;
qzState.PersonalCheckData = null;
qzState.PatentsCheckData = null;
qzState.ArticlesCheckData = null;
qzState.EBooksCheckData = null;
qzState.ContentCheckData = null;
qzState.StandardsCheckData = null;
qzState.CollectionsCheckData = null;
qzState.MySubscriptionCheckData = null;
return qzState;
},
getDefaultState: function() {
return this.searchScope2QZState(this.getDefaultSearchScope());
},
searchScope2QZState: function (searchScope) {
var qzs = new IHS.Model.QueryZone.State(null, null, true);
var ret = IHS.Model.QueryZone.State.qzStateResetCheckData(qzs);
if (searchScope == null || searchScope.Items == null)
return ret;
var checkedItems = $.map(searchScope.Items, function (val) {
if(val.Type != 0) return val.Id;
});
var udsItems = $.map(searchScope.Items, function (val) {
if(val.Type == 0) return val.Id;
});
if (udsItems != null && udsItems.length > 0)
{
ret.UDSName = udsItems[0];
ret.UDSType = 0;
}
var allChecks = 0;
var nonCollChecks = 0;
for (var cat in IHS.Model.QueryZone.State.CategoryRoots)
{
ret[cat + "CheckState"] =
checkedItems.indexOf(IHS.Model.QueryZone.State.CategoryRoots[cat]) != -1 ? 1 : 0;
//If 4,5|1 kb was selected, check both Content & Standards
if (cat == "Content" && ret[cat + "CheckState"]) {
var item = IHS.Model.QueryZone.State.CategoryRoots.Standards;
checkedItems.indexOf(item) > -1 || checkedItems.push(item);
}
if (ret[cat + "CheckState"])
{
++allChecks;
if (cat != 'Collections')
++nonCollChecks;
}
}
for (var i = 0; i < checkedItems.length; i++) {
var id = checkedItems[i];
if (IHS.Model.QueryZone.State.IsRootId(id))
continue;
for (var cat in this.CategoryRoots) {
var f = id.split('|')[0].split(',');
var cr = this.CategoryRoots[cat].split('|')[0];
if (cr == f || (f[0] == '2' && f[0] == cr)) {
ret[cat + "CheckState"] = 2;
var checkDataName = cat + "CheckData";
ret[checkDataName] = ret[checkDataName] == null ? id
: ret[checkDataName] + ";" + id;
++allChecks;
if (cat != 'Collections')
++nonCollChecks;
}
}
}
if (allChecks > nonCollChecks && nonCollChecks == 0)
ret.CollectionsCheckFlags |= IHS.Model.QueryZone.State.CollectionsModeFlag;
this.recheckStandards(ret, []);
return ret;
},
recheckStandards: function (qzState, items) {
if (qzState["ContentCheckState"] == 2 && qzState["ContentCheckData"]) {
qzState["StandardsCheckState"] = 0;
qzState["StandardsCheckData"] = null;
var source_checks = qzState["ContentCheckData"].split(';');
var movedChecked = 0, movedUnchecked = 0, movedCount = 0;
var checks = [];
var specIds = IHS.Model.KbsFilter.getSpecialKbs() || [];
for (var m = 0; m < specIds.StandardExpertsKbs.length; m++) {
movedCount++;
if (source_checks.IndexOf(specIds.StandardExpertsKbs[m]) != -1) {
movedChecked++;
checks.push(specIds.StandardExpertsKbs[m]);
}
else {
movedUnchecked++;
}
}
if (movedChecked == movedCount && movedUnchecked == 0) {
// All Standards check.
qzState["StandardsCheckState"] = 1;
qzState["StandardsCheckData"] = null;
items.push(this.CategoryRoots["Standards"]);
}
else {
if (movedUnchecked > 0 && movedChecked > 0) {
// Partially checked.
qzState["StandardsCheckState"]= 2;
qzState["StandardsCheckData"]= checks.join(';');
items = items.concat(checks);
}
}
//Define ContentCheckState
var checked = 0,
unchecked = 0;
for (var i = 0; i < specIds.ContentKbs.length; i++) {
if (~source_checks.indexOf(specIds.ContentKbs[i])) {
checked++;
} else {
unchecked++;
}
}
if (unchecked > 0) {
//Something was unchecked
qzState.ContentCheckState = checked ? 0x0002 : 0;
!checked && (qzState.ContentCheckData = null);
} else {
//Everything is checked
qzState.ContentCheckData = null;
qzState.ContentCheckState = checked ? 1 : 0;
}
}
return items;
},
_recalcStandards: function (qzState) {
var adds =[];
switch (qzState["StandardsCheckState"]) {
case 1:
adds = IHS.Model.KbsFilter.getSpecialKbs().StandardExpertsKbs || [];
break;
case 2:
adds = qzState["StandardsCheckData"].split(';');
break;
default:
break;
}
switch (qzState["ContentCheckState"]) {
case 1:
// If 'Standards' and 'Content' are both fully checked, then 'Content' should stay checked (1).
if (qzState["StandardsCheckState"] != 1) {
qzState["ContentCheckState"] = 2;
var fullChecks = IHS.Model.KbsFilter.getSpecialKbs().ContentKbs || [];
qzState["ContentCheckData"] = fullChecks.join(';');
if (adds.length > 0) {
qzState["ContentCheckData"] += ';' +adds.join(';');
}
}
break;
case 2:
// Partially checked. Just add partial checks from Standards.
if (adds.length > 0) {
var partChecks = qzState["ContentCheckData"].split(';').concat(adds).Unique();
qzState["ContentCheckData"] = partChecks.join(';');
}
break;
case 0:
// 'Content' is turned off, so we add 'Standards' as selected.
if (adds.length > 0) {
qzState["ContentCheckState"] = 2;
qzState["ContentCheckData"] = adds.join(';');
}
break;
}
},
excludeStandards: function(qzState) {
if (qzState.StandardsCheckState == 0 && qzState.ContentCheckData) {
var items = qzState.ContentCheckData.split(";");
var kbs = IHS.Model.KbsFilter.getSpecialKbs().StandardExpertsKbs;
items.DeleteIf(function (item) { return kbs.indexOf(item) > -1; });
qzState.ContentCheckData = items.join(";");
if (!qzState.ContentCheckData) {
qzState.ContentCheckData = null;
qzState.ContentCheckState = 0;
}
}
},
getDefaultSearchScope: function () {
var kbList, ret = { Items: [] };
im.resolve("settings").get({ Common: ["qz_ss"] }, function (settings) {
if (settings && settings.Common && settings.Common.qz_ss) {
var decoded = JSON.parse(settings.Common.qz_ss);
if (decoded && decoded.sources) {
// DE71649: Check both variants of 'sources' field. It could be either an array or
// a string of Ids separated by ';'
if (typeof (decoded.sources) === "string")
kbList = decoded.sources.split(";");
else {
if ($.isArray(decoded.sources)) {
kbList = [].concat(decoded.sources);
}
}
}
}
});
if (!kbList || !kbList.length) {
return this.qzState2SearchScope(new IHS.Model.QueryZone.State());
}
for (var i = 0; i < kbList.length; i++) {
ret.Items.push({
Id: kbList[i],
Type: kbList[i].indexOf("6") == 0 ? 4 : 1
});
}
return ret;
},
qzState2SearchScope: function (qzState) {
var ret = { Items : []};
var isCollectionMode = IHS.Model.QueryZone.State.isCollectionsMode(qzState);
this._recalcStandards(qzState);
for (var cat in this.CategoryRoots) {
// Skip Titles and Subscription from searchScope.
if (cat === 'Titles' || cat === 'MySubscription' || cat == "Standards")
continue;
// filter checks by mode
if (isCollectionMode != (cat == 'Collections'))
continue;
if (qzState[cat + "CheckState"] == 1) {
ret.Items.push({ Id: this.CategoryRoots[cat], Type: cat == 'Collections' ? 4 : 1 });
}
else {
if (qzState[cat + "CheckState"] == 2) {
var ids = (qzState[cat + "CheckData"] || "").split(";");
for (var i = 0; i < ids.length; i++) {
ret.Items.push({ Id: ids[i], Type: cat == 'Collections' ? 4 : 1 });
}
}
}
}
if (qzState.UDSName != null && qzState.UDSName.length)
{
ret.Items.push({ Id: qzState.UDSName, Type: 0 });
}
return ret;
},
qzState2SearchScopeNew: function (qzState) {
var ret = {
KnowledgeBases: [],
KnowledgeCollections: []
};
this._recalcStandards(qzState, []);
var isCollectionMode = IHS.Model.QueryZone.State.isCollectionsMode(qzState);
for (var cat in this.CategoryRoots) {
// Skip Titles and Subscription from searchScope.
if (cat === 'Titles' || cat === 'MySubscription' || cat == "Standards")
continue;
// filter checks by mode
if (isCollectionMode != (cat == 'Collections'))
continue;
if (qzState[cat + "CheckState"] == 1) {
if (cat == 'Collections')
ret.KnowledgeCollections.push(this.CategoryRoots[cat]);
else
ret.KnowledgeBases.push(this.CategoryRoots[cat]);
}
else
if (qzState[cat + "CheckState"] == 2) {
var ids = (qzState[cat + "CheckData"] || "").split(";");
for (var i = 0; i < ids.length; i++) {
if (cat == 'Collections')
ret.KnowledgeCollections.push(ids[i]);
else
ret.KnowledgeBases.push(ids[i]);
}
}
}
return ret;
},
searchScopeEquals: function (sc1, sc2) {
if (sc1.Items.length != sc2.Items.length)
return false;
for (var i = 0, l1 = sc1.Items.length; i < l1; i++) {
var sc2Item = null;
for (var j = 0, l2 = sc2.Items.length; j < l2; j++) {
if (sc1.Items[i].Id == sc2.Items[j].Id) {
sc2Item = sc2.Items[j];
break;
}
}
if (sc2Item == null)
return false;
}
return true;
},
isCollectionsMode: function(qzs)
{
return (qzs.CollectionsCheckFlags && (qzs.CollectionsCheckFlags & IHS.Model.QueryZone.State.CollectionsModeFlag) == IHS.Model.QueryZone.State.CollectionsModeFlag);
}
}
});
im.define('IHS.Model.QueryZone.SMType', null, null,
{
'static': {
FindQuerySource: 0,
SynonymsQuerySource: 1,
OntologyMoreGeneralQuerySource: 2,
OntologyMoreSpecificQuerySource: 3,
SpellcheckerQuerySource: 4,
ChangeLocusSource: 5,
DocFilterSource: 6
}
});
im.define('IHS.Model.SynOntoSpellResult', null,
{
/*string */ModifiedQuery: "",
/*List */Synonyms: [],
/*List */Spellwords: [],
/*List */MoreGeneralTerms: [],
/*List */MoreSpecificTerms: [],
/*Byte[] */QueryCompareData: []
});
im.define('IHS.Model.CeFinder.State', null, {
Concepts: [],
ConceptIdSelected: 0,
SessionId: null
});
im.define('IHS.Model.QueryZoneView', null, null,
{
'static': {
Dashboard: 0,
FactFinder: 1,
MyAlerts: 2,
CEFinder: 3
}
});
im.define('IHS.Model.AdvancedFilter', { 'baseClass': IHS.Model.BaseActiveModel },
{
allFilters: [],
activeFilters: [],
itemTemplate: "",
FILTER_TYPE_ITEM_MAX_COUNT: 15,
QUERY_MAX_LENGTH: 4096,
_sourceQuery: null,
_combinedQuery: null,
QZViewMode: 0,
QZState: null,
init: function () {
im.autoProperty(this, "viewMode", 0); // render as usual with 'Find' button, viewMode == IHS.Model.QueryZoneView.FactFinder || IHS.Model.QueryZoneView.Dashboard
im.autoProperty(this, "parseError", null);
im.autoProperty(this, "loadingError", null);
im.autoProperty(this, "isLoaded", false);
im.autoProperty(this, "MainQuery", "", this.onMainQueryHandler);
im.autoProperty(this, "FreeModeQuery", "");
im.autoProperty(this, "SavedQueries", []);
im.autoProperty(this, "emptyFilters", false);
this.allFilters = [];
this.activeFilters = [];
IHS.Model.AdvancedFilter.superclass.init.call(this);
this._validationErrors = {
'UnbalancedRoundBracketsException': imcon.jsres.AS_UnbalancedRoundBracketsException,
'QuerySyntaxException': imcon.jsres.AS_QuerySyntaxException,
'EmbeddedFilterException': imcon.jsres.AS_EmbeddedFilterException,
'UnexpectedException': imcon.jsres.AS_UnexpectedException,
'InvalidDateFormatException': imcon.jsres.AS_InvalidDateFormatException,
'InvalidPubDateFormatException': imcon.jsres.AS_InvalidPubDateFormatException,
'EmbeddedFilterExceptionDate': imcon.jsres.AS_EmbeddedFilterExceptionDate,
'UnexpectedError': imcon.jsres.AS_UnexpectedException,
'UnbalancedRoundBracketsExceptionCombine': imcon.jsres.AS_UnbalancedRoundBracketsExceptionCombine,
'QuerySyntaxExceptionCombine': imcon.jsres.AS_QuerySyntaxExceptionCombine,
'QueryTooLong': imcon.jsres.AS_QueryTooLong
};
this._conversionErrors = {
'UnbalancedRoundBracketsException': imcon.jsres.AS_UnbalancedRoundBracketsException,
'EmbeddedFilterException': imcon.jsres.AS_EmbeddedFilterException,
'UnexpectedException': imcon.jsres.QBUnexpectedException,
'UnexpectedError': imcon.jsres.AS_UnexpectedException,
'QuerySyntaxException': imcon.jsres.QBQuerySyntaxException,
'BoolOperatorException': imcon.jsres.AS_BoolOperatorException
};
if (this._params) {
this.QZViewMode = this._params.QZViewMode;
this.QZState = this._params.QZState;
this._langId = this.QZState.Lang;
}
},
activate: function (params) {
IHS.Model.AdvancedFilter.superclass.activate.call(this, params);
this._sourceQuery = params.query;
this.activated();
this.requestSavedAlerts();
},
onMainQueryHandler: function (newVal, insist) {
var f = this.activeFilters.First(function (i) { return !i.Id });
if (f) {
// Getter
if (newVal === undefined) {
return f.Value || "";
}
else {
// Setter
f.Value = newVal;
}
}
return undefined;
},
onQuerySelected: function (data) {
this.openQuery(data);
},
openQuery: function (data) {
var query = IHS.Model.ResearcherFilterManager.toDisplayName(data[0].Query);
try {
this.searchScope = data[0].SearchScope;
var parsedQuery = this.parseQuery(query);
this.viewMode(0);
this._clearActiveFilters();
this._merge(parsedQuery);
this.notify({ topic: 'activeFiltersChanged' });
}
catch (e) {
this.viewMode(1);
this.FreeModeQuery(query);
this.parseError(e.message || e.Message || e._message);
}
},
getActiveFilters: function () {
return this.activeFilters;
},
getAvailableTypes: function () {
return this.allFilters;
},
getFilterColumns: function () {
var columns = [], _this = this;
var f = [].concat(this.allFilters).sort(function (f1, f2) { return _this._comparePopUpFilters(f1, f2) });
// Split by columns.
var columnsCount = Math.round(f.length / this.FILTER_TYPE_ITEM_MAX_COUNT);
for (var i = 0; i < columnsCount; i++) {
columns.push(f.slice(i * this.FILTER_TYPE_ITEM_MAX_COUNT, (i + 1) * this.FILTER_TYPE_ITEM_MAX_COUNT))
}
if (columnsCount * this.FILTER_TYPE_ITEM_MAX_COUNT < f.length)
columns.push(f.slice(columnsCount * this.FILTER_TYPE_ITEM_MAX_COUNT, f.length));
// Scan every item in each column
columns.ForEach(function (items) {
// and search if neibourghs have different IsGfiField. In this case we have to separate them by empty item.
for (var i = 0, l = items.length - 1; i < l; i++) {
if (im.parseBool(items[i].IsGfiField) !== im.parseBool(items[i + 1].IsGfiField)) {
items.splice(i + 1, 0, null);
break;
}
}
});
return columns;
},
addFilter: function () {
var _this = this;
var nextFilter = this.allFilters.First(function (f) {
return f.Id != null && _this.activeFilters.First(function (f2) { return f2.Id == f.Id }) == null;
});
if (!nextFilter)
nextFilter = this.allFilters[0];
nextFilter = im.deepCopy(nextFilter, ["parent"]);
if (!nextFilter)
return null;
// Insert new item at the end of array, but BEFORE the last item (main query).
var index = this.activeFilters.length - 1;
this.activeFilters.splice(index, 0, nextFilter);
this.notify({ topic: "filterAdded", filter: nextFilter, index: index });
return nextFilter;
},
deleteFilter: function (index) {
if (index >= 0 && index < this.activeFilters.length - 1) { // Because the last one is empty filter (main query).
var r = { topic: "filterDeleting", index: index, cancelled: false };
this.notify(r);
if (!r.cancelled) {
this.activeFilters.splice(index, 1);
this.notify({ topic: "filterDeleted", index: index });
return true;
}
}
return false;
},
canFind: function () {
if (this.isLoading)
return false;
var nonEmpty = false;
if (this.viewMode() == 0) {
nonEmpty = this.activeFilters.First(function (f) { return (f.Value && f.Value.TrimAll()) });
}
else {
var q = this.FreeModeQuery();
nonEmpty = q && q.TrimAll();
}
if (nonEmpty)
return true;
return false;
},
clearAllFilters: function (onlyList) {
this.searchScope = null;
for (var i = 0; i < this.activeFilters.length; i++) {
if (this.activeFilters[i].Id)
this.setFilterText(i, "");
}
if (!onlyList) {
this.MainQuery("", true);
this.FreeModeQuery("", true);
}
if (this.QZViewMode === 2)
this.activeFilters = [];
else
this.activeFilters = im.deepCopy(this.allFilters.Where(function (it) { return im.parseBool(it.IsDefaultForAdvanceSearch) }).sort(this._compareFilters), ["parent"]);
this._fixFiltersOrder();
this.notify({ topic: "allFiltersCleared", onlyList: onlyList });
},
setFilterText: function (index, text, insist) {
var filter = this.activeFilters[index];
if (filter) {
if (!filter.Id) {
this.MainQuery(text, insist);
return true;
}
else {
if (filter.Value != text || insist) {
var not = {
topic: "filterTextChanged",
filter: filter,
index: index,
oldText: filter.Value
};
filter.Value = text;
this.notify(not);
return true;
}
}
}
return false;
},
setFilterType: function (index, type, insist) {
var newFilter = this.allFilters.First(function (i) { return i.Id == type });
var filter = this.activeFilters[index];
if (filter && filter.Id && newFilter) {
if (filter.Id != type || insist) {
var not = {
topic: "filterTypeChanged",
oldFilter: filter,
filter: newFilter,
index: index
};
var oldValue = filter.Value;
this.activeFilters[index] = im.deepCopy(newFilter, ["parent"]);
this.activeFilters[index].Value = oldValue;
this.notify(not);
return true;
}
}
return false;
},
getDlgSize: function () {
if (this.settings && this.settings.AdvFilter) {
return $.parseJSON(this.settings.AdvFilter);
}
var settingsCommon = im.resolve("settings").getCached("Common");
if (settingsCommon && settingsCommon.AdvFilter) {
return $.parseJSON(settingsCommon.AdvFilter);
}
return null;
},
parseQuery: function (query, type) {
query = query || this._sourceQuery;
var data = this._prepareData();
var parser = new QueryAnalizer.QueryParser(data);
var filters = [];
try {
var parsedFields = parser.parse(query, { name: 'in', priority: 3 });
while (parsedFields != null) {
if (parsedFields.fieldType == QueryAnalizer.FieldType.field) {
filters.push({ Id: parsedFields.id, Value: parsedFields.fieldValue });
}
parsedFields = parsedFields.nextField;
}
}
catch (e) {
// GFIN10_SFS_279_03_2183_R001
if (type == 1 && e && e.name == 'UnexpectedException' && e.message && e.message.indexOf('[QueryParser.prototype._validateOperators]') > -1)
e.name = 'BoolOperatorException';
throw new Error(this._errorTextByType(e, type));
}
return filters;
},
// Type - type of errors:
// 1 - conversion errors
// 0 - validation errors
_errorTextByType: function (err, type) {
var errors = type == 1 ? this._conversionErrors : this._validationErrors;
if (err.name == 'UnexpectedException' && type != 1) return '';
var txt = (errors[err.name] || errors['UnexpectedError'].replace('{0}', err.message || ''));
if (err.name == 'QueryTooLong')
txt = txt.replace('{0}', err.queryLen);
return txt;
},
_prepareData: function () {
var ret = [];
var f = this.allFilters;
for (var i = 0, n = f.length; i < n; i++) {
ret.push({ id: f[i].Id, aliases: [f[i].UI.Name, f[i].Id] });
}
return ret;
},
requestSavedAlerts: function () {
//im.resolve('alerts').get(null, $.proxy(this.requestSavedAlertsCB, this), null, 14, true);
},
requestSavedAlertsCB: function (data) {
this.SavedQueries(data);
},
getDateSearchable: function () {
if (this._dateSearchable == null)
this._dateSearchable = this.allFilters.Where(function (f) { return f.IsDateSearchable; });
return this._dateSearchable;
},
setDlgSize: function (size) {
im.resolve("settings").put({ Common: { AdvFilter: JSON.stringify(size)/*, AdvFilter: null*/} });
},
saveFilters: function () {
if (this.activeFilters) {
var ids = this.activeFilters.Select(function (e) { return e.Id; });
im.resolve("settings").putLocal('activeAdvFilters', ids || []);
}
},
exportQuery: function () {
this.QZState.Query = IHS.Model.ResearcherFilterManager.toInternalName(this._getFullQuery(), true);
if (this._getFullQuery()) {
im.resolve('commands').invoke("setAlertCommand",
{
qzState: this.QZState,
onReturn: $.proxy(function (res) {
if (res && !isNaN(parseInt(res.Id))) {
// DE18351
// Alert successfully created and we've got an ID.
// Just reload recent queries.
this.requestSavedAlerts();
}
}, this)
});
}
},
saveQuery: function () {
// Do not save filters in "Query Edit" mode, because filters relate only to selected Query.
if (this.QZViewMode != 2)
this.saveFilters();
this.returnValue = this.generateOutputQuery();
},
onSuccess: function (data) {
this._dateSearchable = null;
if (!this.isActive) return;
this._parseResponse(data);
// Do not call base implementation of onSuccess(), because it calls this.activated(),
// which is already called in activate(). Avoiding problems with ready() calling.
this.error = null;
this.setIsError(false);
this.setIsLoading(false);
this.isLoaded(true);
},
generateOutputQuery: function () {
var q;
if (this.viewMode() == 0) {
q = this._combinedQuery;
}
else {
q = this.FreeModeQuery();
}
return { query: q, scope: this.searchScope }
},
_merge: function (filters) {
if (!filters) return;
var _this = this;
filters.ForEach(function (f) {
// If filter is presented in activeFilters array just update the value
var _f = _this.activeFilters.First(function (e) { return e.Id == f.Id });
if (_f)
_f.Value = f.Value;
else {
var temp = _this.getFilterById(f.Id);
if (temp) {
temp.Value = f.Value;
_this.activeFilters.push(temp);
}
else if (!f.Id)
// Main query with Id == null;
_this.activeFilters.push(f);
}
});
this.activeFilters.sort(function (a, b) {
if (a.Value && !b.Value)
return -1;
if (!a.Value && b.Value)
return 1;
return _this._compareFilters(a, b);
});
// Add main query filter if it was missed.
this._fixFiltersOrder();
},
getMainQueryFilter: function () {
return this.activeFilters.First(function (f) { return !f.Id });
},
getFilterById: function (id) {
return im.deepCopy(this.allFilters.First(function (e) { return e.Id == id }), ["parent"]);
},
combine: function (values, withIds, data) {
var parser = new QueryAnalizer.QueryParser(data || this._prepareData(), true);
var builder = new QueryAnalizer.QueryBuilder(parser);
builder.onFieldValidate = $.proxy(this._fieldValidationFunc, this);
for (var i = 0; i < values.length; i++) {
var item = values[i];
var field = new QueryAnalizer.ParsedField();
field.fieldType = QueryAnalizer.FieldType.field;
field.fieldName = item.k;
field.fieldValue = item.v;
field.index = item.index;
field.operatorWithNext = i < values.length - 1 ? QueryAnalizer.Operator.and : null;
if (field.fieldName)
field.id = parser._getFilterIdByName(field.fieldName);
builder.addField(field);
}
return builder.combine(withIds);
},
_templateSetDateValidation: function(dateString)
{
var formatter = im.resolve('dateFormatter');
var templates = IHS.Model.DateLocale.getParsingTemplates();
var checkDatePart = function(dp, val){return !dp || dp == val;};
var check = function(x){return x || x == 0;};
var verifierConverter = function(d,x, m)
{
var failRet = m[0];
if (d.year < 1601)
return failRet; // fail
try
{
var dateObj = new Date(2000, 0, 1);
if (check(d.year))
dateObj.setFullYear(d.year);
if (check(d.month))
dateObj.setMonth(d.month);
if (check(d.day))
dateObj.setDate(d.day);
if (check(d.hour))
dateObj.setHours(d.hour);
if (check(d.minute))
dateObj.setMinutes(d.minute);
if (check(d.second))
dateObj.setSeconds(d.second);
if (dateObj.getFullYear() == d.year &&
checkDatePart(d.month, dateObj.getMonth()) &&
checkDatePart(d.day, dateObj.getDate()) &&
checkDatePart(d.hour, dateObj.getHours()) &&
checkDatePart(d.minute, dateObj.getMinutes()) &&
checkDatePart(d.second, dateObj.getSeconds())
)
return ''; // success
} catch(ex)
{
return failRet; // fail
}
return failRet; // fail
};
for (var i = 0; i < templates.length; ++i)
{
var convertedDateString = formatter.convertDates($.trim(dateString), templates[i], verifierConverter);
if (!convertedDateString)
{
return true;
}
}
return false;
},
_dateValidation: function(value) {
var format = IHS.Model.DateLocale.getShortDateFormat();
var splitter = IHS.Model.DateLocale.getFormatSplitter(format);
var exception = new IHS.Model.AdvancedFilter.InvalidDateFormatException('Modification Date fileld value is invalid');
// additional checking for 31-d numbers of monthes that have 30 days only and so on
var dates = [];
if (splitter == '-') {
var trimmed = value.replace(/ /g, '');
var numbers = trimmed.split(splitter);
if (numbers.length === 2 || numbers.length > 3) { // support "yyyy-yyyy-mm-dd" "yyyy-mm-dd-yyyy-mm-dd format" "yyyy-mm-dd-yyyy" formats
var separatorPosition = 0;
for (var i = 0; i < numbers.length; i++) {
var item = numbers[i];
if (i && (item.length === 4)) break; //stop before second 'yyyy'
separatorPosition += item.length + splitter.length;
}
dates = [trimmed.substring(0, separatorPosition - splitter.length), trimmed.substring(separatorPosition)];
} else {
dates = [trimmed];
}
} else {
dates = value.split('-');
}
var $this =this;
dates.ForEach(function(oneDate) {
try {
oneDate = $.trim(oneDate);
// DE23497
// Support greater-less operators in Advanced dialog
// GFIN10_SFS_304_01_0546
if (oneDate.indexOf('>') == 0 || oneDate.indexOf('<') == 0)
if (dates.Where(function (e) { return !!e }).length > 1)
throw exception;
else
oneDate = oneDate.substring(1);
if (!$this._templateSetDateValidation(oneDate))
throw exception;
} catch(exc) {
throw exception;
}
});
},
_fieldValidationFunc: function (field_id, value) {
var d = this.getDateSearchable().Select(function (f) { return f.Id; });
if (d.indexOf(field_id) !== -1)
this._dateValidation(value);
},
trySwitchMode: function (mode) {
switch (mode) {
case 0:
if (this.advancedToSimple()) {
this.viewMode(mode);
this.notify({ topic: 'activeFiltersChanged' });
}
break;
case 1:
if (this._validateActiveFilters()) {
this.viewMode(mode);
this.FreeModeQuery(this._combinedQuery);
}
break;
}
},
advancedToSimple: function () {
var res = true;
var q = this.FreeModeQuery();
if (!q) {
this._clearActiveFilters();
return res;
}
try {
var f = this.parseQuery(q, 1);
this._clearActiveFilters();
this._merge(f);
}
catch (e) {
res = false;
this.parseError(e.message || e.Message || e._message, true);
}
return res;
},
_clearActiveFilters: function () {
this.activeFilters.ForEach(function (f) { f.Value = ""; });
},
_getFullQuery: function(){
var _this = this;
if (this.viewMode() == 1)
return this.FreeModeQuery();
var mq = this.getMainQueryFilter();
var n = 0;
// Build part of the query related to the filters.
var qf = this.activeFilters
.Where(function (f) {
return f.Id && (f.Value ? !!f.Value.TrimAll() : false);
})
.Select(function (f) {
n++;
var v = _this._getResultValue(f.Value);
return f.UI ? (v + " " + f.UI.Name) : v;
})
.join(" ");
// Merge with main query
if (mq && mq.Value.TrimAll()) {
if (n > 1)
qf = '(' + qf + ')';
if (n > 0)
return [this._getResultValue(mq.Value), qf].join(" ");
return mq.Value;
}
return qf;
},
_getResultValue: function (value) {
if (new RegExp('(' + IHS.GHC.Model.Operators.boolOperators.join('|') + ')').test(value))
value = '(' + value + ')';
return value;
},
_validateActiveFilters: function () {
// Advanced query is not validated.
if (this.viewMode() == 1)
return true;
var f = this.activeFilters;
var main, arr = [], count = 0;
for (var i = 0, n = f.length; i < n; i++) {
if (f[i].Value && f[i].Value.TrimAll())
if (f[i].Id) {
if (!arr.First(function (e) { return e.k == f[i].Id }))
count++;
arr.push({ k: f[i].Id, v: f[i].Value, index: i })
}
else
main = { k: f[i].Id, v: f[i].Value, index: i };
}
// Validate filters.
var valid = this.validateFilter(arr);
// Save built query.
var q = this._combinedQuery;
// Validate main query
var mq = '';
if (main) {
valid = this.validateFilter([main], []) && valid;
mq = this._combinedQuery.TrimAll();
}
// Clear query if validation is failed.
if (!valid)
this._combinedQuery = '';
else // Build result query
this._combinedQuery = (q ? this._checkValue(mq) : mq) + (q && mq ? ' ' : '') + (mq && count > 1 ? '(' + q + ')' : q);
return valid;
},
_checkValue: function (v) {
var operators = IHS.GHC.Model.Operators.boolOperators;
if (new RegExp(".*\\s*" + operators.join("|") + '.*\\s*', 'i').test(v))
return "(" + v + ")";
return v;
},
validateFilter: function (f, data) {
//Reset combined query
this._combinedQuery = '';
if (!f || !f.length) return true;
try {
var valid = true;
var r = this.combine(f, false, data);
var combinedQueryWithIds = this.combine(f, true, data)[0];
f = r[1];
while (f != null) {
if (f.fault != null) {
valid = false;
var type = f.fault.name;
if (type == 'EmbeddedFilterException' && f.id != null)
type = 'EmbeddedFilterExceptionDate';
if (type == 'UnbalancedRoundBracketsException')
type = 'UnbalancedRoundBracketsExceptionCombine';
if (type == 'QuerySyntaxException')
type = 'QuerySyntaxExceptionCombine';
var errTxt = this._errorTextByType({ name: type }).replace('\\n', ' ').replace('\n', ' ');
this.notify({ topic: 'validateFieldError', text: errTxt, index: f.index, id: f.id });
} else
this.notify({ topic: 'validateFieldPassed', text: errTxt, index: f.index, id: f.id });
f = f.nextField;
}
var combinedQuery = r[0].replace(/\n/g, ' ');
if (combinedQueryWithIds.length > this.QUERY_MAX_LENGTH)
throw new IHS.Model.AdvancedFilter.QueryTooLongException(combinedQueryWithIds.length);
if (valid)
this._combinedQuery = combinedQuery;
return valid;
}
catch (e) {
this.notify({ topic: 'validateFilterError', text: this._errorTextByType(e) });
}
return false;
},
_parseResponse: function (data) {
if (!data) return;
this.allFilters = [].concat($.grep(data, function(x){return x.IsSearchable;})).sort(this._compareFilters);
this.emptyFilters(this.allFilters.length == 0);
this._updateDatePrompt();
var ids = im.resolve("settings").getLocal('activeAdvFilters');
if (ids) {
this.activeFilters = im.deepCopy(this.allFilters.Where(function (f) { return ids.indexOf(f.Id) !== -1; }), ["parent"]).sort(this._compareFilters);
}
else {
this.activeFilters = im.deepCopy(this.allFilters.Where(function (it) { return im.parseBool(it.IsDefaultForAdvanceSearch) }), ["parent"]).sort(this._compareFilters);
}
//!!!!!!!!!!!!!!!
//if modify the code below see function loadQuery(). It has similar code.
//!!!!!!!!!!!!!!!
try {
var res = this.parseQuery();
this._merge(res);
}
catch (e) {
this.viewMode(1);
this.parseError(e.message || e.Message || e._message);
this.FreeModeQuery(this._sourceQuery);
}
if (this.QZViewMode === 2)
this.activeFilters = this.activeFilters.Where(function(i){return i.Value});
this._fixFiltersOrder();
},
_updateDatePrompt: function (filters) {
// Localized date examples
var dataFormat = IHS.Model.DateLocale.getShortDateFormat();
var date1 = IHS.Model.DateLocale.parseDateFromEnUS('12/02/2012', dataFormat);
var date2 = IHS.Model.DateLocale.parseDateFromEnUS('12/31/2012', dataFormat);
var date3 = IHS.Model.DateLocale.parseDateFromEnUS('6/30/2012', dataFormat);
filters = filters || this.allFilters;
filters.ForEach(function (f) {
if (f.IsDateSearchable) {
f.UI.Prompt = imcon.jsres.ExamplesString + [date1, '{0} - {1}'.format([date1, date2]),
'2012', '{0} - 2015'.format([date3])].join('; ');
}
});
},
_comparePopUpFilters: function (f1, f2) {
var hosted1 = im.parseBool(f1.IsGfiField);
var hosted2 = im.parseBool(f2.IsGfiField);
// Hosted filters shall be on top.
if (hosted1 != hosted2) {
return (0 + hosted2) - (0 + hosted1);
}
return this._compareFilters(f1, f2);
},
_compareFilters: function (f1, f2) {
// Compare by priority.
var pri1 = parseInt(f1.SearchFilterListPriority) || 0;
var pri2 = parseInt(f2.SearchFilterListPriority) || 0;
// If same priority, then sort by name.
if (pri1 == pri2)
return f1.UI.Name.localeCompare(f2.UI.Name);
else
return pri1 - pri2;
},
_fixFiltersOrder: function () {
var mq = "";
var index = this.activeFilters.IndexOf(function (f) { return !f.Id });
if (index == this.activeFilters.length - 1 && this.activeFilters.length > 0)
return;
if (index != -1) {
mq = this.activeFilters[index].Value || "";
this.activeFilters.splice(index, 1);
}
this.activeFilters.push({ Id: null, Value: mq });
},
onError: function (err) {
this.setIsLoading(false);
this.loadingError(err.userMessage || err.Message || err._message);
this.isLoaded(true);
},
startLoading: function () {
this.stopLoading();
this.setIsLoading(true);
var settings = im.resolve('settings');
//settings.getMDFilters().done($.proxy(this.onSuccess, this)).fail($.proxy(this.onError, this));
this.onSuccess(settings.getMdfFilters());
},
stopLoading: function () {
this.setIsLoading(false);
},
getFilterText: function (id, field) {
var filter = this.allFilters.First(function (f) { return f.Id == id });
if (filter)
return filter.UI[field];
return "";
},
getPromptText: function (id) {
var filter = this.allFilters.First(function (f) { return f.Id == id });
if (filter && filter.UI && filter.UI.Prompt)
return filter.UI.Prompt;
return "";
},
getDescriptionText: function (id) {
var filter = this.allFilters.First(function (f) { return f.Id == id });
if (filter) {
if (filter.UI.Description)
return filter.UI.Description;
if (filter.UI.Name)
return im.netFormat(imcon.jsres.MTFTitleTTMessage, filter.UI.Name);
}
return "";
},
deactivate: function () {
this._dateSearchable = null;
this.stopLoading();
IHS.Model.AdvancedFilter.superclass.deactivate.call(this);
}
});
IHS.Model.AdvancedFilter.InvalidDateFormatException = function (message) {
this.name = 'InvalidDateFormatException';
this.message = (message || "");
};
IHS.Model.AdvancedFilter.QueryTooLongException = function (queryLen) {
this.name = 'QueryTooLong';
this.message = 'Query is too long';
this.queryLen = queryLen;
};
im.define("IHS.Export.ActiveModel", null, null, {
'static': {
'MyData': 'mydata',
'SearchResults': 'factfinder',
'Summary': 'summary',
'ITASemanticIndex': 'ITA-SemanticIndex',
'RCASemanticIndex': 'rca-semanticIndex',
'ITAExport': 'ITA-Export',
'kbgroupfilter': 'kbgroupfilter',
'RCAExport': 'RCA-Export'
}
});
im.define("IHS.Export.Actions", null, null, {
'static': {
'Artifacts': 'artifacts',
'SearchResults': 'citations',
'Summary': 'summary',
'Stream': 'data',
'Status': 'Status',
'Table': 'table',
'PatentGraph': 'patentgraph',
'Chart': 'chart',
'Fulltext': 'fulltext',
'Biblio': 'biblio',
'ExportKbStats': 'kbstats',
'RCAModel': 'rca/model'
}
});
im.define('IHS.Model.ExportModel', { 'baseClass': IHS.Model.BaseActiveModel }, {
parentModel: null,
resources: null,
format: null,
checked: null,
settings: null,
token: null,
errorUrl: null,
warnUrl: null,
isHiddenRButons: false,
artifactId: null,
doc: null,
readonly: false,
init: function () {
IHS.Model.ExportModel.superclass.init.call(this);
this.settings = im.resolve('settings');
},
getRenderData: function () {
var o = {
'List': this._params.types || [{ id: 2, text: "Excel (xlsx)" }, { id: 3, text: "Word (docx)" }, { id: 1, text: "CSV" }, { id: 4, text: "PDF" }],
'All': this._params.allTemplate || imcon.jsres.AllResultsFormat.replace(/\{0\}/g, imcon.SearchResultLimits.Citations.DefaultCount)
};
if (this.isPNGavailabe())
o.List.push({ id: 6, text: "PNG" });
return o;
},
isPNGavailabe: function () {
return false;
},
isRButtonsEnable: function () {
return !this.isHiddenRButons;
},
'export': function () {
this.saveSettings();
return this.exportArtifacts();
},
activate: function (data) {
this.parseParameters($.extend(this._params, data));
},
trackActivity: function () {
if (this.doc != null) {
var contentCategory = IHS.Model.Services.DocumentOpener.getContentCategory(this.doc) || '';
var kbName = this.doc.Document.KbName || '';
im.resolve('commands').invoke("track-activity", { 'urlParts': ["SaveResults", "Export", contentCategory, kbName] });
}
else
im.resolve('commands').invoke("track-activity", { 'urlParts': ["SaveResults", "Export", "MultipleSources"] });
},
_getActionForITA: function (data, parentModel) {
if (data.Request && data.Request.Svg)
return IHS.Export.Actions.Chart;
if (data.Patent && data.Patent.SipId)
return parentModel.biblioOnly ? IHS.Export.Actions.Biblio : IHS.Export.Actions.Fulltext;
if (data.Request && data.Request.QueryInfo && data.Request.QueryInfo.ItaPatentCitations && data.Request.QueryInfo.ItaPatentCitations.ResultType && data.Request.QueryInfo.ItaPatentCitations.ResultType != "0")
return IHS.Export.Actions.PatentGraph;
else
return IHS.Export.Actions.Table;
},
exportArtifacts: function () {
var self = this;
if (this.parentModel && this.parentModel.getExportData) {
var temp = false;
if (this.checked == "all")
temp = true;
var data = this.parentModel.getExportData(this.isHiddenRButons == true ? null : temp, this.artifactId);
data.Format = this.format;
data.ShortDatePattern = IHS.Model.DateLocale.getShortDateFormat();
data.MonthYearPattern = IHS.Model.DateLocale.getBrowserFormats().yMformat;
data.ShortTimePattern = IHS.Model.DateLocale.getBrowserFormats().shortTime;
var _action = null;
switch (this.parentModel.name) {
case IHS.Export.ActiveModel.MyData:
_action = IHS.Export.Actions.Artifacts;
break;
case IHS.Export.ActiveModel.SearchResults:
_action = IHS.Export.Actions.SearchResults;
break;
case IHS.Export.ActiveModel.ITASemanticIndex:
_action = IHS.Export.Actions.SearchResults;
break;
case IHS.Export.ActiveModel.Summary:
_action = IHS.Export.Actions.Summary;
break;
case IHS.Export.ActiveModel.ITAExport:
//_action = data.Request.Svg ? IHS.Export.Actions.Chart : IHS.Export.Actions.Table;
_action = this._getActionForITA(data, this.parentModel);
break;
case IHS.Export.ActiveModel.kbgroupfilter:
_action = IHS.Export.Actions.ExportKbStats;
break;
}
if (_action != null)
return im.resolve('ExportController-loader', null, { action: _action })
.post(data)
.done(
function (data) {
self.onSuccess();
self.token = data.Token;
}
)
.fail($.proxy(function (jqXHR, statusText, error) {
if (statusText != 'abort') {
var errorStruct;
try {
errorStruct = $.parseJSON(jqXHR.responseText);
} catch (ex) {
errorStruct = jqXHR.responseText;
}
switch (errorStruct.errorCode) {
case 805:
this.notify({ topic: "onHandledServerErrorOccurred", data: errorStruct });
return;
}
$(this).trigger('isExportFailed', [errorStruct]);
} else
$(this).trigger('onCloseRequest');
}, self));
else
return null;
}
else
return null;
},
getStatus: function () {
return im.resolve('ExportController-loader', null, { action: IHS.Export.Actions.Status }).get({ 'token': this.token });
},
onSuccess: function () {
IHS.Model.ExportModel.superclass.onSuccess.call(this);
},
makeUrl: function (token) {
// return IHS.Model.Data.Loader.makeApiUrl('Export', IHS.Export.Actions.Stream, { 'token': this.token }) + "&errorUrl=" + encodeURIComponent(IHS.Model.Data.Loader.makeAbsUrl(this.errorUrl))
// + "&warnUrl=" + encodeURIComponent(IHS.Model.Data.Loader.makeAbsUrl(this.warnUrl));
return IHS.Model.Data.Loader.makeApiUrl('Export', IHS.Export.Actions.Stream, { 'token': this.token });
},
getUrlParams: function () {
var o = {
'action': IHS.Model.Data.Loader.makeApiUrl('Export', IHS.Export.Actions.Stream),
'token': this.token,
'errorUrl': encodeURIComponent(IHS.Model.Data.Loader.makeAbsUrl(this.errorUrl)),
'warnUrl': encodeURIComponent(IHS.Model.Data.Loader.makeAbsUrl(this.warnUrl))
};
return o;
},
saveSettings: function () {
if (this.checked != null)
this.settings.putLocal('ExportDlg-rButton', this.checked);
if (this.format != null)
this.settings.putLocal('ExportDlg-List', this.format);
},
setSelectedFormat: function (format) {
this.format = format;
},
getSelectedFormat: function () {
var id = this.settings.getLocal('ExportDlg-List');
if (id == null)
id = 2; //Excel
this.setSelectedFormat(id);
return id;
},
getCheckedRButton: function () {
var id = this.settings.getLocal('ExportDlg-rButton');
this.checked = id;
return id;
},
setCheckedRButton: function (checked) {
return this.checked = checked;
},
setExportType: function (type) {
this.type = type;
},
setReadonly: function (set) {
this.readonly = set !== false;
},
getReadonly: function () {
return this.readonly;
},
destroy: function () {
IHS.Model.ExportModel.superclass.destroy.call(this);
}
});
im.define('IHS.Model.ExportNewModel', { 'baseClass': IHS.Model.ExportModel }, {
init: function () {
IHS.Model.ExportNewModel.superclass.init.call(this);
},
activate: function (data) {
this.parseParameters($.extend(this._params, data));
this.loader = this._params.loader;
this.pageRequest = this._params.pageRequest;
this.allRequest = this._params.allRequest;
this.queryTransformer = this._params.queryTransformer;
this.skipUntyped = this._params.skipUntyped;
if (!this.allRequest)
this.isHiddenRButons = true;
else
this.isHiddenRButons = false;
},
exportArtifacts: function () {
if (!this.loader)
return null;
var self = this;
var request = this.pageRequest;
if (this.checked == "all" && this.allRequest)
request = this.allRequest;
request.Format = this.format;
request.DateTimeFormats = {
ShortDatePattern: IHS.Model.DateLocale.getShortDateFormat(),
MonthYearPattern: IHS.Model.DateLocale.getBrowserFormats().yMformat,
ShortTimePattern: IHS.Model.DateLocale.getBrowserFormats().shortTime
};
if (!this.skipUntyped) {
var expression = this.queryTransformer ? this.queryTransformer(request.Expression) : request.Expression;
request.Untyped = JSON.stringify({
'displayExpression': IHS.Model.ResearcherFilterManager.toDisplayName(expression)
});
}
return this.loader
.post(request)
.done(
function (data) {
self.onSuccess();
self.token = data.Token;
}
)
.fail($.proxy(function (jqXHR, statusText, error) {
if (statusText != 'abort') {
var errorStruct;
try {
errorStruct = $.parseJSON(jqXHR.responseText);
} catch (ex) {
errorStruct = jqXHR.responseText;
}
switch (errorStruct.errorCode) {
case 805:
this.notify({ topic: "onHandledServerErrorOccurred", data: errorStruct });
return;
}
$(this).trigger('isExportFailed', [errorStruct]);
} else
$(this).trigger('onCloseRequest');
}, self));
}
});
im.define('IHS.Model.ExportWarningModel', { 'baseClass': IHS.Model.BaseActiveModel }, {
token: null,
warnUrl: null,
errorUrl: null,
isError: null,
msg: null,
init: function () {
IHS.Model.ExportWarningModel.superclass.init.call(this);
},
activate: function (data) {
this.parseParameters($.extend(this._params, data));
},
makeUrl: function () {
return IHS.Model.Data.Loader.makeApiUrl('Export', IHS.Export.Actions.Stream, { 'token': this.token, skiperrors: true, errorUrl: this.errorUrl, warnUrl: this.warnUrl });
},
isWarning: function () {
return !this.isError;
}
});
im.define('IHS.GHC.Model.Paginator', { baseClass: IHS.Model.BaseActiveModel }, {
itemsPerPage: 20,
currentPage: 1,
totalCount: 0,
fixedPageSize: false,
itemsPerPageText: null,
itemsDropDown: [10, 20, 50, 75, 100],
onTotalCountChanged: null,
onPageChanged: null,
onItemsPerPageChanged: null,
activate: function (data) {
IHS.GHC.Model.Paginator.superclass.activate.call(this, data);
this.activated();
},
setItemsPerpage: function (value) {
this.itemsPerPage = value;
this.currentPage = 1;
$(this).trigger('onDataChanged');
if (this.onItemsPerPageChanged) {
this.onItemsPerPageChanged(value);
}
},
setCurrentPage: function (value) {
this.currentPage = value;
$(this).trigger('onDataChanged');
if (this.onPageChanged) {
this.onPageChanged(value);
}
},
setTotalCount: function (value) {
this.totalCount = value;
$(this).trigger('onDataChanged');
if (this.onTotalCountChanged) {
this.onTotalCountChanged(value);
}
},
onSuccess: function (data) {
IHS.GHC.Model.Paginator.superclass.onSuccess.call(this);
},
refresh: function () {
}
});
im.define('IHS.Model.KBUsageToolType', null, null,
{
static:
{
FactFinder: 0,
CEFinder: 1,
ITA: 2,
RCA: 3
}
});
im.define('IHS.Model.KBUsageCounterType', null, null,
{
static:
{
OpenedUrl: 0,
SavedResult: 1,
OpenedSummary: 2
}
});
im.define('IHS.Model.KBUsageEntry', null,
{
KbId: "",
Tool: 0,
Type: 0,
Value: 0
},
{
static:
{
Equals: function (i1, i2) {
return i1.KbId == i2.KbId && i1.Tool == i2.Tool && i1.Type == i2.Type;
}
}
});
im.define('IHS.Model.Services.StatsAccumulator', { 'baseClass': IHS.Model.BaseService },
{
_items: [],
_saveToServer: null,
init: function () {
if (IHS.Model.Services.StatsAccumulator.superclass)
IHS.Model.Services.StatsAccumulator.superclass.init.call(this);
this._saveToServer = $.proxy(this.saveToServer, this);
// Perform saving each 15 minutes.
// Due to low frequency of statistics events (DocumentOpen) we will save all data on each
// statistic event. See AddCounter().
//setInterval(this._saveToServer, 15 * 60 * 1000);
// In case of GFTab we have to save data if current window is being unloaded.
// In EWC/GFHC configuration it is performed automatically.
if (this.isStandalone())
$(window).bind('unload', this._saveToServer);
},
addCounter: function (ids, tool, type) {
if (!ids || !ids.length)
return;
for (var i = 0; i < ids.length; i++) {
this._addCounter(ids[i], tool, type);
}
this.saveToServer();
},
addCounterRaw: function (raw) {
return this.addCounter(raw.KbIds, raw.Tool, raw.Counter);
},
_canSaveInStats: function (id, removeAfter) {
return true; // Boris said to return all items.
if (!id.DocType)
return true;
var res = parseInt(id.DocType);
if (removeAfter)
delete id.DocType;
return res == 2 || res == 3 || res == 4;
},
_addCounter: function (id, tool, type) {
if (this._canSaveInStats(id, true) == false)
return false;
var check = { KbId: id, Tool: tool, Type: type, Value: 0 };
var entry = this._FirstOrDefault(this._items, function (i) {
return IHS.Model.KBUsageEntry.Equals(check, i);
});
if (entry == null) {
entry = check;
this._items.push(entry);
}
entry.Value++;
return true;
},
_FirstOrDefault: function (items, predicate) {
for (var i = 0, l = items.length; i < l; i++) {
if (predicate(items[i], i))
return items[i];
}
return null;
},
saveToServer: function (e) {
if (e && e.type == "unload")
$(window).unbind('unload', this._saveToServer);
var data = [];
if (this.save(data)) {
if (this._params.saveUrl != null) {
var req = {
url: this._params.saveUrl,
dataType: "json",
data: JSON.stringify(data),
type: "PUT",
contentType: "application/json"
};
$.ajax(req, null, null, '_sync');
}
else {
var settings = im.resolve("kbusage");
if (settings)
settings.post(data);
}
}
},
save: function (data, doNotRemove) {
if (this._items.length == 0)
return false;
for (var i = 0; i < this._items.length; i++) {
data.push(this._items[i]);
}
data = JSON.stringify(data);
if (doNotRemove != true)
this._items = [];
return true;
},
isStandalone: function () {
return this._params.saveUrl != null;
},
isActive: function () {
return true;
}
});
im.define('IHS.Model.Services.DocumentOpener', { 'baseClass': IHS.Model.BaseService },
{
GFCOMP_TAG: 'gfcomp:',
GFCOMP_CLSID: 'clsid=525D2381-F58C-455c-B1ED-47EF2CAF27CE',
request: null,
'showDocument_New': function (docInfo, credentials, request, dontUsePlugin, tool, event) {
// This code uses new hiliteService and waitUrlService. This technique is the same as in
// $\app\shared\documentUrl\documentUrlDirective.js
var options = {
url: (event && $(event.target).closest("[href]").attr("href")) || docInfo.Document.Url
};
var angApp = im.resolve("ewbApp");
if (angApp.$injector.get("HLService").highlight({ urlType: docInfo.Document.UrlType, url: options.url, sentences: docInfo.Sentences }))
return im.stopEvent(event);
if (angApp.$injector.get("waitUrlService").wait(options)) {
return im.stopEvent(event);
}
},
'showDocument': function (docInfo, credentials, request, dontUsePlugin, tool) {
this.request = request;
switch (docInfo.Document.Type) {
case 1:
this._showCorporate(docInfo, credentials, dontUsePlugin);
break;
case 2:
this._showEffect(docInfo);
break;
case 3:
this._showPatentFulltext(docInfo);
break;
case 4:
this._showArticle(docInfo);
break;
default:
throw new IHS.Model.ArgumentException(null, { message: 'unknown document type' }, true);
}
var contentCategory = IHS.Model.Services.DocumentOpener.getContentCategory(docInfo) || '';
var doc = docInfo.Document;
var kbName = doc.KbName || '';
im.resolve('commands').invoke("track-activity",
{
'urlParts': ["OpenDocument", contentCategory, kbName],
'kbUsage': {
DocInfo: docInfo,
KbIds: doc.KbIds,
Tool: tool || IHS.Model.KBUsageToolType.FactFinder,
Counter: IHS.Model.KBUsageCounterType.OpenedUrl
}
});
},
_convertSentences2OldFormat: function (doc) {
var ret = { Sentences: [] };
if (!doc || !doc.Sentences)
return ret;
for (var i = 0, l = doc.Sentences.length; i < l; i++) {
var it = doc.Sentences[i];
if (!it || !it.Text)
continue;
var newIt = { Text: { Original: it.Text.Src || it.Text.Value, ShowValue: it.Text.Value } };
if (it.PaintInfo && it.PaintInfo.Value)
newIt.PaintInfo = { Original: it.PaintInfo.Src || it.PaintInfo.Value, ShowValue: it.PaintInfo.Value };
ret.Sentences.push(newIt);
}
return ret;
},
'_showPatentFulltext': function (doc) {
var docNew = (imcon.defaults.useNewSearchApi && !doc.fromMyData) ? this._convertSentences2OldFormat(doc) : doc;
im.doFormPost(doc.Document.Url + "#id_0", "_blank", "jsDoc", encodeURIComponent(JSON.stringify(docNew)));
},
'_showEffect': function (doc) {
var sentences = [];
var pinfo = [];
var settings = im.resolve('settings');
var highlightSentence = null;
var paintInfo = null;
// Try to return first non-anaphoric sentence
for (var i = 0; i < doc.Sentences.length; i++) {
var item = doc.Sentences[i];
var mdf;
var isHighlightedField = (!item.Field) ||
(item.Field == 'ET0') ||
((mdf = settings.getMetadataFieldInfo(item.Field)) && mdf && mdf.self.IsBodyField);
if (isHighlightedField) {
if ((!item.IsAnaphoric || !highlightSentence) && item.Text != null) {
var txt = item.Text.Original;
if (txt == null)
txt = item.Text.Src || item.Text.Value; //support new API
if (txt == null) continue;
highlightSentence = txt;
paintInfo = item.PaintInfo.Original || item.PaintInfo.Src || item.PaintInfo.Value;
if (!item.IsAnaphoric) // right sentence found
break;
}
}
}
if (highlightSentence) {
sentences.push(highlightSentence);
if (paintInfo) pinfo.push(paintInfo);
}
im.doFormPost(doc.Document.Url, "_blank", "id", doc.Document.Number, "pinfo", pinfo, "sentences", sentences);
},
'_showCorporate': function (doc, credentials, dontUsePlugin) {
var gfCompUrl = this._preProccessGfCompUrl(doc);
if (gfCompUrl != doc.Document.Url)
doc.gfCompUrl = gfCompUrl;
doc.Document.Url = gfCompUrl;
doc.dontUsePlugin = dontUsePlugin;
var settings = IHS.Model.Services.DocumentOpener.getSettings();
if (doc.Document.ConnectorType == 8 && settings.openNetworkDocsDirectly) {
this._defaultOpenCorporate(doc);
return;
}
if ((doc.Document.ConnectorType && doc.Document.ConnectorType != 0 && doc.Document.ConnectorType != 8)
|| doc.usePostDoc || this._isPostableDoc(doc.Document.Url))
this._postDocumentOpenCorporate(doc, credentials);
else
this._defaultOpenCorporate(doc);
},
_postDocumentOpenCorporate: function (doc, credentials, docOrigin) {
var docInner = $.extend(true, {}, doc);
var mr = docInner.Document.Url.match(/doc\/([^?]+).*[&?]url=([^&]+)/);
if (mr) {
var fillDocId = decodeURIComponent(mr[1]);
docInner.Id = fillDocId;
docInner.Document.Url = decodeURIComponent(mr[2]);
docInner.Document.DocId = parseInt(fillDocId.split('|')[1]);
}
var _this = this;
var postAction = this.postDocument(docInner, credentials, function (data, textStatus, jqXHR) {
var docUrl = data.RedirectUri;
var docCopy = JSON.parse(JSON.stringify(docInner)); //$.extend can't send with window.postMessage
if(docUrl == null)
{
docUrl = [
location.protocol,
"//",
location.host,
IHS.Model.Data.Loader.makeApiUrl('document', data.DocumentViewToken),
'/',
encodeURIComponent(data.DocumentFileName || docInner.Document.Title.Original)
].join('');
// mark this document URL as 'back to GFR'
docCopy.Document.GfrUrl = true;
}
docCopy.Document.tokenUrl = docUrl;
docCopy.Document.Url = docUrl;
docCopy.usePostDoc = true;
im.resolve('dialog').deactivate();
if (doc.dontUsePlugin === true || !im.resolve('document-hl-model', null, {}).tryOpenAndHighlight(docCopy, docCopy.Document.tokenUrl)) {
im.resolve('commands').invoke("document.open", { 'uri': docCopy.Document.tokenUrl });
}
}, function () {
im.resolve('dialog').deactivate();
});
im.resolve('dialog').
alert
(
imcon.jsres['DownloadingDocument'],
'\xA0', // non breaking space (not empty and not space) string to prevent showing of default title and provide normal title height
{
onOk: function()
{
if (postAction)
postAction.abort();
im.resolve('dialog').deactivate();
},
alertButtonText: imcon.jsres['Cancel'],
alertButtonClass: 'imfindprogressbtn',
textClass: 'alertTextCentered'
}
);
},
_defaultOpenCorporate: function (doc, credentials) {
var model = im.resolve('document-hl-model', null, {});
doc.backIfNotInstalled = true;
var pureUrl = doc.Document.Url;
if (doc.dontUsePlugin === true || !model.tryOpenAndHighlight(doc, pureUrl)) {
var settings = IHS.Model.Services.DocumentOpener.getSettings();
if(doc.Document.ConnectorType == 8 && settings.openNetworkDocsDirectly)
{
pureUrl = this._checkGfComp(doc.Document.Url);
if (IHS.Controllers.Browser.isFirefox() && (pureUrl.indexOf("http") != 0 && pureUrl.indexOf("file") != 0))
pureUrl = "file:///" + pureUrl;
im.resolve('commands').invoke("document.open", { 'uri': pureUrl });
return;
}
if ((doc.Document.ConnectorType && doc.Document.ConnectorType != 0
&& !(doc.Document.ConnectorType == 8 && settings.openNetworkDocsDirectly))
|| this._isPostableDoc(doc.Document.Url)) {
var docCopy = $.extend(true, {}, doc, { Document: { Url: pureUrl }, usePostDoc: true });
this._postDocumentOpenCorporate(docCopy, credentials, doc);
} else {
im.resolve('commands').invoke("document.open", { 'uri': pureUrl });
}
}
},
openCorporateFromPlugin: function (doc) {
var pureUrl = doc.Document.Url;
var settings = IHS.Model.Services.DocumentOpener.getSettings();
if ((doc.Document.ConnectorType && doc.Document.ConnectorType != 0
&& !(doc.Document.ConnectorType == 8 && settings.openNetworkDocsDirectly))
|| this._isPostableDoc(doc.Document.Url)) {
var docCopy = JSON.parse(JSON.stringify(doc));//$.extend can't send with window.postMessage
docCopy.Document.Url = pureUrl;
docCopy.usePostDoc = true;
this._postDocumentOpenCorporate(docCopy);
} else
im.resolve('commands').invoke("document.open", { 'uri': pureUrl });
},
_preProccessGfCompUrl: function (doc) {
var url = doc.Document.Url;
var urlSrcIndex = url.indexOf('source=');
if (urlSrcIndex > -1 && this._gfCompExists(url))
url = this.GFCOMP_TAG + url.substr(urlSrcIndex);
return url;
},
_getSourcesUriParts: function (url) {
return $.grep(url.replace(this.GFCOMP_TAG, '').split('&'), function (el, i) {
var a = el.split('=');
return a.length > 1 && a[0] == 'source';
});
},
_checkGfComp: function (url) {
if (this._gfCompExists(url)) {
var sources = this._getSourcesUriParts(url);
if (sources.length > 0)
return this._checkGfComp(decodeURIComponent(sources[0].split('=')[1]));
}
return url;
},
_gfCompExists: function(url) {
return url.indexOf(this.GFCOMP_CLSID.replace(/-/g, "%2D")) > -1 ||
url.indexOf(this.GFCOMP_CLSID) > -1;
},
_hasMsgExtension: function(url) {
var re = /\.msg.?($|\?)/i;
return re.test(url);
},
_isPostableDoc: function(url) {
return this._gfCompExists(url) || this._hasMsgExtension(url);
},
'_showArticle': function (doc) {
var gfCompUrl = this._preProccessGfCompUrl(doc);
if (gfCompUrl != doc.Document.Url)
doc.gfCompUrl = gfCompUrl;
doc.Document.Url = gfCompUrl;
if ((doc.Document.ConnectorType && doc.Document.ConnectorType != 0 && doc.Document.ConnectorType != 8)
|| doc.usePostDoc || this._isPostableDoc(doc.Document.Url))
{
this._postDocumentOpenCorporate(doc);
}
else
{
var model = im.resolve('document-hl-model', null, {});
if (model && !model.tryOpenAndHighlight(doc, doc.Document.Url)) {
im.resolve('commands').invoke("document.open", { 'uri': doc.Document.Url });
}
}
},
postDocument: function (doc, credentials, cb, errcb) {
return im.resolve('document-loader', null, null).post({
Document: doc,
Credentials: credentials
}, cb, $.proxy(function (jqXHR, textStatus, errorThrown) { if (errcb) errcb(jqXHR, textStatus, errorThrown); this.onPostDocumentError(jqXHR, textStatus, errorThrown, doc); }, this));
},
onPostDocumentError: function (jqXHR, textStatus, errorThrown, doc) {
var error = JSON.parse(jqXHR.responseText);
if (error.errorCode == 505) {
$(this).trigger('DOS_onDocumentAccessDenied', [doc]);
im.resolve('dialog').activate({paramsToActivate: { doc: doc, error: error }, modelToActivate: 'open-corp-login-model'});
}
else if (error.errorCode == 509) // newer version available
{
im.resolve('dialog').activate({paramsToActivate: { doc: doc, error: error }, modelToActivate: 'open-corp-new-version-model'});
}
else if (error.errorCode == 510) // processed version is not available
{
im.resolve('dialog').activate({paramsToActivate: { doc: doc, error: error }, modelToActivate: 'open-corp-no-version-model'});
}
else {
var query = this.request && this.request.Query ? this.request.Query : null;
this.getErrorInfo(doc, query, error.errorCode, error.userMessage, function(d) {
im.resolve('dialog').alert(d.ErrorMessageDescription || d.ErrorMessage, imcon.jsres.CannotOpenDocument,
{ isRawText: true, alertButtonText: imcon.jsres.Ok, textClass: 'error-text' });
});
$(this).trigger('DOS_onPostDocumentError', [jqXHR, textStatus, errorThrown]);
this.request = null;
}
},
getErrorInfo: function (doc, query, errorCode, errorMsg, cb) {
im.resolve('document-error-loader', null, null).post({
Document: doc,
Query: query,
ErrorCode: errorCode,
ErrorMsg: errorMsg
}, cb, $.proxy(this.onLoadErrorInfoError, this));
},
onLoadErrorInfoError: function (jqXHR, textStatus, errorThrown) {
}
}, {
'static': {
'getContentCategory': function (docInfo) {
if (!docInfo) return '';
var contentTypesMapping = {
'1': imcon.jsres.KBCorporateTitle,
'2': imcon.jsres.KBEffectsTitle,
'3': imcon.jsres.KBPatentsTitle,
'4': imcon.jsres.KBArticlesTitle
};
return contentTypesMapping[docInfo.Document.Type] || '';
},
_defaultSettings: {
openDoc: {
openNetworkDocsDirectly: false,
showProposePluginInstallMsg: true,
pluginOpenDocumentErrorHandlerAdded: false
}
},
getSettings: function () {
return $.extend({}, this._defaultSettings, imcon.settings).openDoc;
}
}
}
);
im.define('IHS.Model.Services.ClientSettings', { 'baseClass': IHS.Model.BaseService },
{
'provider': null,
'init': function () {
if(!this.provider) {
this.provider = im.resolve("cookie-provider"); //cookie provider by default.
}
},
'getItem': function (/*String*/key) {
return this.provider.getItem(key);
},
'setItem': function (/*String*/key, /*Int*/age) {
return this.provider.setItem(key, age);
},
'removeItem': function(/*String*/key) {
return this.provider.removeItem(key);
}
}
);
// IM library UserDataStore processing functions set
im.define('IHS.Model.Services.UserDataStore', { 'baseClass': IHS.Model.BaseService },
{
StorageEl: null,
init: function()
{
if (!this.isLocalStorageAvailable())
{
this.StorageEl = document.getElementById(IHS.Model.Services.UserDataStore.STORAGE_ELEMENT_ID);
if (this.StorageEl)
{
if (this.StorageEl.addBehavior)
{
try
{
this.StorageEl.addBehavior("#default#userData");
this.StorageEl.load(IHS.Model.Services.UserDataStore.STORAGE_NAMESPACE); // if already loaded can throw
}
catch (e)
{
this.StorageEl = null;
}
}
else
this.StorageEl = null;
}
}
},
isAvailable: function () { return (this.isLocalStorageAvailable() || !!this.StorageEl); },
isLocalStorageAvailable: function ()
{
try
{
return !!window.localStorage.getItem;
}
catch (e)
{
return false;
}
},
isSessionStorageAvailable: function ()
{
try
{
return !!im.sessStore.getItem;
}
catch (e)
{
return false;
}
},
isAppCacheAvailable: function ()
{
try
{
return !!window.applicationCache;
}
catch (e)
{
return false;
}
},
get: function(key)
{
var sureKey = key ? key : IHS.Model.Services.UserDataStore.STORAGE_HASHES_KEYS;
if (window.localStorage)
{
return window.localStorage[IHS.Model.Services.UserDataStore.STORAGE_NAMESPACE + '_'+ sureKey];
}
// older browsers support
var stor = this.StorageEl;
if(stor){
try
{
return stor.getAttribute(sureKey);
}
catch(err) {/* if already loaded can throw*/}
}
return null;
},
set: function(key, value)
{
if (window.localStorage)
{
window.localStorage[IHS.Model.Services.UserDataStore.STORAGE_NAMESPACE+'_'+key] = value;
return;
}
// older browsers support
var stor = this.StorageEl;
if(stor){
try
{
stor.setAttribute(key, value);
stor.save(IHS.Model.Services.UserDataStore.STORAGE_NAMESPACE);
}
catch(err)
{}
}
},
addHash: function (hashVal)
{
if (hashVal.length != IHS.Model.Services.UserDataStore.VISITED_HASH_SIZE)
throw new Error(IHS.Model.Services.UserDataStore.HASH_SIZE_ERROR);
var oldVal = this.get(IHS.Model.Services.UserDataStore.STORAGE_HASHES_KEYS);
//check does hashVal already exists in the value
if (this.isHashExists(hashVal, oldVal))
return oldVal;
var newVal = hashVal + (oldVal ? oldVal : '');
//check value size
if (newVal.length > (IHS.Model.Services.UserDataStore.VISITED_HASH_COUNT_MAX * IHS.Model.Services.UserDataStore.VISITED_HASH_SIZE))
newVal = newVal.substring(0, newVal.length - IHS.Model.Services.UserDataStore.VISITED_HASH_SIZE);
return this.set(IHS.Model.Services.UserDataStore.STORAGE_HASHES_KEYS, newVal);
},
isHashExists: function (hashVal, currentCasheVal)
{
if (hashVal) {
var casheVal = (currentCasheVal ? currentCasheVal : this.get(IHS.Model.Services.UserDataStore.STORAGE_HASHES_KEYS));
var s = (casheVal ? casheVal.indexOf(hashVal) : -1);
if (s >= 0 && (s % IHS.Model.Services.UserDataStore.VISITED_HASH_SIZE) == 0){
return true;
}
}
return false;
},
isValExists: function (val, currentCasheVal) {
if (val) {
var newHash = hash.MD5(val);
return this.isHashExists(newHash, currentCasheVal);
}
return false;
},
addValue: function (newVal)
{
if (newVal) {
var newHash = hash.MD5(newVal);
return this.addHash(newHash);
}
return null;
}
},
{
'static':
{
VISITED_HASH_COUNT_MAX: 1000,
VISITED_HASH_SIZE: 32,
HASH_SIZE_ERROR: 'Hash with wrong size provided',
STORAGE_ELEMENT_ID: 'ffRoot',
STORAGE_NAMESPACE: 'VisitedLinks',
STORAGE_HASHES_KEYS: 'HashKeys'
}
}
);
///
// This class provides environment for running active models
// It can be used for main application, nested models like tabs or dialogs
im.define('IHS.Model.Sandbox', { 'baseClass': IHS.Model.BaseActiveModel }, {
sandboxName: '',
commandProcessor: null,
activeModel: null,
activation: null,
titleService: null,
modelToActivate: '',
paramsToActivate: null,
models: null,
// TODO: Application and ITA sandbox use correct activeModelChanged notification. Dialogs have _useCorrectActivateNotification set to false until the concurrency issues are fixed.
_useCorrectActivateNotification: true, // TEMP
_listOfModelsForCorrectActivation: { 'translation-model': true, 'ita-companygroup-model': true, 'ITA-Find-Assignee-model': true, 'ITA-Find-Groups-model': true, 'ita-fulltext-model': true, 'ita-newgroup-model': true }, // TEMP
init: function () {
IHS.Model.Sandbox.superclass.init.call(this);
this.commandProcessor = im.resolve('commands');
this.activation = im.resolve('activation');
this.titleService = im.resolve('title-service');
if (this.sandboxName) {
IHS.Model.Sandbox.register(this.sandboxName, this);
}
if (this.modelToActivate) {
this._useCorrectActivateNotification = !!this._listOfModelsForCorrectActivation[this.modelToActivate];
}
},
startup: function () {
this.activate();
},
activate: function (params) {
IHS.Model.Sandbox.superclass.activate.call(this);
this.selectModelToActivate();
},
executeCommand: function (name, params) {
if (this.commandProcessor) {
this.commandProcessor.invoke(name, params, this.sandboxName);
}
},
selectModelToActivate: function () {
this.activateModel(this.modelToActivate ? this.activation.map(this.modelToActivate) : this.activation.getDefault(), this.paramsToActivate, this.modelToActivate);
},
setActiveModel: function (data, params, token) {
if (this.activeModel) {
try {
this.activeModel.deactivate(
(data && this.activeModel.alias == data.alias && this.activeModel.appActivationToken == token) // re-activation
);
}
catch (e) {
im.trace(e.message);
if (im.isRegistered('commands')) im.resolve('commands').invoke('error.command', { e: e });
}
this.activeModel.removeObserver(this);
}
this.activeModel = data;
if (this.activeModel && token)
this.activeModel.appActivationToken = token;
// New and correct place to fire this topic
if (this._useCorrectActivateNotification) {
this.notify({ topic: this.getEventName('activeModelChanged') });
}
if (this.activeModel) {
this.activeModel.addObserver(this);
try {
if (this.activeModel.settingsSectionName) {
// Preload settings before activate
this.activeModel.activateWithSettings(params);
}
else { // Normal activate
this.activeModel.activate(params);
}
}
catch (e) {
im.trace(e.message);
if (im.isRegistered('commands')) im.resolve('commands').invoke('error.command', { e: e });
}
}
// Old place which is left for compatibility reasons
if (!this._useCorrectActivateNotification) {
this.notify({ topic: this.getEventName('activeModelChanged') }); // Deprecated
}
},
setActiveModelChecked: function (model, params, token) {
var simos = token ? im.resolve('simosService') : null;
if (model && simos &&
(!this.activeModel || this.activeModel.alias !== model.alias || this.activeModel.appActivationToken != token) // avoid re-check(IN/OUT) if model is already active
) {
simos.activateTool
(
token,
$.proxy
(
function () { this.setActiveModel(model, params, token); }, // successfull check-out
this
)
);
}
else
this.setActiveModel(model, params, token);
},
activateModel: function (name, params, token) {
if (!this.activeModel || this.activeModel.alias !== name || (this.modelsToActivate && this.modelsToActivate.indexOf(name) !== -1)) { // Avoid model refresh when the same model is already activated
if (!(params && params.restoreFromState)) { // Avoid model refresh when the model already restored from state
// Request registration info for model.
var modelInit = im.getRegistrationParams(name);
if (!modelInit)
throw "Model registration info not found for '" + name + "'";
if (modelInit.forceDepends && modelInit.depends) {
this.activateWithDepends(name, modelInit, params);
}
else {
var model = im.resolve(name, null, modelInit.paramsOnInit ? params : null);
if (!model && modelInit.depends) {
this.activateWithDepends(name, modelInit, params);
}
else {
this.setActiveModelChecked(model, params, token);
}
}
}
}
},
activateWithDepends: function (name, modelInit, params, modelState) {
var _this = this;
var activator = function () {
if (modelInit.loadDependsOnly)
return;
var model = im.resolve(name, null, modelInit.paramsOnInit ? params : null);
if (model && modelState)
model.setState(modelState);
_this.setActiveModel(model, params);
if (model && _this.titleService)
_this.titleService.update(model.displayName);
};
if (!IHS.Model.Sandbox._depends)
IHS.Model.Sandbox._depends = { loading: 0, files: [] };
var oldFiles = IHS.Model.Sandbox._depends;
var newFiles = {
loading: 0, files:
modelInit.depends
.Where(function (i) {
var inOldFiles = oldFiles.files.First(function (f) { return f.name == i });
return inOldFiles == null || inOldFiles.ready == false;
})
.Select(function (i) {
return {
name: i,
path: IHS.Model.Data.Loader.makeAbsUrl(i, false),
ready: false,
data: null
}
})
};
modelInit.forceDepends = false;
if ((newFiles.loading = newFiles.files.length) > 0) {
newFiles.files.ForEach(function (i) { oldFiles.files.push(i); oldFiles.loading++; });
this.setIsLoading(true);
newFiles.files.ForEach(function (i) {
var file = i;
$.ajax({
url: _this._addBuildToPath(file.path),
dataType: 'text',
type: 'GET',
cache: true,
success: function (data) {
i.data = data;
i.ready = true;
if (--oldFiles.loading <= 0) {
_this._mergeLoadedDepends(newFiles);
_this.setIsLoading(false);
activator();
}
},
error: function (err) {
_this.setIsLoading(false);
}
});
});
}
else {
activator();
}
},
_addBuildToPath: function (url) {
if (imcon.defaults.appBuild) { // "10.0.10700.10700"
return url + "?b=" + imcon.defaults.appBuild.split(".").join("");
}
else {
return url;
}
},
_mergeLoadedDepends: function (loadedPack) {
var megaFunction = [];
for (var i = 0, l = loadedPack.files.length; i < l; i++) {
var it = loadedPack.files[i];
var data = it.data;
if (it.path.EndsWith('.htm', true)) {
if ($.trim(data).indexOf('