it('should sanitize the html snippet by default', function() {
expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
toBe('
an html\nclick here\nsnippet
');
});
it('should inline raw snippet if bound to a trusted value', function() {
expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).
toBe("
an html\n" +
"click here\n" +
"snippet
");
});
it('should escape snippet without any filter', function() {
expect(element(by.css('#bind-default div')).getInnerHtml()).
toBe("<p style=\"color:blue\">an html\n" +
"<em onmouseover=\"this.textContent='PWN3D!'\">click here</em>\n" +
"snippet</p>");
});
it('should update', function() {
element(by.model('snippet')).clear();
element(by.model('snippet')).sendKeys('new text');
expect(element(by.css('#bind-html-with-sanitize div')).getInnerHtml()).
toBe('new text');
expect(element(by.css('#bind-html-with-trust div')).getInnerHtml()).toBe(
'new text');
expect(element(by.css('#bind-default div')).getInnerHtml()).toBe(
"new <b onclick=\"alert(1)\">text</b>");
});
*/
function $SanitizeProvider() {
this.$get = ['$$sanitizeUri', function($$sanitizeUri) {
return function(html) {
var buf = [];
htmlParser(html, htmlSanitizeWriter(buf, function(uri, isImage) {
return !/^unsafe/.test($$sanitizeUri(uri, isImage));
}));
return buf.join('');
};
}];
}
function sanitizeText(chars) {
var buf = [];
var writer = htmlSanitizeWriter(buf, angular.noop);
writer.chars(chars);
return buf.join('');
}
// Regular Expressions for parsing tags and attributes
var START_TAG_REGEXP =
/^<((?:[a-zA-Z])[\w:-]*)((?:\s+[\w:-]+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)\s*(>?)/,
END_TAG_REGEXP = /^<\/\s*([\w:-]+)[^>]*>/,
ATTR_REGEXP = /([\w:-]+)(?:\s*=\s*(?:(?:"((?:[^"])*)")|(?:'((?:[^'])*)')|([^>\s]+)))?/g,
BEGIN_TAG_REGEXP = /^,
BEGING_END_TAGE_REGEXP = /^<\//,
COMMENT_REGEXP = //g,
DOCTYPE_REGEXP = /]*?)>/i,
CDATA_REGEXP = //g,
SURROGATE_PAIR_REGEXP = /[\uD800-\uDBFF][\uDC00-\uDFFF]/g,
// Match everything outside of normal chars and " (quote character)
NON_ALPHANUMERIC_REGEXP = /([^\#-~| |!])/g;
// Good source of info about elements and attributes
// http://dev.w3.org/html5/spec/Overview.html#semantics
// http://simon.html5.org/html-elements
// Safe Void Elements - HTML5
// http://dev.w3.org/html5/spec/Overview.html#void-elements
var voidElements = makeMap("area,br,col,hr,img,wbr");
// Elements that you can, intentionally, leave open (and which close themselves)
// http://dev.w3.org/html5/spec/Overview.html#optional-tags
var optionalEndTagBlockElements = makeMap("colgroup,dd,dt,li,p,tbody,td,tfoot,th,thead,tr"),
optionalEndTagInlineElements = makeMap("rp,rt"),
optionalEndTagElements = angular.extend({},
optionalEndTagInlineElements,
optionalEndTagBlockElements);
// Safe Block Elements - HTML5
var blockElements = angular.extend({}, optionalEndTagBlockElements, makeMap("address,article," +
"aside,blockquote,caption,center,del,dir,div,dl,figure,figcaption,footer,h1,h2,h3,h4,h5," +
"h6,header,hgroup,hr,ins,map,menu,nav,ol,pre,script,section,table,ul"));
// Inline Elements - HTML5
var inlineElements = angular.extend({}, optionalEndTagInlineElements, makeMap("a,abbr,acronym,b," +
"bdi,bdo,big,br,cite,code,del,dfn,em,font,i,img,ins,kbd,label,map,mark,q,ruby,rp,rt,s," +
"samp,small,span,strike,strong,sub,sup,time,tt,u,var"));
// Special Elements (can contain anything)
var specialElements = makeMap("script,style");
var validElements = angular.extend({},
voidElements,
blockElements,
inlineElements,
optionalEndTagElements);
//Attributes that have href and hence need to be sanitized
var uriAttrs = makeMap("background,cite,href,longdesc,src,usemap");
var validAttrs = angular.extend({}, uriAttrs, makeMap(
'abbr,align,alt,axis,bgcolor,border,cellpadding,cellspacing,class,clear,'+
'color,cols,colspan,compact,coords,dir,face,headers,height,hreflang,hspace,'+
'ismap,lang,language,nohref,nowrap,rel,rev,rows,rowspan,rules,'+
'scope,scrolling,shape,size,span,start,summary,target,title,type,'+
'valign,value,vspace,width'));
function makeMap(str) {
var obj = {}, items = str.split(','), i;
for (i = 0; i < items.length; i++) obj[items[i]] = true;
return obj;
}
/**
* @example
* htmlParser(htmlString, {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* });
*
* @param {string} html string
* @param {object} handler
*/
function htmlParser( html, handler ) {
if (typeof html !== 'string') {
if (html === null || typeof html === 'undefined') {
html = '';
} else {
html = '' + html;
}
}
var index, chars, match, stack = [], last = html, text;
stack.last = function() { return stack[ stack.length - 1 ]; };
while ( html ) {
text = '';
chars = true;
// Make sure we're not in a script or style element
if ( !stack.last() || !specialElements[ stack.last() ] ) {
// Comment
if ( html.indexOf("", index) === index) {
if (handler.comment) handler.comment( html.substring( 4, index ) );
html = html.substring( index + 3 );
chars = false;
}
// DOCTYPE
} else if ( DOCTYPE_REGEXP.test(html) ) {
match = html.match( DOCTYPE_REGEXP );
if ( match ) {
html = html.replace( match[0], '');
chars = false;
}
// end tag
} else if ( BEGING_END_TAGE_REGEXP.test(html) ) {
match = html.match( END_TAG_REGEXP );
if ( match ) {
html = html.substring( match[0].length );
match[0].replace( END_TAG_REGEXP, parseEndTag );
chars = false;
}
// start tag
} else if ( BEGIN_TAG_REGEXP.test(html) ) {
match = html.match( START_TAG_REGEXP );
if ( match ) {
// We only have a valid start-tag if there is a '>'.
if ( match[4] ) {
html = html.substring( match[0].length );
match[0].replace( START_TAG_REGEXP, parseStartTag );
}
chars = false;
} else {
// no ending tag found --- this piece should be encoded as an entity.
text += '<';
html = html.substring(1);
}
}
if ( chars ) {
index = html.indexOf("<");
text += index < 0 ? html : html.substring( 0, index );
html = index < 0 ? "" : html.substring( index );
if (handler.chars) handler.chars( decodeEntities(text) );
}
} else {
html = html.replace(new RegExp("(.*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
function(all, text){
text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");
if (handler.chars) handler.chars( decodeEntities(text) );
return "";
});
parseEndTag( "", stack.last() );
}
if ( html == last ) {
throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
"of html: {0}", html);
}
last = html;
}
// Clean up any remaining tags
parseEndTag();
function parseStartTag( tag, tagName, rest, unary ) {
tagName = angular.lowercase(tagName);
if ( blockElements[ tagName ] ) {
while ( stack.last() && inlineElements[ stack.last() ] ) {
parseEndTag( "", stack.last() );
}
}
if ( optionalEndTagElements[ tagName ] && stack.last() == tagName ) {
parseEndTag( "", tagName );
}
unary = voidElements[ tagName ] || !!unary;
if ( !unary )
stack.push( tagName );
var attrs = {};
rest.replace(ATTR_REGEXP,
function(match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
var value = doubleQuotedValue
|| singleQuotedValue
|| unquotedValue
|| '';
attrs[name] = decodeEntities(value);
});
if (handler.start) handler.start( tagName, attrs, unary );
}
function parseEndTag( tag, tagName ) {
var pos = 0, i;
tagName = angular.lowercase(tagName);
if ( tagName )
// Find the closest opened tag of the same type
for ( pos = stack.length - 1; pos >= 0; pos-- )
if ( stack[ pos ] == tagName )
break;
if ( pos >= 0 ) {
// Close all the open elements, up the stack
for ( i = stack.length - 1; i >= pos; i-- )
if (handler.end) handler.end( stack[ i ] );
// Remove the open elements from the stack
stack.length = pos;
}
}
}
var hiddenPre=document.createElement("pre");
var spaceRe = /^(\s*)([\s\S]*?)(\s*)$/;
/**
* decodes all entities into regular string
* @param value
* @returns {string} A string with decoded entities.
*/
function decodeEntities(value) {
if (!value) { return ''; }
// Note: IE8 does not preserve spaces at the start/end of innerHTML
// so we must capture them and reattach them afterward
var parts = spaceRe.exec(value);
var spaceBefore = parts[1];
var spaceAfter = parts[3];
var content = parts[2];
if (content) {
hiddenPre.innerHTML=content.replace(//g, '>');
}
/**
* create an HTML/XML writer which writes to buffer
* @param {Array} buf use buf.jain('') to get out sanitized html string
* @returns {object} in the form of {
* start: function(tag, attrs, unary) {},
* end: function(tag) {},
* chars: function(text) {},
* comment: function(text) {}
* }
*/
function htmlSanitizeWriter(buf, uriValidator){
var ignore = false;
var out = angular.bind(buf, buf.push);
return {
start: function(tag, attrs, unary){
tag = angular.lowercase(tag);
if (!ignore && specialElements[tag]) {
ignore = tag;
}
if (!ignore && validElements[tag] === true) {
out('<');
out(tag);
angular.forEach(attrs, function(value, key){
var lkey=angular.lowercase(key);
var isImage = (tag === 'img' && lkey === 'src') || (lkey === 'background');
if (validAttrs[lkey] === true &&
(uriAttrs[lkey] !== true || uriValidator(value, isImage))) {
out(' ');
out(key);
out('="');
out(encodeEntities(value));
out('"');
}
});
out(unary ? '/>' : '>');
}
},
end: function(tag){
tag = angular.lowercase(tag);
if (!ignore && validElements[tag] === true) {
out('');
out(tag);
out('>');
}
if (tag == ignore) {
ignore = false;
}
},
chars: function(chars){
if (!ignore) {
out(encodeEntities(chars));
}
}
};
}
// define ngSanitize module and register $sanitize service
angular.module('ngSanitize', []).provider('$sanitize', $SanitizeProvider);
/* global sanitizeText: false */
/**
* @ngdoc filter
* @name linky
* @kind function
*
* @description
* Finds links in text input and turns them into html links. Supports http/https/ftp/mailto and
* plain email address links.
*
* Requires the {@link ngSanitize `ngSanitize`} module to be installed.
*
* @param {string} text Input text.
* @param {string} target Window (_blank|_self|_parent|_top) or named frame to open links in.
* @returns {string} Html-linkified text.
*
* @usage
*
* @example
"
}
return result;
}
function getAPage() {
var data = [];
var startIndex = $scope.currentRowIndex;
var endIndex = startIndex + infiniteScrollLoadsize;
for (var i = startIndex; i < endIndex; i++) {
if ($scope.currentRowIndex < $scope.total) {
data.push(vm.data[i]);
$scope.currentRowIndex += 1;
} else {
break;
}
}
return data;
}
function openDocument(documentId) {
$scope.onOpenDocument({ id: documentId });
};
function openFolder(folderId) {
$state.go(handbookActions.FolderAction, { folderId: folderId });
}
function calculateColumnsWidth(numColumns, extraWidth) {
var __numCoumns = numColumns == null ? 0 : numColumns;
var __extraWidth = extraWidth == null ? 0 : extraWidth;
var additionWidth = 0;
if (__numCoumns > 0) {
additionWidth = (__extraWidth / __numCoumns);
}
var columns = 0; // title column always visible.
var temp = commonGridSetting;
var ratio = 100;
temp.title.width = ratio + '%';
if ($scope.columnsDefinition.documentType) {
ratio -= (additionWidth + 12);
temp.documentType.width = (additionWidth + 12) + '%';
columns += 1;
}
if ($scope.columnsDefinition.chapter) {
ratio -= (additionWidth + 13);
temp.chapter.width = (additionWidth + 13) + '%';
columns += 1;
}
if ($scope.columnsDefinition.location) {
ratio -= (additionWidth + 17);
temp.location.width = (additionWidth + 17) + '%';
columns += 1;
}
if ($scope.columnsDefinition.approver) {
ratio -= (additionWidth + 8);
temp.approver.width = (additionWidth + 8) + '%';
columns += 1;
}
if ($scope.columnsDefinition.responsible) {
ratio -= (additionWidth + 9);
temp.responsible.width = (additionWidth + 9) + '%';
columns += 1;
}
if ($scope.columnsDefinition.hasAttachment) {
ratio -= (additionWidth + 4);
temp.hasAttachment.width = (additionWidth + 4) + '%';
columns += 1;
}
if ($scope.columnsDefinition.documentId) {
ratio -= (additionWidth + 5);
temp.documentId.width = (additionWidth + 5) + '%';
columns += 1;
}
if ($scope.columnsDefinition.version) {
ratio -= (additionWidth + 7);
temp.version.width = (additionWidth + 7) + '%';
columns += 1;
}
if ($scope.columnsDefinition.readCount) {
ratio -= (additionWidth + 5);
temp.readCount.width = (additionWidth + 5) + '%';
columns += 1;
}
if ($scope.columnsDefinition.approvedDate) {
ratio -= (additionWidth + 9);
temp.approvedDate.width = (additionWidth + 9) + '%';
columns += 1;
}
temp.title.width = ratio + '%';
if (ratio > 51 && ratio != 100) {
temp = calculateColumnsWidth(columns, (ratio - 50));
}
return temp;
};
function arrayCopy(data) {
if (data && data.length > 0) {
return data.slice();
}
};
//$('.popover-visible-trigger')
// .popover('show')
// .off('click');
}
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npGridExporter', [function () {
return {
restrict: 'E',
controller: ['ngDialog', '$scope', controller],
scope: {
excelExporterUrl: '@',
wordExporterUrl: '@',
exportParams: '=',
loadExportColumns: '&', // Some views get column settings from local storage, we also need to support this case
fileName: '@'
},
templateUrl: paths.GridExporterControlView,
replace: true
}
}]);
function controller(ngDialog, $scope) {
$scope.translation = globalResources;
$scope.showExporterDialog = showExporterDialog;
function showExporterDialog() {
if ($scope.loadExportColumns) {
$scope.loadExportColumns();
}
ngDialog.open({
template: paths.GridDialogExporterView,
controller: 'dialogExporter',
data: {
excelExporterUrl: $scope.excelExporterUrl,
wordExporterUrl: $scope.wordExporterUrl,
exportParams: $scope.exportParams,
fileName: $scope.fileName
},
className: 'ngdialog-theme-default'
});
}
}
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npImage', function () {
return {
restrict: 'E',
scope: {
model: '=npImageModel'
},
templateUrl: paths.ImageView,
replace: true,
link: link
};
});
function link(scope, element, attrs) {
var model = scope.model,
image = angular.element('')
.attr('src', handbookRequests.GetImageRequest + model.imageId)
.attr('align', 'left')
.attr('alt', model.caption)
.css('width', '100%')
.addClass('np-image__image');
if (model.url) {
image = angular.element('')
.attr({
href: model.url,
target: model.openInNewWindow ? '_blank' : '_self',
title: model.caption
})
.append(image);
}
element
.css('width', getWidth(model))
.addClass(getImageClass(model))
.prepend(image);
}
function getImageClass(image) {
var horizontalAlign = "";
switch (parseInt(image.horizontalAlign)) {
case parseInt(E.HorizontalAlign.Right):
horizontalAlign = "ImageRight";
break;
case parseInt(E.HorizontalAlign.Left):
horizontalAlign = "ImageLeft";
break;
case parseInt(E.HorizontalAlign.Center):
horizontalAlign = "ImageMid";
break;
}
return horizontalAlign;
}
function getWidth(image) {
var width;
if (image.scaleDir != 0)
if (image.scaleDir == 1) {
width = image.size;
}
else {
width = image.size / image.height * image.width;
}
else {
width = image.width;
}
return width;
}
})();;
(function () {
angular
.module('customeDirectivesModule')
.directive('imageSizeLimitation', function () {
return {
restrict: 'A',
scope: {
maximumWidth: '=',
maximumHeight: '='
},
link: link
};
});
function link(scope, element, attrs) {
element.bind('load', function () {
if (!scope.maximumWidth || !scope.maximumHeight) {
return;
}
if (this.width > this.height) {
$(this).css({ 'max-width': scope.maximumWidth + 'px' });
$(this).css({ 'display': 'block' });
} else {
$(this).css({ 'max-height': scope.maximumHeight + 'px' });
$(this).css({ 'display': 'block' });
}
});
}
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npFeedbackButton', function () {
return {
restrict: 'E',
replace: true,
controller: ['$scope', '$http', '$modal', controller],
templateUrl: paths.FeedbackButtonView,
scope: {
entityId: '='
},
};
});
function controller($scope, $http, $modal) {
$scope.globalResources = globalResources;
if ($scope.globalResources.Feedbacktooltip.indexOf('\n(CTRL + ALT + T)') <= 0) {
$scope.globalResources.Feedbacktooltip = $scope.globalResources.Feedbacktooltip + '\n(CTRL + ALT + T)';
}
$scope.popupModal = function () {
var modalInstance = $modal.open({
templateUrl: paths.FeedbackModalView,
controller: controllers.feedbackController,
size: 'lg',
backdrop: 'static',
resolve: {
model: function () {
return {
entityId: $scope.entityId,
positive: null
};
}
}
});
};
$scope.$on(broadcastType.toggleDocumentFeedbackTarget, function (e, target) {
$scope.popupModal();
});
}
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npReadingReceiptButton', ['$document', function ($document) {
return {
restrict: 'E',
controller: ['$scope', 'readingConfirmationService', '$http', controller],
scope: {
entityId: '=',
folderId: '=',
entityDisabled: '='
},
templateUrl: paths.ReadingReceiptButtonView,
replace: true,
link: function (scope, element, attr) {
$document.bind('click', function (event) {
var isClickedElementChildOfPopup = element
.find(event.target)
.length > 0;
if (isClickedElementChildOfPopup)
return;
scope.readingReciept.showReadingRecieptContextMenu = false;
scope.$apply();
});
}
};
}]);
function controller($scope, readingConfirmationService, $http) {
$scope.translation = globalResources;
if ($scope.translation.ReadingReciept.indexOf('\n(CTRL + ALT + L)') <= 0) {
$scope.translation.ReadingReciept = $scope.translation.ReadingReciept + '\n(CTRL + ALT + L)';
}
$scope.isShowReConfirm = false;
$scope.readingReciept = { showReadingRecieptContextMenu : false };
$scope.currentData = {
readConfirmationDate: '',
confirmedReadLast: '',
fullName: ''
};
$scope.getConfirmInformation = function () {
if (!$scope.currentData.readConfirmationDate && !$scope.currentData.fullName) {
readingConfirmationService.GetConfirmInformation($scope.entityId)
.then(function (response) {
$scope.currentData = response.data;
if (response.data.readConfirmationDate) {
$scope.currentData.confirmedReadLast = String.format($scope.translation.ConfirmedReadLast, response.data.readConfirmationDate);
var readConfirmationDate = new Date(response.data.readConfirmationDateTime);
$scope.isShowReConfirm = (compareDate(readConfirmationDate, new Date()) == false);
}
});
}
};
function compareDate(date1, date2) {
if (date1.getFullYear() != date2.getFullYear()) {
return false;
}
if (date1.getMonth() != date2.getMonth()) {
return false;
}
if (date1.getDate() != date2.getDate()) {
return false;
}
return true;
}
$scope.sendReadingConfirmation = function () {
readingConfirmationService.sendReadingConfirmation($scope.entityId, $scope.folderId)
.then(function (data) {
if (data) {
$scope.currentData.readConfirmationDate = data.replace('"', '').replace('"', '');
$scope.currentData.confirmedReadLast = String.format($scope.translation.ConfirmedReadLast, $scope.currentData.readConfirmationDate);
$scope.isShowReConfirm = false;
}
});
};
$scope.$on(broadcastType.toggleReadingReceiptTarget, function (e, target) {
$scope.getConfirmInformation();
$scope.readingReciept.showReadingRecieptContextMenu = true;
});
}
})();;
(function () {
'use strict';
angular.module('customeDirectivesModule')
.directive('npPin', npPinDirective);
function npPinDirective() {
var directive = {
restrict: 'EA',
templateUrl: paths.PinView,
scope: {
},
link: linkFunction,
controller: controller,
controllerAs: 'vm'
};
return directive;
function linkFunction(scope, el, attr, ctrl) {
};
controller.$inject = ['$scope', '$window'];
function controller($scope, $window) {
var vm = this;
vm.hideSidebarButton = hideSidebarButton;
function hideSidebarButton() {
angular.element('.sidebar-toggle').toggleClass('display--non');
};
};
};
})();;
(function () {
'use strict';
angular.module('customeDirectivesModule')
.directive('npCollapse', npCollapse)
.directive('npCollapse3', npCollapse3);
function npCollapse() {
var directive = {
restrict: 'EA',
replace: true,
template: 'kollapse',
scope: {
collapseTarget: '@'
},
link: linkFunction,
controller: ['$scope', controller],
controllerAs: 'vm'
};
return directive;
function linkFunction(scope, el, attr, ctrl) {
};
function controller($scope) {
var vm = this;
vm.collapsed = collapsed;
function collapsed() {
angular.element('#' + $scope.collapseTarget).toggleClass('collapsed');
angular.element('#' + $scope.collapseTarget + '_icon').toggleClass('collapsed-arrow').toggleClass('collapse-arrow');
};
};
};
function npCollapse3() {
var directive = {
restrict: 'E',
replace: true,
template: '',
scope: {
collapseTarget: '@',
onCollapsed: '&',
collapsedFlag: '='
},
link: linkFunction,
controller: ['$scope', controller],
controllerAs: 'vm'
};
return directive;
function linkFunction(scope, el, attr, ctrl) {
};
function controller($scope) {
var vm = this;
vm.collapsedFlag = angular.copy($scope.collapsedFlag);
vm.collapsed = collapsed;
function collapsed() {
vm.collapsedFlag = !vm.collapsedFlag;
angular.element('#' + $scope.collapseTarget).toggleClass('collapsed');
angular.element('#' + $scope.collapseTarget + '_icon').toggleClass('collapsed-arrow').toggleClass('collapse-arrow');
$scope.onCollapsed({ collapsedFlag: vm.collapsedFlag });
};
};
};
})();;
(function () {
'use strict';
angular.module('customeDirectivesModule')
.directive('npCollapseLeft', npCollapse);
function npCollapse() {
var directive = {
restrict: 'EA',
replace: true,
template: '',
scope: {
collapseTarget: '@',
onCollapsed: '&'
},
link: linkFunction,
controller: ['$scope', controller],
controllerAs: 'vm'
};
return directive;
function linkFunction(scope, el, attr, ctrl) {
};
function controller($scope) {
var vm = this;
vm.collapsedFlag = false;
vm.collapsed = collapsed;
function collapsed() {
vm.collapsedFlag = !vm.collapsedFlag;
angular.element('#' + $scope.collapseTarget).toggleClass('collapsed');
angular.element('#' + $scope.collapseTarget + '_icon').toggleClass('group-collapsed-arrow').toggleClass('group-collapse-arrow');
$scope.onCollapsed({ collapsedFlag: vm.collapsedFlag });
};
};
};
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npNavigateToggle', function () {
return {
restrict: 'E',
controller: ['$scope', '$http', 'treeNavigationService', 'localStorageService', controller],
controllerAs: 'vm',
templateUrl: '/app/shared/navigation/navigateToggle.html',
scope: {
},
link: function (scope, element, attr) {
}
};
});
function controller($scope, $http, treeNavigationService, localStorageService) {
var vm = this;
vm.showToggleButton = HandbookConfiguration.AutoHighlightInTree.toUpperCase() == "FALSE";
vm.toggleNavigate = toggleNavigate;
vm.showInTreeviewInLeftMenu = globalResources.ShowInTreeviewInLeftMenu;
vm.initialize = function () {
vm.navigateSideBar = false;
buildTooltip();
};
function toggleNavigate() {
vm.navigateSideBar = !vm.navigateSideBar;
treeNavigationService.navigateToItemLocation(vm.navigateSideBar, true);
};
function buildTooltip() {
var availWidth = screen.availWidth;
var availHeight = screen.availHeight;
if (!((availWidth <= 768 && availHeight <= 1024) || (availHeight <= 768 && availWidth <= 1024))) {
vm.showInTreeviewInLeftMenu = globalResources.ShowInTreeviewInLeftMenu + ' \r(CTRL + ALT + N)';
}
}
$(window).on('resize', function () {
buildTooltip();
});
};
})();;
(function () {
var model = angular.module('advanceSearchModule', []);
model.controller(controllers.advanceSearchController, ['$scope', '$state', '$http', 'folderService', '$modalInstance', 'quickSearchKeyword', 'broadcastService',
function ($scope, $state, $http, folderService, $modalInstance, quickSearchKeyword, broadcastService) {
$scope.translation = globalResources;
$scope.currentData = {
advanceSearchKeyword: quickSearchKeyword,
folderName: '',
selectedDocType: 0,
selectedFolderId: 0,
datetime: {
fromDate: null,
toDate: null,
isView: false
},
searchInContent: false,
hasExpired: false
};
$scope.documentTypes = [];
$scope.folderTree = [];
$scope.filterOptionNeededMessage = globalResources.FilterOptionNeededMessage;
$scope.showTreeDocument = false;
$scope.key_showRemoveIcon = false;
$scope.folder_showRemoveIcon = false;
$scope.dateFrom_showRemoveIcon = false;
$scope.dateTo_showRemoveIcon = false;
$scope.initAdvanceSearchData = initAdvanceSearchData;
$scope.onAdvanceSearch = onAdvanceSearch;
$scope.close = close;
$scope.loadFolderTree = loadFolderTree;
$scope.hidePopupOnLostFocus = hidePopupOnLostFocus;
$scope.selectNodeHead = selectNodeHead;
$scope.selectNodeLabel = selectNodeLabel;
$scope.hideTooltip = hideTooltip;
$scope.clear_advKeyword = clear_advKeyword;
$scope.clear_advFolder = clear_advFolder;
$scope.clear_advDateFrom = clear_advDateFrom;
$scope.clear_advDateTo = clear_advDateTo;
function initAdvanceSearchData() {
setTimeout(function () {
$('#adv_keyword').focus();
},1000);
//Init chapter base on url
var id = $state.params.folderId;
if (id != undefined && id > 0 && $state.current.name == 'folder') {
folderService.getFolderById(id).then(function (response) {
$scope.currentData.folderName = response.data.name;
$scope.currentData.selectedFolderId = response.data.id;
});;
}
$scope.key_showRemoveIcon = ($scope.currentData.advanceSearchKeyword != undefined && $scope.currentData.advanceSearchKeyword.length > 0);
};
function onAdvanceSearch() {
if ($scope.currentData.selectedFolderId != 0 || $scope.currentData.datetime.toDate != null || $scope.currentData.datetime.fromDate != null || $scope.currentData.advanceSearchKeyword != '') {
$scope.filterOptionNeededMessage = '';
$state.go(handbookActions.SearchResultAction, {
keyword: $scope.currentData.advanceSearchKeyword,
searchInContents: 1,
folderId: $scope.currentData.selectedFolderId,
fromDate: $scope.currentData.datetime.fromDate != null ? $scope.currentData.datetime.fromDate.getTime() : null,
toDate: $scope.currentData.datetime.toDate != null ? $scope.currentData.datetime.toDate.getTime() : null,
hasExpired: $scope.currentData.hasExpired ? 1: 0,
type: 3
});
$modalInstance.close(true);
broadcastService(broadcastType.resetQuickSearchKeyword, null);
}
else {
$scope.filterOptionNeededMessage = globalResources.FilterOptionNeededMessage;
}
};
function close() {
$modalInstance.close(true);
}
function loadFolderTree() {
$scope.showTreeDocument = !$scope.showTreeDocument;
if ($scope.showTreeDocument) {
if ($scope.folderTree.length == undefined || $scope.folderTree.length == 0) {
$http.get(handbookRequests.GetFoldersRequest)
.success(function (data, status, headers, config) {
$scope.folderTree = data;
});
}
}
};
function hidePopupOnLostFocus() {
$scope.showTreeDocument = false;
};
function selectNodeHead(node) {
if (!node.isLoaded) {
$http.get(handbookRequests.GetSubfoldersRequest, { params: { 'folderId': node.id } })
.success(function (data, status, headers, config) {
node.children = data;
node.isLoaded = true;
})
.error(function (data, status, headers, config) {
node.isLoaded = true;
});
}
};
function selectNodeLabel(node) {
$scope.currentData.folderName = node.name;
$scope.currentData.selectedFolderId = node.id;
$scope.folder_showRemoveIcon = ($scope.currentData.selectedFolderId != undefined && $scope.currentData.selectedFolderId > 0);
folderService.setFolder(node);
hidePopupOnLostFocus();
hideTooltip();
};
$scope.$watch('currentData.datetime.fromDate', function () {
if ($scope.currentData.datetime.fromDate != null) {
hideTooltip();
$scope.dateFrom_showRemoveIcon = ($scope.currentData.datetime.fromDate != undefined && $scope.currentData.datetime.fromDate != null);
}
});
$scope.$watch('currentData.datetime.toDate', function () {
if ($scope.currentData.datetime.toDate != null) {
hideTooltip();
$scope.dateTo_showRemoveIcon = ($scope.currentData.datetime.toDate != undefined && $scope.currentData.datetime.toDate != null);
}
});
function hideTooltip() {
if (angular.element('#btnAdvanceSearch').scope().tt_isOpen) {
angular.element('#btnAdvanceSearch').scope().tt_isOpen = false;
}
$scope.key_showRemoveIcon = ($scope.currentData.advanceSearchKeyword != undefined && $scope.currentData.advanceSearchKeyword.length > 0);
};
function clear_advKeyword() {
$scope.currentData.advanceSearchKeyword = '';
$scope.key_showRemoveIcon = false;
};
function clear_advFolder() {
$scope.currentData.folderName = '';
$scope.currentData.selectedFolderId = 0;
$scope.folder_showRemoveIcon = false;
};
function clear_advDateFrom() {
$scope.currentData.datetime.fromDate = null;
$scope.dateFrom_showRemoveIcon = false;
};
function clear_advDateTo() {
$scope.currentData.datetime.toDate = null;
$scope.dateTo_showRemoveIcon = false;
};
}]);
})();;
(function () {
angular.module('customeDirectivesModule')
.directive('npBreadcrumbs', npBreadcrumbs);
function npBreadcrumbs() {
var directive = {
restrict: 'EA',
replace: true,
templateUrl: '/app/shared/breadcrumbs/breadcrumbsTemplate.html',
scope: {
},
link: linkFunction,
controller: ['$rootScope', '$scope', '$location', '$state', '$timeout', '$http', 'broadcastService', 'localStorageService', 'tabStateService', controller],
controllerAs: 'vm'
};
return directive;
function linkFunction(scope, el, attr, ctrl) {
};
function controller($rootScope, $scope, $location, $state, $timeout, $http, broadcastService, localStorageService, tabStateService) {
var vm = this;
vm.translation = {
home: globalResources.Home,
searchResult: globalResources.SearchResult,
viewNews: globalResources.News
};
vm.url = $location.path();
vm.breadcrumbs = [];
vm.otherBreadcrumbs = [];
vm.navigateToFolder = navigateToFolder;
vm.isSearchResultView = false;
vm.isNewsView = false;
vm.setMasterTab = setMasterTab;
vm.goToNewsList = goToNewsList;
vm.showAllBreadcrumbs = showAllBreadcrumbs;
initialize();
function initialize() {
vm.isDocumentAction = false;
vm.isFolderAction = false;
vm.hasSubFolders = false;
getBreadcrumbs();
};
function setMasterTab() {
tabStateService.setState(tabStateType.homeTabState, homeTabs.startPage);
}
function getBreadcrumbs() {
var element = vm.url.split('/');
if (element != undefined && element.length > 0) {
var requestParams = {
itemId: element[2],
itemType: element[1]
};
var validCondition = (requestParams.itemType == handbookActions.DocumentAction
|| requestParams.itemType == handbookActions.FolderAction)
&& !isNaN(requestParams.itemId);
vm.isDocumentAction = requestParams.itemType == handbookActions.DocumentAction;
vm.isFolderAction = requestParams.itemType == handbookActions.FolderAction;
if (validCondition) {
$http.get(handbookRequests.GetParentFoldersRequest, { params: requestParams })
.then(function (response, status, headers, config) {
if (vm.isFolderAction) {
$http.get(handbookRequests.GetSubfoldersRequest, { params: { 'folderId': element[2] } })
.success(function (data, status, headers, config) {
vm.hasSubFolders = (data != null && data.length > 0);
if (vm.hasSubFolders) {
buildSubFoldersBreadcrumbs(data);
}
buildBreadcrumbs(response.data);
});
} else {
buildBreadcrumbs(response.data);
}
});
} else {
buildOthersBreadcrumbs(requestParams);
}
vm.isSearchResultView = requestParams.itemType.contains(handbookActions.SearchResultAction);
vm.isNewsView = (requestParams.itemType === handbookActions.NewsListAction)
|| (requestParams.itemType === handbookActions.StartpageNews)
|| (requestParams.itemType === handbookActions.NewsCategoryAction);
}
};
function buildSubFoldersBreadcrumbs(data) {
for (var i = 0; i < data.length; i++) {
data[i].icon = getFolderIcon(data[i].type);
}
if (!(typeof data === 'string')) {
vm.subFolders = data;
}
};
function navigateToFolder(sub) {
$state.go(handbookActions.FolderAction, { folderId: sub.id });
};
function goToNewsList() {
if ($state.$current.name == handbookActions.StartpageNews) {
$state.go(handbookActions.NewsListAction, { pageIndex: user.currentNewsPage });
} else {
$state.go(handbookActions.NewsListAction);
}
}
function buildOthersBreadcrumbs(requestParams) {
switch (requestParams.itemType) {
case handbookActions.HandbookAdminAction:
addAdminBreadcrums();
break;
case handbookActions.HandbookManagementAction:
addAdminBreadcrums();
addHandbookBreadcrums();
break;
case handbookActions.DocumentTemplateAction:
addAdminBreadcrums();
addHandbookBreadcrums();
vm.otherBreadcrumbs.push({
id: handbookActions.DocumentTemplateAction,
name: resources.L.Action.documentTypes,
icon: 'fa fa-file-image-o'
});
break;
case handbookActions.DocumentFieldsAction:
addAdminBreadcrums();
addHandbookBreadcrums();
vm.otherBreadcrumbs.push({
id: handbookActions.DocumentFieldsAction,
name: resources.L.Action.fieldList,
icon: 'fa fa-list-ul'
});
break;
case handbookActions.RolesAction:
addAdminBreadcrums();
vm.otherBreadcrumbs.push({
id: handbookActions.RolesAction,
name: resources.L.Action.roles,
icon: 'fs22 icon-ehand_tilgang2 vtca-tb'
});
break;
case handbookActions.StaffManagementAction:
addAdminBreadcrums();
vm.otherBreadcrumbs.push({
id: handbookActions.StaffManagementAction,
name: resources.L.Action.staff,
icon: 'fs20 typcn typcn-user-outline'
});
break;
case handbookActions.DepartmentsManagementAction:
addAdminBreadcrums();
vm.otherBreadcrumbs.push({
id: handbookActions.DepartmentsManagementAction,
name: resources.L.Action.departments,
icon: 'fs20 typcn typcn-group-outline'
});
broadcastService(broadcastType.sidebarNav, { id: sidebarTypes.DEPARTMENT });
showSidebar();
break;
default:
break;
}
if (vm.otherBreadcrumbs != null && vm.otherBreadcrumbs.length > 0 && (requestParams.itemType != handbookActions.DepartmentsManagementAction)) {
hideSidebar();
} else {
showSidebar();
}
}
function showSidebar() {
if (angular.element('body.sidebar-hidden').length || angular.element('body.sidebar-rtl').length) {
angular.element('body').addClass('sidebar-ltr').removeClass('sidebar-hidden sidebar-rtl');
angular.element('#toggle_sidemenu_l').show();
}
};
function hideSidebar() {
angular.element('body').addClass('sidebar-hidden').removeClass('sidebar-ltr sidebar-rtl');
angular.element('#toggle_sidemenu_l').hide();
angular.element('.navbar-brand').attr('style', 'margin-left: 40px;');
}
function addAdminBreadcrums() {
vm.otherBreadcrumbs.push({
id: handbookActions.HandbookAdminAction,
name: resources.L.Action.admin,
icon: 'fs20 typcn typcn-microphone-outline'
});
}
function addHandbookBreadcrums() {
vm.otherBreadcrumbs.push({
id: handbookActions.HandbookManagementAction,
name: resources.L.Action.handbook,
icon: 'fa fa-folder-o'
});
}
function buildBreadcrumbs(data) {
var totalItem = data.length;
//move root to result array
for (var i = 0; i < data.length; i++) {
if (data[i].parentFolderId == null) {
data[i].icon = getFolderIcon(data[i].type);
vm.breadcrumbs.push(data[i]);
data.splice(i, 1);
break;
}
}
//fill in the rest
var currentItem = 0;
while (vm.breadcrumbs.length != totalItem && currentItem <= vm.breadcrumbs.length) {
for (var i = 0; i < data.length; i++) {
if (vm.breadcrumbs[currentItem].id == data[i].parentFolderId) {
data[i].icon = getFolderIcon(data[i].type);
vm.breadcrumbs.push(data[i]);
data.splice(i, 1);
break;
}
}
currentItem++;
}
vm.fullBreadcrumbs = angular.copy(vm.breadcrumbs);
breadcrumbsCompact();
};
function breadcrumbsCompact() {
vm.isBreadcrumbsCompact = false;
vm.mobileView = false;
$timeout(function () {
var divBreadcrumb = angular.element('.np-breadcrumbs');
var lineHeight = divBreadcrumb.height();
var documentWidth = $(document).width();
if (documentWidth > 667) {
if (lineHeight > 28) {
var arrTemp = [];
if (vm.breadcrumbs.length > 2) {
vm.isBreadcrumbsCompact = true;
arrTemp.push(vm.breadcrumbs[vm.breadcrumbs.length - 2]);
arrTemp.push(vm.breadcrumbs[vm.breadcrumbs.length - 1]);
vm.breadcrumbs = arrTemp;
refreshScrollContentView();
}
}
} else {
if (lineHeight > 28) {
var arrTemp = [];
if (vm.breadcrumbs.length > 1) {
vm.mobileView = true;
vm.isBreadcrumbsCompact = true;
arrTemp.push(vm.breadcrumbs[vm.breadcrumbs.length - 1]);
vm.breadcrumbs = arrTemp;
refreshScrollContentView();
}
}
}
}, 100);
};
function showAllBreadcrumbs() {
vm.isBreadcrumbsCompact = false;
vm.mobileView = false;
vm.breadcrumbs = angular.copy(vm.fullBreadcrumbs);
refreshScrollContentView();
};
function updateBreadcrumbs() {
vm.breadcrumbs = [];
vm.otherBreadcrumbs = [];
vm.url = $location.path();
getBreadcrumbs();
};
$(window).on('resize', function () {
vm.breadcrumbs = angular.copy(vm.fullBreadcrumbs);
$timeout(function () {
breadcrumbsCompact();
}, 0, false);
});
function refreshScrollContentView() {
if (vm.url.contains('document')) {
adjustDocumentContentPosition();
} else if (vm.url.contains('folder')) {
adjustChapterContentPosition();
}
};
function adjustChapterContentPosition() {
var tabState = tabStateService.getState(tabStateType.chapterTabState);
$timeout(function () {
tabStateService.adjustContentPosition(tabState, tabStateType.chapterTabState);
}, 0, false);
};
function adjustDocumentContentPosition() {
var tabState = tabStateService.getState(tabStateType.documentTabState);
$timeout(function () {
tabStateService.adjustContentPosition(tabState, tabStateType.documentTabState);
}, 0, false);
}
function getFolderIcon(folderType) {
if (folderType != null) {
switch (folderType.toString()) {
case E.nodeTypes.Folder:
return paths.FolderIcon;
case E.nodeTypes.TopFolder:
return paths.TopFolderIcon;
case E.nodeTypes.DepartmentFolder:
return paths.DepartmentFolderIcon;
case E.nodeTypes.RegionalFolder:
return paths.RegionalFolderIcon;
default:
return paths.FolderIcon;
}
} else {
return paths.FolderIcon;
}
};
}
};
})();;
(function($) {
// @todo Document this.
$.extend($,{ placeholder: {
browser_supported: function() {
return this._supported !== undefined ?
this._supported :
( this._supported = !!('placeholder' in $('')[0]) );
},
shim: function(opts) {
var config = {
color: '#888',
cls: 'placeholder',
selector: 'input[placeholder], textarea[placeholder]'
};
$.extend(config,opts);
return !this.browser_supported() && $(config.selector)._placeholder_shim(config);
}
}});
$.extend($.fn,{
_placeholder_shim: function(config) {
function calcPositionCss(target)
{
var op = $(target).offsetParent().offset();
var ot = $(target).offset();
return {
top: ot.top - op.top,
left: ot.left - op.left,
width: $(target).width()
};
}
function adjustToResizing(label) {
var $target = label.data('target');
if(typeof $target !== "undefined") {
label.css(calcPositionCss($target));
$(window).one("resize", function () { adjustToResizing(label); });
}
}
return this.each(function() {
var $this = $(this);
if( $this.is(':visible') ) {
if( $this.data('placeholder') ) {
var $ol = $this.data('placeholder');
$ol.css(calcPositionCss($this));
return true;
}
var possible_line_height = {};
if( !$this.is('textarea') && $this.css('height') != 'auto') {
possible_line_height = { lineHeight: $this.css('height'), whiteSpace: 'nowrap' };
}
var isBorderBox = ($this.css('box-sizing') === 'border-box');
var isTextarea = $this.is('textarea');
var ol = $('')
.text($this.attr('placeholder'))
.addClass(config.cls)
.css($.extend({
position:'absolute',
display: 'inline',
'float':'none',
overflow:'hidden',
textAlign: 'left',
color: config.color,
cursor: 'text',
paddingTop: !isTextarea && isBorderBox ? '0' : $this.css('padding-top'),
paddingRight: $this.css('padding-right'),
paddingBottom: !isTextarea && isBorderBox ? '0' : $this.css('padding-bottom'),
paddingLeft: $this.css('padding-left'),
fontSize: $this.css('font-size'),
fontFamily: $this.css('font-family'),
fontStyle: $this.css('font-style'),
fontWeight: $this.css('font-weight'),
textTransform: $this.css('text-transform'),
backgroundColor: 'transparent',
zIndex: 99
}, possible_line_height))
.css(calcPositionCss(this))
.attr('for', this.id)
.data('target',$this)
.click(function(){
if (!$(this).data('target').is(':disabled')) {
$(this).data('target').focus();
}
})
.insertBefore(this);
$this
.data('placeholder', ol)
.on('keydown', function () {
ol.hide();
})
.on('blur change', function () {
ol[$this.val().length ? 'hide' : 'show']();
})
.triggerHandler('blur');
$(window).one("resize", function () { adjustToResizing(ol); });
}
});
}
});
})(jQuery);
jQuery(document).add(window).bind('ready load', function() {
if (jQuery.placeholder) {
jQuery.placeholder.shim();
}
});
;
/*!
* angular-hotkeys v1.7.0
* https://chieffancypants.github.io/angular-hotkeys
* Copyright (c) 2016 Wes Cruver
* License: MIT
*/
!function(){"use strict";angular.module("cfp.hotkeys",[]).provider("hotkeys",["$injector",function(a){this.includeCheatSheet=!0,this.useNgRoute=a.has("ngViewDirective"),this.templateTitle="Keyboard Shortcuts:",this.templateHeader=null,this.templateFooter=null,this.template='
{{ title }}
{{ key }}
{{ hotkey.description }}
×
',this.cheatSheetHotkey="?",this.cheatSheetDescription="Show / hide this help menu",this.$get=["$rootElement","$rootScope","$compile","$window","$document",function(a,b,c,d,e){function f(){q=!1}function g(){q=!0}function h(a){var b={command:"⌘",shift:"⇧",left:"←",right:"→",up:"↑",down:"↓","return":"⏎",backspace:"⌫"};a=a.split("+");for(var c=0;c=0?a[c]="command":a[c]="ctrl"),a[c]=b[a[c]]||a[c];return a.join(" + ")}function i(a,b,c,d,e,f){this.combo=a instanceof Array?a:[a],this.description=b,this.callback=c,this.action=d,this.allowIn=e,this.persistent=f,this._formated=null}function j(){for(var a=r.hotkeys.length;a--;){var b=r.hotkeys[a];b&&!b.persistent&&m(b)}}function k(){r.helpVisible=!r.helpVisible,r.helpVisible?(w=n("esc"),m("esc"),l("esc",w.description,k,null,["INPUT","SELECT","TEXTAREA"])):(m("esc"),w!==!1&&l(w))}function l(a,b,c,d,e,f){var g,h=["INPUT","SELECT","TEXTAREA"],j=Object.prototype.toString.call(a);if("[object Object]"===j&&(b=a.description,c=a.callback,d=a.action,f=a.persistent,e=a.allowIn,a=a.combo),m(a),b instanceof Function?(d=c,c=b,b="$$undefined$$"):angular.isUndefined(b)&&(b="$$undefined$$"),void 0===f&&(f=!0),"function"==typeof c){g=c,e instanceof Array||(e=[]);for(var k,l=0;l-1)b=!0;else for(var e=0;e-1?(r.hotkeys[e].combo.length>1?r.hotkeys[e].combo.splice(r.hotkeys[e].combo.indexOf(b),1):(angular.forEach(s,function(a){var b=a.indexOf(r.hotkeys[e]);-1!==b&&a.splice(b,1)}),r.hotkeys.splice(e,1)),!0):!1}function n(a){if(!a)return r.hotkeys;for(var b,c=0;c-1)return b;return!1}function o(a){return a.$id in s||(s[a.$id]=[],a.$on("$destroy",function(){for(var b=s[a.$id].length;b--;)m(s[a.$id].pop())})),{add:function(b){var c;return c=arguments.length>1?l.apply(this,arguments):l(b),s[a.$id].push(c),this}}}function p(a){return function(c,d){if(a instanceof Array){var e=a[0],f=a[1];a=function(a){f.scope.$eval(e)}}b.$apply(function(){a(c,n(d))})}}var q=!0;Mousetrap.prototype.stopCallback=function(a,b){return q?(" "+b.className+" ").indexOf(" mousetrap ")>-1?!1:b.contentEditable&&"true"==b.contentEditable:!0},i.prototype.format=function(){if(null===this._formated){for(var a=this.combo[0],b=a.split(/[\s]/),c=0;c95&&112>a||r.hasOwnProperty(a)&&(q[r[a]]=a)}return q}function l(a,b,c){return c||(c=k()[a]?"keydown":"keypress"),"keypress"==c&&b.length&&(c="keydown"),c}function m(a){return"+"===a?["+"]:(a=a.replace(/\+{2}/g,"+plus"),a.split("+"))}function n(a,b){var c,d,e,f=[];for(c=m(a),e=0;e1?void q(a,g,b,c):(f=n(a,c),s._callbacks[f.key]=s._callbacks[f.key]||[],k(f.key,f.modifiers,{type:f.action},d,a,e),void s._callbacks[f.key][d?"unshift":"push"]({callback:b,modifiers:f.modifiers,action:f.action,seq:d,level:e,combo:a}))}var s=this;if(a=a||b,!(s instanceof p))return new p(a);s.target=a,s._callbacks={},s._directMap={};var t,u={},v=!1,w=!1,x=!1;s._handleKey=function(a,b,d){var e,f=k(a,b,d),g={},h=0,i=!1;for(e=0;e":".","?":"/","|":"\\"},u={option:"alt",command:"meta","return":"enter",escape:"esc",plus:"+",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"},v=1;20>v;++v)r[111+v]="f"+v;for(v=0;9>=v;++v)r[v+96]=v;p.prototype.bind=function(a,b,c){var d=this;return a=a instanceof Array?a:[a],d._bindMultiple.call(d,a,b,c),d},p.prototype.unbind=function(a,b){var c=this;return c.bind.call(c,a,function(){},b)},p.prototype.trigger=function(a,b){var c=this;return c._directMap[a+":"+b]&&c._directMap[a+":"+b]({},a),c},p.prototype.reset=function(){var a=this;return a._callbacks={},a._directMap={},a},p.prototype.stopCallback=function(a,b){var c=this;return(" "+b.className+" ").indexOf(" mousetrap ")>-1?!1:o(b,c.target)?!1:"INPUT"==b.tagName||"SELECT"==b.tagName||"TEXTAREA"==b.tagName||b.isContentEditable},p.prototype.handleKey=function(){var a=this;return a._handleKey.apply(a,arguments)},p.init=function(){var a=p(b);for(var c in a)"_"!==c.charAt(0)&&(p[c]=function(b){return function(){return a[b].apply(a,arguments)}}(c))},p.init(),a.Mousetrap=p,"undefined"!=typeof module&&module.exports&&(module.exports=p),"function"==typeof define&&define.amd&&define(function(){return p})}(window,document);;
"use strict";angular.module("placeholderShim",[]).directive("placeholder",["$interpolate","$timeout",function(a,b){return jQuery.placeholder.browser_supported()?{}:function(c,d){function e(){j=b(function(){d._placeholder_shim(f),i=d.data("placeholder"),j=null})}var f={color:"#888",cls:"placeholder"},g=a(d.attr("placeholder")),h=null,i=null,j=null;d.is(":visible")&&e(),c.$watch(function(){if(i||!d.is(":visible")||j||e(),i&&d.get(0)!==document.activeElement&&(d.val().length?i.hide():i.show()),i){var a=g(c);a!==h&&(h=a,i.text(h))}}),c.$on("$destroy",function(){j&&(b.cancel(j),j=null)})}}]);;
var internetPublishOption = (window.HandbookConfiguration && window.HandbookConfiguration.InternetPublishOption == 'True') ? true : false;
var publishedVersion = (window.HandbookConfiguration && window.HandbookConfiguration.PublishedVersion == 'True') ? true : false;
var gridSettingKeys = {
commonVisibilitySettings: 'ColumnVisiblitySettings',
readingListVisibilitySettings: 'ReadingListVisibilitySettings'
}
function ColumnItem() {
this.visible = false;
this.width = '';
this.minWidth = 0;
};
var commonGridSetting = {
title: new ColumnItem(),
documentType: new ColumnItem(),
chapter: new ColumnItem(),
documentId: new ColumnItem(),
readingList: new ColumnItem(),
isConfirmed: new ColumnItem(),
location: new ColumnItem(),
version: new ColumnItem(),
readCount: new ColumnItem(),
approvedDate: new ColumnItem(),
approver: new ColumnItem(),
responsible: new ColumnItem(),
hasAttachment: new ColumnItem(),
id: new ColumnItem(),
rowInfo: new ColumnItem(),
internet: new ColumnItem(),
readingReceipt: new ColumnItem(),
readingReceiptDtmConfirmed: new ColumnItem()
};
if (internetPublishOption && !publishedVersion) {
commonGridSetting.internet = new ColumnItem();
}
var commonColumnsDefinition = [];
var optionalColumnsDenifinition;
var layoutPlugin = new ngGridLayoutPlugin();
var charToPixelRatio = 9; //change this value if u change the font size
var autoColWidth = function (colDefs, rows) {
var totalChars = {};
var totalCharsLength = 0;
for (var i = 0, n = rows.length; i < n; i++) {
var tempTotalChars = {};
for (var colName in rows[i]) {
tempTotalChars[colName] = rows[i][colName].toString().length;
if (i == 0 || tempTotalChars[colName] > totalChars[colName]) {
totalChars[colName] = tempTotalChars[colName];
totalCharsLength += tempTotalChars[colName];
}
}
}
for (var i = 0, n = colDefs.length; i < n; i++) {
if (colDefs[i].field == commonGridColumns.attachment) {
colDefs[i].width = "4%";
} else {
colDefs[i].width = (totalChars[colDefs[i].field] / totalCharsLength * 100) + "%";//(totalChars[colDefs[i].field] * charToPixelRatio) + "px";
}
};
return colDefs;
}
var commonGridOptions = function (dataSource) {
return {
data: dataSource,
plugins: [layoutPlugin],
headerRowHeight: 40,
rowHeight: 40,
multiSelect: false,
enableColumnResize: true,
columnDefs: 'vm.commonGridColumnDefinition',
rowTemplate: paths.WhatNewRowTemplate
};
};
function getColumnsDefinition(gridSettingKey) {
commonColumnsDefinition = [
{
field: commonGridColumns.rowInfo, displayName: '',
minWidth: commonGridSetting.rowInfo.minWidth,
width: commonGridSetting.rowInfo.width,
cellTemplate: paths.DocumentInfoCellTemplate,
visible: commonGridSetting.rowInfo.visible
},
{
field: commonGridColumns.name, displayName: globalResources.CommonGridColumns.Title,
width: commonGridSetting.title.width
},
{
field: commonGridColumns.template, displayName: globalResources.CommonGridColumns.Type,
width: commonGridSetting.documentType.width,
visible: commonGridSetting.documentType.visible
},
{
field: commonGridColumns.folderName, displayName: globalResources.CommonGridColumns.Chapter,
width: commonGridSetting.chapter.width,
cellTemplate: paths.FolderCellTemplate,
visible: commonGridSetting.chapter.visible
},
{
field: commonGridColumns.location, displayName: globalResources.CommonGridColumns.Location,
width: commonGridSetting.location.width,
cellTemplate: paths.LocationCellTemplate,
visible: commonGridSetting.location.visible
},
{
field: commonGridColumns.version, displayName: globalResources.CommonGridColumns.Version,
minWidth: commonGridSetting.version.minWidth,
width: commonGridSetting.version.width,
visible: commonGridSetting.version.visible
},
{
field: commonGridColumns.readCount, displayName: globalResources.CommonGridColumns.ReadCount,
width: commonGridSetting.readCount.width,
visible: commonGridSetting.readCount.visible
},
{
field: commonGridColumns.documentId, displayName: globalResources.CommonGridColumns.DocumentId,
minWidth: commonGridSetting.documentId.minWidth,
width: commonGridSetting.documentId.width,
visible: commonGridSetting.documentId.visible
},
{
field: commonGridColumns.approvedDate, displayName: globalResources.CommonGridColumns.ApprovedDate,
width: commonGridSetting.approvedDate.width,
visible: commonGridSetting.approvedDate.visible
},
{
field: commonGridColumns.approvedBy, displayName: globalResources.CommonGridColumns.Approver,
width: commonGridSetting.approver.width,
visible: commonGridSetting.approver.visible
},
{
field: commonGridColumns.responsible, displayName: globalResources.CommonGridColumns.DocumentResponsible,
width: commonGridSetting.responsible.width,
visible: commonGridSetting.responsible.visible
},
{
field: commonGridColumns.attachment, displayName: '',
width: commonGridSetting.hasAttachment.width,
cellTemplate: paths.DocumentAttachmentTemplate,
visible: commonGridSetting.hasAttachment.visible
},
{
field: commonGridColumns.readingReceipt, displayName: '',
width: commonGridSetting.readingReceipt.width,
visible: commonGridSetting.readingReceipt.visible
},
{
field: commonGridColumns.readingReceiptDtmConfirmed, displayName: globalResources.CommonGridColumns.ReadingReceiptDtmCOnfirmedColumnHeader,
width: commonGridSetting.readingReceiptDtmConfirmed.width,
visible: commonGridSetting.readingReceiptDtmConfirmed.visible
},
{
field: commonGridColumns.id, displayName: '',
width: commonGridSetting.id.width,
visible: false
}
];
optionalColumnsDenifinition = {
version: commonGridSetting.version.visible,
location: commonGridSetting.location.visible,
documentType: commonGridSetting.documentType.visible,
approvedDate: commonGridSetting.approvedDate.visible,
approver: commonGridSetting.approver.visible,
responsible: commonGridSetting.responsible.visible,
chapter: commonGridSetting.chapter.visible,
documentId: commonGridSetting.documentId.visible,
hasAttachment: commonGridSetting.hasAttachment.visible,
documentInfo: commonGridSetting.rowInfo.visible,
readingReceipt: commonGridSetting.readingReceipt.visible,
readingReceiptDtmConfirmed: commonGridSetting.readingReceiptDtmConfirmed.visible,
readCount: commonGridSetting.readCount.visible
};
if (internetPublishOption && !publishedVersion) {
// Add internet column after version column which has order 6
commonColumnsDefinition.splice(6, 0, {
field: commonGridColumns.internet,
displayName: '',
width: commonGridSetting.internet.width,
visible: commonGridSetting.internet.visible
});
optionalColumnsDenifinition.internet = commonGridSetting.internet.visible;
}
if (gridSettingKey == gridSettingKeys.readingListVisibilitySettings) {
commonColumnsDefinition.push({
field: commonGridColumns.readingList, displayName: globalResources.ReadingList,
width: commonGridSetting.readingList.width,
visible: commonGridSetting.readingList.visible
});
commonColumnsDefinition.push({
field: commonGridColumns.isConfirmed, displayName: globalResources.Confirmed,
width: commonGridSetting.readingList.width,
visible: commonGridSetting.readingList.visible
});
optionalColumnsDenifinition.readingList = commonGridSetting.readingList.visible;
optionalColumnsDenifinition.isConfirmed = commonGridSetting.isConfirmed.visible;
}
}
function getDefaultVisibleColumns(gridSettingKey) {
commonGridSetting.title.visible = true;
commonGridSetting.chapter.visible = true;
commonGridSetting.documentId.visible = true;
commonGridSetting.rowInfo.visible = true;
if (internetPublishOption && !publishedVersion) {
commonGridSetting.internet.visible = false;
}
if (gridSettingKey == gridSettingKeys.readingListVisibilitySettings) {
commonGridSetting.version.visible = true;
commonGridSetting.documentId.visible = true;
commonGridSetting.hasAttachment.visible = true;
commonGridSetting.readingReceipt.visible = false;
commonGridSetting.documentType.visible = false;
commonGridSetting.approvedDate.visible = false;
commonGridSetting.approver.visible = false;
commonGridSetting.responsible.visible = false;
commonGridSetting.location.visible = false;
commonGridSetting.readingList.visible = true;
commonGridSetting.readingReceiptDtmConfirmed.visible = false;
commonGridSetting.isConfirmed.visible = true;
commonGridSetting.readCount.visible = false;
}
getDefaultColumnWidth(gridSettingKey);
}
function clearColumnsVisibleSetting() {
commonGridSetting.chapter.visible = false;
commonGridSetting.documentId.visible = false;
commonGridSetting.documentType.visible = false;
commonGridSetting.readingList.visible = false;
commonGridSetting.isConfirmed.visible = false;
commonGridSetting.location.visible = false;
commonGridSetting.version.visible = false;
commonGridSetting.approvedDate.visible = false;
commonGridSetting.approver.visible = false;
commonGridSetting.responsible.visible = false;
commonGridSetting.hasAttachment.visible = false;
commonGridSetting.readingReceipt.visible = false;
commonGridSetting.readingReceiptDtmConfirmed.visible = false;
commonGridSetting.rowInfo.visible = false;
commonGridSetting.readCount.visible = false;
if (internetPublishOption && !publishedVersion) {
commonGridSetting.internet.visible = false;
}
}
function readVisibleColumnsFromLocalStorage(columnVisibleSettings) {
clearColumnsVisibleSetting();
var columnsSetting = columnVisibleSettings.split(',');
for (var i = 0; i < columnsSetting.length; i++) {
switch (columnsSetting[i]) {
case 'chapter':
commonGridSetting.chapter.visible = true;
break;
case 'documentId':
commonGridSetting.documentId.visible = true;
break;
case 'documentType':
commonGridSetting.documentType.visible = true;
break;
case 'readingList':
commonGridSetting.readingList.visible = true;
break;
case 'isConfirmed':
commonGridSetting.isConfirmed.visible = true;
break;
case 'location':
commonGridSetting.location.visible = true;
break;
case 'version':
commonGridSetting.version.visible = true;
break;
case 'approvedDate':
commonGridSetting.approvedDate.visible = true;
break;
case 'approver':
commonGridSetting.approver.visible = true;
break;
case 'responsible':
commonGridSetting.responsible.visible = true;
break;
case 'hasAttachment':
commonGridSetting.hasAttachment.visible = true;
break;
case 'readingReceipt':
commonGridSetting.readingReceipt.visible = true;
break;
case 'readingReceiptDtmConfirmed':
commonGridSetting.readingReceiptDtmConfirmed.visible = true;
break;
case 'documentInfo':
commonGridSetting.rowInfo.visible = true;
break;
case 'internet':
commonGridSetting.internet.visible = true;
case 'readCount':
commonGridSetting.readCount.visible = true;
break;
}
}
updateColumnWidth();
}
function getGridSetting(gridSettingKey) {
if (typeof (Storage) != "undefined") { // Browser is supported local storage
var existsInLocalStorage = false;
var columnVisibleSettings = gridSettingKey ? localStorage.getItem(gridSettingKey) : localStorage.getItem(gridSettingKeys.readingListVisibilitySettings);
if (columnVisibleSettings != undefined) {
existsInLocalStorage = true;
}
if (existsInLocalStorage) {
readVisibleColumnsFromLocalStorage(columnVisibleSettings);
} else {
getDefaultVisibleColumns(gridSettingKey);
}
} else {
getDefaultVisibleColumns(gridSettingKey);
}
}
function getDocumentColumnsForExporting(gridKey) {
var columns = [];
getGridSetting(gridKey);
columns.push(E.documentExportColumns.docUrl);
if (commonGridSetting.internet.visible) {
columns.push(E.documentExportColumns.isInternet);
}
columns.push(E.documentExportColumns.documentName);
if (commonGridSetting.documentType.visible) {
columns.push(E.documentExportColumns.documentType);
}
if (commonGridSetting.chapter.visible) {
columns.push(E.documentExportColumns.chapter);
}
if (commonGridSetting.location.visible) {
columns.push(E.documentExportColumns.location);
}
if (commonGridSetting.version.visible) {
columns.push(E.documentExportColumns.version);
}
if (commonGridSetting.readCount.visible) {
columns.push(E.documentExportColumns.readCount);
}
if (commonGridSetting.documentId.visible) {
columns.push(E.documentExportColumns.documentId);
}
if (commonGridSetting.approvedDate.visible) {
columns.push(E.documentExportColumns.approvedDate);
}
if (commonGridSetting.approver.visible) {
columns.push(E.documentExportColumns.approver);
}
if (commonGridSetting.responsible.visible) {
columns.push(E.documentExportColumns.documentResponsible);
}
if (commonGridSetting.hasAttachment.visible) {
columns.push(E.documentExportColumns.hasAttachment);
}
if (commonGridSetting.readingReceipt.visible) {
columns.push(E.documentExportColumns.readingReceipt);
}
if (commonGridSetting.readingReceiptDtmConfirmed.visible) {
columns.push(E.documentExportColumns.readingReceiptDtmConfirmed);
}
return columns;
}
function setGridSetting(gridSettingkey, gridColumns) {
var columnSettings = '';
if (gridColumns.documentType) {
columnSettings += 'documentType,';
}
if (gridColumns.location) {
columnSettings += 'location,';
}
if (gridSettingkey == gridSettingKeys.readingListVisibilitySettings) {
if (gridColumns.readingList) {
columnSettings += 'readingList,';
}
if (gridColumns.isConfirmed) {
columnSettings += 'isConfirmed,';
}
}
if (gridColumns.version) {
columnSettings += 'version,';
}
if (gridColumns.readCount) {
columnSettings += 'readCount,';
}
if (gridColumns.approvedDate) {
columnSettings += 'approvedDate,';
}
if (gridColumns.approver) {
columnSettings += 'approver,';
}
if (gridColumns.responsible) {
columnSettings += 'responsible,';
}
if (gridColumns.chapter) {
columnSettings += 'chapter,';
}
if (gridColumns.documentId) {
columnSettings += 'documentId,';
}
if (gridColumns.hasAttachment) {
columnSettings += 'hasAttachment,';
}
if (gridColumns.documentInfo) {
columnSettings += 'documentInfo,';
}
if (gridColumns.readingReceipt) {
columnSettings += 'readingReceipt,';
}
if (gridColumns.readingReceiptDtmConfirmed) {
columnSettings += 'readingReceiptDtmConfirmed,';
}
if (gridColumns.internet) {
columnSettings += 'internet';
}
//Remove last commna if any
var lastSplitterIndex = columnSettings.lastIndexOf(',');
if (lastSplitterIndex >= columnSettings.length - 1) {
columnSettings = columnSettings.substring(0, lastSplitterIndex);
}
if (gridSettingkey) {
localStorage.setItem(gridSettingkey, columnSettings);
} else {
localStorage.setItem(gridSettingKeys.commonVisibilitySettings, columnSettings);
}
getGridSetting(gridSettingkey);
}
function updateColumnWidth() {
commonGridSetting.title.width = '20%';
commonGridSetting.documentType.width = '12%';
commonGridSetting.chapter.width = '14%';
commonGridSetting.readingList.width = '0%';
commonGridSetting.isConfirmed.width = '0%';
commonGridSetting.location.width = '18%';
commonGridSetting.version.width = 'auto';
commonGridSetting.version.minWidth = '77px';
commonGridSetting.readCount.width = 'auto';
commonGridSetting.readCount.minWidth = '65px';
commonGridSetting.documentId.width = 'auto';
commonGridSetting.documentId.minWidth = '65px';
commonGridSetting.approvedDate.width = 'auto';
commonGridSetting.approvedDate.minWidth = '120px';
commonGridSetting.approver.width = '9%';
commonGridSetting.responsible.width = '10%';
commonGridSetting.hasAttachment.width = '4%';
commonGridSetting.readingReceipt.width = '4%';
commonGridSetting.readingReceiptDtmConfirmed.width = 'auto';
commonGridSetting.readingReceiptDtmConfirmed.minWidth = '120px';
commonGridSetting.id.width = '0%';
commonGridSetting.rowInfo.width = 'auto';
commonGridSetting.rowInfo.minWidth = '24px';
if (internetPublishOption && !publishedVersion) {
commonGridSetting.internet.width = '24px';
}
}
function getDefaultColumnWidth(gridSettingKey) {
commonGridSetting.title.width = '20%';
commonGridSetting.documentType.width = '12%';
commonGridSetting.chapter.width = '14%';
commonGridSetting.location.width = '18%';
commonGridSetting.version.width = 'auto';
commonGridSetting.version.minWidth = '77px';
commonGridSetting.version.width = 'auto';
commonGridSetting.version.minWidth = '65px';
commonGridSetting.documentId.width = '65px';
commonGridSetting.approvedDate.width = 'auto';
commonGridSetting.approvedDate.minWidth = '120px';
commonGridSetting.approver.width = '9%';
commonGridSetting.responsible.width = '10%';
commonGridSetting.hasAttachment.width = '4%';
commonGridSetting.readingReceipt.width = '4%';
commonGridSetting.readingReceiptDtmConfirmed.width = 'auto';
commonGridSetting.readingReceiptDtmConfirmed.minWidth = '120px';
commonGridSetting.id.width = '0%';
commonGridSetting.rowInfo.width = 'auto';
commonGridSetting.rowInfo.minWidth = '24px';
if (internetPublishOption && !publishedVersion) {
commonGridSetting.internet.width = '24px';
}
if (gridSettingKey == gridSettingKeys.readingListVisibilitySettings) {
commonGridSetting.readingList.width = '0%';
commonGridSetting.isConfirmed.width = '0%';
}
}
function getBooleanValue(val) {
return val === 'true';
}
function getArray(obj) {
var array = [];
for (var i in obj) {
array.push(obj[i]);
}
return array;
}
function groupBy(list, fn) {
var groups = {};
for (var i = 0; i < list.length; i++) {
var group = fn(list[i])[0];
if (group in groups) {
groups[group].value.data.push(list[i]);
} else {
groups[group] = { key: '', value: [] };
groups[group].key = group;
groups[group].value = { data: [], gridOption: {} };
groups[group].value.data.push(list[i]);
}
}
return getArray(groups);
}
String.format = function () {
var result = arguments[0];
for (var i = 0; i < arguments.length - 1; i++) {
var reg = new RegExp("\\{" + i + "\\}", "gm");
result = result.replace(reg, arguments[i + 1]);
}
return result;
}
function FormattedDateDMYYYY(date, delimiter) {
var month = date.getMonth() + 1;
var day = date.getDate();
var year = date.getFullYear();
return day + delimiter + month + delimiter + year;
}
function ngGridLayoutPlugin() {
var self = this;
this.grid = null;
this.scope = null;
this.init = function (scope, grid, services) {
self.domUtilityService = services.DomUtilityService;
self.grid = grid;
self.scope = scope;
};
this.updateGridLayout = function () {
if (self.scope == null) {
return;
}
if (!self.scope.$$phase) {
self.scope.$apply(function () {
self.domUtilityService.RebuildGrid(self.scope, self.grid);
});
}
else {
// $digest or $apply already in progress
self.domUtilityService.RebuildGrid(self.scope, self.grid);
}
};
}
function msieversion() {
var ua = window.navigator.userAgent
var msie = ua.indexOf("MSIE ")
if (msie > 0) // If Internet Explorer, return version number
return parseInt(ua.substring(msie + 5, ua.indexOf(".", msie)));
else if (!!navigator.userAgent.match(/Trident.*rv\:11\./)) // If another browser, return 0
return 11;
else
return 0;
}
function detectIE() {
var ua = window.navigator.userAgent;
// Test values; Uncomment to check result …
// IE 10
// ua = 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Trident/6.0)';
// IE 11
// ua = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
// Edge 12 (Spartan)
// ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36 Edge/12.0';
// Edge 13
// ua = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586';
var msie = ua.indexOf('MSIE ');
if (msie > 0) {
// IE 10 or older => return version number
return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
}
var trident = ua.indexOf('Trident/');
if (trident > 0) {
// IE 11 => return version number
var rv = ua.indexOf('rv:');
return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
}
var edge = ua.indexOf('Edge/');
if (edge > 0) {
// Edge (IE 12+) => return version number
return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
}
// other browser
return false;
}
function isSafari() {
var isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
return (isSafari == null ? false : isSafari);
}
var NewsGridConfig = {
pageSize: 10,
maxDisplayPage: 3
};
function splitDateString(dateString) {
if (dateString.indexOf('.') > -1) {
return dateString.split('.');
} else if (dateString.indexOf('/') > -1) {
return dateString.split('/');
} else if (dateString.indexOf('-') > -1) {
return dateString.split('-');
}
}
var Utils = {
ToDate: function (dateString) { //Norwegian format: dd.MM.yyyy
if (dateString == "" || dateString == null) {
return new Date('01-01-1900');
}
else {
var dateParts = splitDateString(dateString);
if (dateString.indexOf('/') > -1) {
return new Date(dateParts[2], dateParts[0] - 1, dateParts[1], 0, 0, 0, 0); //year, month, day, hours, minutes, seconds, milliseconds
}
return new Date(dateParts[2], dateParts[1] - 1, dateParts[0], 0, 0, 0, 0); //year, month, day, hours, minutes, seconds, milliseconds
}
},
ToDateTime: function (dateTimeString) {
if (dateTimeString == "" || dateTimeString == null) {
return new Date('01-01-1900');
}
else {
var dateTimeParts = dateTimeString.split(' ');
var dateParts = splitDateString(dateTimeParts[0]);
var timeParts = dateTimeParts[1].split(':');
if (dateString.indexOf('/') > -1) {
return new Date(dateParts[2], dateParts[0] - 1, dateParts[1], timeParts[0], timeParts[1], 0, 0); //year, month, day, hours, minutes, seconds, milliseconds
}
return new Date(dateParts[2], dateParts[1] - 1, dateParts[0], timeParts[0], timeParts[1], 0, 0); //year, month, day, hours, minutes, seconds, milliseconds
}
}
};
var dialogTypes = {
OK: 1,
OK_CANCEL: 2,
YES_NO: 3
};
var dialogResults = {
CONFIRM: 1,
CANCEL: 2
};
var RESPONSE_MESSAGE = {
recommended: 1,
notRecommended: 2,
neutral: 3
};
void function $getLines($) {
function countLines($element) {
var lines = 0;
var greatestOffset = void 0;
$element.find('character').each(function () {
if (!greatestOffset || this.offsetTop > greatestOffset) {
greatestOffset = this.offsetTop;
++lines;
}
});
return lines;
}
$.fn.getLines = function $getLines() {
var lines = 0;
var clean = this;
var dirty = this.clone();
(function wrapCharacters(fragment) {
var parent = fragment;
$(fragment).contents().each(function () {
if (this.nodeType === Node.ELEMENT_NODE) {
wrapCharacters(this);
}
else if (this.nodeType === Node.TEXT_NODE) {
void function replaceNode(text) {
var characters = document.createDocumentFragment();
text.nodeValue.replace(/[\s\S]/gm, function wrapCharacter(character) {
characters.appendChild($('' + character + '>')[0]);
});
parent.replaceChild(characters, text);
}(this);
}
});
}(dirty[0]));
clean.replaceWith(dirty);
lines = countLines(dirty);
dirty.replaceWith(clean);
return lines;
};
}(jQuery);
function getElementForTooltips(label, value) {
var fisrtOfElement = "
";
var centerOfElement = "";
var lastOfElement = "
";
return fisrtOfElement + label + centerOfElement + value + lastOfElement;
}
function generateRelatedDocumentTooltip(row) {
var result = "
";
result += getElementForTooltips(globalResources.LinkedVirtually, row.virtual ? globalResources.Yes : globalResources.No);
result += getElementForTooltips(globalResources.CommonGridColumns.Title, row.name);
result += getElementForTooltips(globalResources.CommonGridColumns.Type, row.template);
result += getElementForTooltips(globalResources.CommonGridColumns.Chapter, row.folderName);
result += getElementForTooltips(globalResources.CommonGridColumns.Location, row.location);
result += getElementForTooltips(globalResources.CommonGridColumns.Version, row.version);
result += getElementForTooltips(globalResources.CommonGridColumns.DocumentId, row.documentId);
result += getElementForTooltips(globalResources.CommonGridColumns.ApprovedDate, row.approvedDate);
result += getElementForTooltips(globalResources.CommonGridColumns.Approver, row.approvedBy);
result += getElementForTooltips(globalResources.CommonGridColumns.Responsible, row.responsible);
result += "
";
return result;
}
function createTooltipsRelatedDocument(data) {
if (data.relatedDocuments != null && data.relatedDocuments.length > 0) {
data.relatedDocuments.forEach(function (item) {
item.htmlTooltips = generateRelatedDocumentTooltip(item);
});
}
if (data.fieldContents != null) {
data.fieldContents.forEach(function (fieldContent) {
if (fieldContent.relatedDocuments != null && fieldContent.relatedDocuments.length > 0) {
fieldContent.relatedDocuments.forEach(function (item) {
item.htmlTooltips = generateRelatedDocumentTooltip(item);
});
}
});
}
}
var LANGUAGECULTURE = 'languageCulture';
var LANGUAGES = {
NORWEGIAN: 'no',
ENGLISH: 'en'
};
function getLanguageCulture() {
var result = '';
var cookieItems = document.cookie.split(';');
if (cookieItems != null && cookieItems.length > 0) {
for (var i = 0; i < cookieItems.length; i++) {
var items = cookieItems[i].split('=');
if (items != null && items.length > 0) {
if (items[0].replace(/\s/g, '') == LANGUAGECULTURE) {
result = items[1];
break;
}
}
}
}
return result;
}
/*Open dialog add members, roleId use for editrole view*/
function openAddMembersDialog(modal, existedMember, titlePage, roleId, excludedQuitDepartmentId, folderId) {
if (excludedQuitDepartmentId == null)
excludedQuitDepartmentId = false;
var modalInstance = modal.open({
templateUrl: '/app/components/document/addMembers.html',
controller: 'AddMembersController as vm',
size: 'lg',
resolve: {
existedEmployees: function () {
return existedMember;
},
titlePage: function () {
return titlePage;
},
roleId: function () {
return roleId;
},
excludedQuitDepartmentId: function () {
return excludedQuitDepartmentId;
},
folderId: function () {
return folderId;
}
}
});
return modalInstance;
};
var gridUtilities = {
lookupData: function (data, rowCollection, originalCollection, infiniteScrollLoadsize, total, currentRowIndex) {
var newTotal = data != null ? data.length : 0;
if (infiniteScrollLoadsize == 0) {
rowCollection = data;
originalCollection = angular.copy(rowCollection);
} else {
if ((rowCollection == null || rowCollection.length == 0) || total != newTotal) {
total = newTotal;
currentRowIndex = 0;
var response = gridUtilities.getAPageItem(data, infiniteScrollLoadsize, currentRowIndex, total);
rowCollection = response.data;
currentRowIndex = response.currentIndex;
originalCollection = angular.copy(rowCollection);
}
}
return { total: total, currentIndex: currentRowIndex, data: rowCollection };
},
getAPageItem: function (items, infiniteScrollLoadsize, currentRowIndex, total) {
var data = [];
var startIndex = currentRowIndex;
var endIndex = startIndex + infiniteScrollLoadsize;
for (var i = startIndex; i < endIndex; i++) {
if (currentRowIndex < total) {
data.push(items[i]);
currentRowIndex += 1;
} else {
break;
}
}
return { data: data, currentIndex: currentRowIndex };
}
};;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('dropdownList',['$document', function ($document) {
return {
restrict: 'E',
replace: true,
scope: {
items: '=',
selectedItem: '=',
disabledControl: '='
},
controller: ['$window', '$scope', '$filter', '$timeout', dropdownListController],
controllerAs: 'vm',
templateUrl: '/app/shared/directives/dropdownListTemplate.html',
link: function (scope, element, attrs, ctrl) {
scope.translation = globalResources;
scope.valueName = 'id';
scope.textName = 'name';
if (attrs.value) {
scope.valueName = attrs.value;
}
if (attrs.text) {
scope.textName = attrs.text;
}
if (attrs.disabledField) {
scope.disabled = attrs.disabledField;
}
if (attrs.disabledInfo) {
scope.disabledInfo = attrs.disabledInfo;
}
if (attrs.iconClasses) {
scope.iconClasses = attrs.iconClasses;
}
if(attrs.searchable){
scope.searchable = attrs.searchable == 'true';
}
scope.$watch('items', function (items) {
scope.visibleItems = items;
});
scope.showDropdownList = false;
$document.bind('click', function (event) {
var isClickedElementChildOfPopup = element
.find(event.target)
.length > 0;
if (isClickedElementChildOfPopup)
return;
scope.showDropdownList = false;
scope.$apply();
});
}
}
}]);
function dropdownListController($window, $scope, $filter, $timeout) {
var vm = this;
vm.nextPage = nextPage;
vm.selectItem = selectItem;
vm.removeCurrentItem = removeCurrentItem;
vm.onSearch = onSearch;
vm.onDataNavigating = onDataNavigating;
vm.onEnter = onEnter;
vm.currentRowIndex = 0;
var infiniteScrollLoadsize = (HandbookConfiguration.InfiniteScrollLoadSize == "0" || HandbookConfiguration.InfiniteScrollLoadSize == 0) ?
0 :
parseInt(HandbookConfiguration.InfiniteScrollLoadSize);
vm.infiniteItems = [];
vm.busy = false;
vm.newTotalItems = 0;
vm.selectedItemText = '';
vm.currentIndex = -1;
vm._scrollHeight = 0;
vm.visibleItems = [];
vm.infiniteItems = getAPage();
vm.showPopup = showPopup;
vm.showPopupWhenClickInput = showPopupWhenClickInput;
function selectItem(item, index) {
if ($scope.disabled && !item[$scope.disabled]) {
return;
}
$scope.selectedItem = item;
vm.selectedItem = item;
$scope.showDropdownList = false;
vm.selectedItemText = item[$scope.textName];
vm.currentItem = item;
vm.currentIndex = index;
}
function showPopup() {
if (!$scope.disabledControl) {
$scope.showDropdownList = !$scope.showDropdownList;
}
}
function showPopupWhenClickInput() {
if (!$scope.disabledControl) {
if (!$scope.searchable) {
$scope.showDropdownList = !$scope.showDropdownList;
}
}
}
function removeCurrentItem() {
vm.selectedItemText = '';
resetData();
if ($scope.visibleItems.length > 0)
vm.visibleItems = $scope.visibleItems.slice();
nextPage();
}
function onSearch(keyEvent) {
if (keyEvent.which != 38 && keyEvent.which != 40) {
if (keyEvent.which == 13) {
enterSelectItem();
}
else {
$scope.showDropdownList = true;
resetData();
var searchObject = {};
searchObject[$scope.textName] = vm.selectedItemText;
if ($scope.visibleItems.length > 0) {
var itemsVisible = $scope.visibleItems.slice();
vm.visibleItems = $filter('filter')(itemsVisible, searchObject);
nextPage();
}
}
}
};
function onEnter(keyEvent) {
if (keyEvent.which == 13) {
enterSelectItem();
}
};
function onDataNavigating(keyEvent) {
if ((keyEvent.which == 38 || keyEvent.which == 40) && $scope.showDropdownList) {
setcurrentItemInPopup(keyEvent.which);
}
};
function setcurrentItemInPopup(keyCode) {
if (keyCode == 38 && vm.currentIndex > 0) {
vm.currentIndex -= 1;
vm._scrollHeight -= 24;
}
if (keyCode == 40 && vm.currentIndex < vm.infiniteItems.length - 1) {
vm.currentIndex += 1;
vm._scrollHeight += 24;
}
if (vm.currentIndex == 0)
vm._scrollHeight = 0;
if ((keyCode == 40 && vm._scrollHeight + 10 > angular.element('#selectId')[0].clientHeight) || (keyCode == 38))
angular.element('#selectId')[0].scrollTop = vm._scrollHeight;
if (vm.currentIndex < vm.infiniteItems.length) {
vm.currentItem = vm.infiniteItems[vm.currentIndex];
}
};
function getAPage() {
if (vm.visibleItems != undefined) {
var data = [];
var startIndex = vm.currentRowIndex;
var endIndex = startIndex + infiniteScrollLoadsize;
for (var i = startIndex; i < endIndex; i++) {
if (vm.currentRowIndex < vm.visibleItems.length) {
data.push(vm.visibleItems[i]);
vm.currentRowIndex += 1;
} else {
break;
}
}
return data;
}
}
$scope.$watch('items', function (items) {
resetData();
$scope.visibleItems = items;
if ($scope.visibleItems !=null && $scope.visibleItems !=undefined && $scope.visibleItems.length > 0)
{
vm.visibleItems = $scope.visibleItems.slice();
vm.infiniteItems = getAPage();
}else
{
vm.visibleItems = null;
vm.infiniteItems = null;
}
});
$scope.$watch('selectedItem', function (selectedItem) {
if (selectedItem != null && selectedItem != undefined) {
vm.selectedItem = selectedItem;
vm.selectedItemText = selectedItem[$scope.textName];
vm.currentItem = selectedItem;
} else {
vm.selectedItemText = '';
vm.selectedItem = null;
vm.currentItem = null;
}
});
function nextPage() {
if (vm.busy) return;
vm.busy = true;
if (vm.infiniteItems != undefined) {
if (infiniteScrollLoadsize == 0) {
vm.infiniteItems = scope.visibleItems;
} else {
if (vm.infiniteItems.length <= vm.newTotalItems) {
vm.infiniteItems = vm.infiniteItems.concat(getAPage());
}
}
vm.newTotalItems = vm.infiniteItems.length;
}
vm.busy = false;
};
function resetData() {
$scope.selectedItem = null;
vm.selectedItem = null;
vm.currentItem = null;
vm.currentIndex = -1;
vm._scrollHeight = 0;
vm.currentRowIndex = 0;
vm.infiniteItems = [];
};
function enterSelectItem() {
if (vm.currentItem != null && (($scope.disabled && vm.currentItem[$scope.disabled]) || $scope.disabled == undefined || $scope.disabled == null)) {
$scope.selectedItem = vm.currentItem;
vm.selectedItem = vm.currentItem;
$scope.showDropdownList = false;
vm.selectedItemText = vm.currentItem[$scope.textName];
}
};
}
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npCommonGrid', function () {
return {
restrict: 'E',
transclude: true,
controller: ['$scope', '$state', '$timeout', '$filter', 'localStorageService', controller],
controllerAs: 'vm',
templateUrl: '/app/shared/grid/commonGrid.html',
scope: {
data: '=',
gridSetting: '=',
notFixHeightRow: '=',
hiddencheck: '=',
rowCss: '=',
maxHeight: '=',
identifier: '@',
wrapText: '=',
onSelectRow: '&onSelectRow',
onDoubleClick: '&onDoubleClick',
gridSettingKey: '@',
columnNotRemove: '=',
hiddenShowAll: '=',
showCheckboxOnProperty: '@',
onRowClick: '&onRowClick',
notUpperHeader: '=',
isTotalTitle: '='
},
link: function (scope, element, attrs, ctrl, transclude) {
transclude(scope, function (clone) {
element.append(clone);
});
if (scope.showCheckboxOnProperty != null) {
scope.$watch('data', function (data, old) {
if (data != null) {
var numberOfHiddenCheckboxes = 0;
for (var i = 0; i < data.length; i++) {
if (!data[i][scope.showCheckboxOnProperty]) {
numberOfHiddenCheckboxes++;
}
}
if (numberOfHiddenCheckboxes == data.length) {
scope.hideAllCheckboxes = true;
} else {
scope.hideAllCheckboxes = false;
}
}
});
}
}
};
});
function controller($scope, $state, $timeout, $filter, localStorageService) {
var vm = this;
vm.translation = globalResources;
vm.columnsDefinition = [];//$scope.gridSetting;
vm.commonGridSetting = [];//angular.copy(calculateColumnsWidth());
vm.onRowClick = onRowClick;
vm.onDoubleClick_ = function (row) {
$scope.onDoubleClick({ row: row });
};
vm.data = arrayCopy($scope.data);
vm.originalData = arrayCopy($scope.data);
vm.selectRow = selectRow;
vm.showColumnInformation = false;
$scope.reverse = true;
$scope.currentRowIndex = 0;
$scope.total = vm.data != null ? vm.data.length : 0;
$scope.rowCollection = [];
$scope.showAllDocuments = showAllDocuments;
$scope.selectedColumn = { order: 'descending', key: '' };
$scope.times = 0;
$scope.originalCollection = [];
vm.showSortIcon = true;
vm.totalTitle = $scope.isTotalTitle ? vm.translation.Total : vm.translation.TotalNumberDocument;
var orderBy = $filter('orderBy');
var infiniteScrollLoadsize = (HandbookConfiguration.InfiniteScrollLoadSize == "0" || HandbookConfiguration.InfiniteScrollLoadSize == 0) ?
0 :
parseInt(HandbookConfiguration.InfiniteScrollLoadSize);
$scope.initialize = function () {
getSettingGridColumn();
};
function getSettingGridColumn() {
vm.columnsDefinition = $scope.gridSetting;
if ($scope.gridSettingKey) {
var localStorage = localStorageService.getItem($scope.gridSettingKey);
if (localStorage != undefined) {
var objectLocalStorage = JSON.parse(localStorage);
vm.columnsDefinition = objectLocalStorage;
for (var i = 0; i < $scope.gridSetting.length; i++) {
vm.columnsDefinition[i].name = $scope.gridSetting[i].name;
}
}
}
vm.commonGridSetting = angular.copy(calculateColumnsWidth());
vm.showColumnInformation = false;
vm.commonGridSetting.forEach(function (item) {
if (item.id == 'information' && item.coldefault) {
vm.showColumnInformation = true;
}
});
};
var lastStart = 0;
$scope.nextPage = function getData(tableState) {
if (infiniteScrollLoadsize == 0) {
$scope.rowCollection = vm.data;
$scope.originalCollection = arrayCopy($scope.rowCollection);
} else {
//if we reset (like after a search or an order)
if (tableState.pagination.start === 0) {
if ($scope.rowCollection == null || $scope.rowCollection.length == 0) {
$scope.rowCollection = getAPage();
$scope.originalCollection = arrayCopy($scope.rowCollection);
}
} else {
//we load more
$scope.rowCollection = $scope.rowCollection.concat(getAPage());
$scope.originalCollection = arrayCopy($scope.rowCollection);
$scope.$apply();
}
lastStart = tableState.pagination.start;
}
};
$scope.order = function (predicate, type) {
$scope.reverse = !$scope.reverse;
var reverse = $scope.reverse;
if (predicate == $scope.selectedColumn.key || $scope.selectedColumn.key == "") { // Click header more than one time
$scope.times += 1;
} else { // Click another column
$scope.times = 1;
}
$scope.selectedColumn.key = predicate;
$scope.selectedColumn.order = reverse ? 'descending' : 'ascending';
if ($scope.times > 2) {
vm.showSortIcon = false;
vm.data = arrayCopy(vm.originalData);
$scope.reverse = !$scope.reverse;
$scope.times = 0;
} else {
switch (type) {
case COLUMN_DATA_TYPES.STRING_DATE_TIME:
vm.data.sort(function (x, y) {
var d1 = Utils.ToDateTime(x[predicate]);
var d2 = Utils.ToDateTime(y[predicate]);
if (reverse) {
return d1 > d2 ? -1 : (d1 == d2 ? 0 : 1);
} else {
return d1 > d2 ? 1 : (d1 == d2 ? 0 : -1);
}
});
break;
case COLUMN_DATA_TYPES.STRING_DATE:
vm.data.sort(function (x, y) {
var d1 = Utils.ToDate(x[predicate]);
var d2 = Utils.ToDate(y[predicate]);
if (reverse) {
return d1 > d2 ? -1 : (d1 == d2 ? 0 : 1);
} else {
return d1 > d2 ? 1 : (d1 == d2 ? 0 : -1);
}
});
break;
default:
vm.data = orderBy(vm.originalData, predicate, reverse);
break;
}
vm.showSortIcon = true;
}
$scope.rowCollection = vm.data.slice(0, $scope.currentRowIndex);
$scope.originalCollection = arrayCopy(vm.rowCollection);
};
$scope.$watch('data', function (data, old) { // This handler for initialize data.
vm.data = arrayCopy($scope.data);
vm.originalData = arrayCopy($scope.data);
var newTotal = data != null ? data.length : 0;
if (infiniteScrollLoadsize == 0) {
$scope.rowCollection = vm.data;
$scope.originalCollection = arrayCopy($scope.rowCollection);
} else {
if ($scope.rowCollection.length == 0 || $scope.total != newTotal) {
$scope.total = newTotal;
$scope.currentRowIndex = 0;
$scope.rowCollection = getAPage();
$scope.originalCollection = arrayCopy($scope.rowCollection);
$timeout(function () { //scroll a bit up
var gridBody = angular.element('#' + folderContent.gridDocuments + ' tbody')[0];
var scrollTop = gridBody.scrollTop;
gridBody.scrollTop -= scrollTop / 2;
}, 10, false);
}
}
}, true);
$scope.$on(broadcastType.gridDataChanges, function (e, target) {
if (target.id == $scope.identifier) {
var newTotal = target.data != null ? target.data.length : 0;
if (infiniteScrollLoadsize == 0) {
$scope.rowCollection = target.data;
$scope.originalCollection = arrayCopy($scope.rowCollection);
} else {
if ($scope.rowCollection.length == 0 || $scope.total != newTotal || target.isForced) {
$scope.total = newTotal;
$scope.currentRowIndex = 0;
vm.data = target.data;
$scope.rowCollection = getAPage();
$scope.originalCollection = arrayCopy($scope.rowCollection);
$timeout(function () { //scroll a bit up
var gridBody = angular.element('#' + folderContent.gridDocuments + ' tbody')[0];
var scrollTop = gridBody.scrollTop;
gridBody.scrollTop -= scrollTop / 2;
}, 10, false);
}
}
}
});
$scope.$on($scope.gridSettingKey, function (e, target) {
getSettingGridColumn();
});
function showAllDocuments() {
$scope.rowCollection = vm.data;
$scope.originalCollection = arrayCopy($scope.rowCollection);
$scope.currentRowIndex = $scope.total;
}
function getAPage() {
var data = [];
var startIndex = $scope.currentRowIndex;
var endIndex = startIndex + infiniteScrollLoadsize;
for (var i = startIndex; i < endIndex; i++) {
if ($scope.currentRowIndex < $scope.total) {
data.push(vm.data[i]);
$scope.currentRowIndex += 1;
} else {
break;
}
}
return data;
}
function onRowClick(id) {
$scope.onRowClick({id: id});
};
function selectRow(e, row) {
e.stopPropagation();
}
function calculateColumnsWidth(numColumns, extraWidth) {
var __numCoumns = numColumns == null ? 0 : numColumns;
var __extraWidth = extraWidth == null ? 0 : extraWidth;
var additionWidth = 0;
if (__numCoumns > 0) {
additionWidth = (__extraWidth / __numCoumns);
}
var temp = [];
angular.copy(vm.columnsDefinition, temp);
var ratio100 = 100;
var columns = 0;
var index = -1;
for (var i = 0; i < vm.columnsDefinition.length; i++) {
var column = vm.columnsDefinition[i];
if (column.coldefault && column.id != $scope.columnNotRemove) {
if (String(column.width).indexOf('px') <= 0) {
var ratio = additionWidth + parseInt(column.width);
ratio100 = ratio100 - ratio;
temp[i].width = ratio + '%';
columns += 1;
}
} else if (column.id == $scope.columnNotRemove) {
index = i;
}
}
if (index != -1) {
temp[index].width = ratio100 + "%";
}
if (ratio100 > 51 && ratio100 != 100) {
temp = calculateColumnsWidth(columns, (ratio100 - 50));
}
return temp;
}
$scope.$watch('gridSetting', function (newData, oldData) {
if (newData != null && newData != oldData) {
getSettingGridColumn();
}
});
function arrayCopy(data) {
if (data && data.length > 0) {
return data.slice();
}
};
};
})();;
(function () {
'use strict';
angular.module('customeDirectivesModule')
.directive('ngLoadDirective', loadDirective)
.directive('inLoadingStateWhenClick', buttonDirective);
loadDirective.$inject = ['$http'];
function loadDirective($http) {
return {
restrict: 'A',
template: '',
link: function (scope, elm, attrs) {
scope.isLoading = function () {
return isShowLoading($http.pendingRequests);
};
scope.$watch(scope.isLoading, function (v) {
if (v) {
elm.show();
} else {
elm.hide();
}
});
function isShowLoading(pendingRequests) {
return pendingRequests.some(function (r) {
return (r.params && r.params.showLoading);
});
}
}
};
}
buttonDirective.$inject = ['$parse', '$q', '$timeout'];
function buttonDirective($parse, $q, $timeout) {
return {
restrict: 'A',
priority: 0,
link: function (scope, element, attrs) {
var action = $parse(attrs.inLoadingStateWhenClick);
element.on('click', function (e) {
element.attr('disabled', 'disabled');
$timeout(function () {
var promise = action(scope, { $event: e }),
isPromise = promise && promise.finally;
if (isPromise) {
promise
.then(function (promise) {
if (promise && promise.message) {
return $q.reject(promise.message);
}
})
.catch(function (exception) {
if (exception) {
console.log(exception);
}
})
.finally(function () {
releaseClick();
});
} else {
releaseClick();
}
});
});
function releaseClick() {
element.removeAttr('disabled');
element.find('.processing').remove();
}
}
};
}
})();;
(function () {
'use strict';
angular.module('newsListModule', [])
.controller('NewsListController', NewsListController);
NewsListController.$inject = ['$state', '$http', '$scope', '$sce', '$timeout', '$window', 'newsService', 'tabStateService'];
function NewsListController($state, $http, $scope, $sce, $timeout, $window, newsService, tabStateService) {
var vm = this;
vm.loadNews = loadNews;
vm.toggleLoadAllNews = false;
vm.news = [];
vm.currentPage = -1;
vm.startPage = -1;
vm.totalResults = 0;
vm.maxDisplayPage = NewsGridConfig.maxDisplayPage;
vm.itemPerPage = HandbookConfiguration.NewsPageSize;
vm.pageSize = HandbookConfiguration.NewsPageSize;
vm.translation = {
title: globalResources.CommonGridColumns.Title,
createdDate: globalResources.CreatedDate,
first: globalResources.First,
last: globalResources.Last,
description: globalResources.Description,
publishedDate: globalResources.Published,
ingress: globalResources.Ingress
};
vm.newsSetting = [];
function newsSetting() {
vm.newsSetting.push({ id: 'title', name: vm.translation.title, width: 35, coldefault: true });
vm.newsSetting.push({ id: 'dtmPublish', name: vm.translation.publishedDate, width: '90px', coldefault: true });
vm.newsSetting.push({ id: 'ingress', name: vm.translation.ingress, width: 60, coldefault: true });
}
initialize();
function initialize() {
getHeightGrid();
newsSetting();
loadAllNews($state.params.pageIndex);
}
function loadNews(id) {
newsService
.updateNewsReadCount(id)
.then(function (result) {
$state.go(handbookActions.StartpageNews, { newsId: id, isPreview: false });
});
}
function getInternetExplorerVersion() {
var rv = -1;
if (navigator.appName == 'Microsoft Internet Explorer') {
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
else if (navigator.appName == 'Netscape') {
var ua = navigator.userAgent;
var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat(RegExp.$1);
}
return rv;
}
function isMobile() {
try {
if (/Android|webOS|iPhone|iPad|iPod|pocket|psp|kindle|avantgo|blazer|midori|Tablet|Palm|maemo|plucker|phone|BlackBerry|symbian|IEMobile|mobile|ZuneWP7|Windows Phone|Opera Mini/i.test(navigator.userAgent)) {
return true;
};
return false;
} catch (e) { console.log("Error in isMobile"); return false; }
}
function getHeightGrid() {
var documentHeight = isMobile() ? window.innerHeight : $(window).height();
var $gridTop = $('.table.gridStyle.margin-bottom-0');
var top = ($gridTop.eq(0).offset() == null) ? 0 : $gridTop.eq(0).offset().top;
var height = (documentHeight - top - 160);
if (getInternetExplorerVersion() > -1) {
angular.element('.scrollableTable').css('max-height', height + 'px');
} else {
angular.element('#gridController').css('max-height', height + 'px');
}
}
$(window).on('resize', function () {
getHeightGrid();
});
function loadAllNews(pageIndex, pageSize) {
if (!pageIndex || pageIndex == -1) {
pageIndex = 1;
}
if (pageIndex != vm.startPage) {
user.currentNewsPage = pageIndex;
newsService
.getNewsWithPaging(pageIndex - 1, pageSize || vm.pageSize)
.then(function (result) {
vm.news = result.data.news;
vm.totalResults = result.data.totalResults;
vm.currentPage = pageIndex;
vm.startPage = pageIndex;
addTrustAsHtml();
});
}
}
function addTrustAsHtml() {
if (vm.news != null) {
vm.news.forEach(function (item) {
item.ingress = $sce.trustAsHtml(item.ingress);
});
}
}
$scope.$watch('vm.currentPage', function (newPage) {
if (vm.currentPage != -1) {
loadAllNews(newPage);
}
});
};
})();
;
(function () {
'use strict';
angular.module('NewsCategoryModule', [])
.controller('NewsCategoryController', NewsCategoryController);
NewsCategoryController.$inject = ['$state', '$scope', '$sce','newsService'];
function NewsCategoryController($state, $scope, $sce, newsService) {
var vm = this;
vm.loadNews = loadNews;
vm.toggleLoadAllNews = false;
vm.news = [];
vm.currentPage = -1;
vm.startPage = -1;
vm.totalResults = 0;
vm.maxDisplayPage = NewsGridConfig.maxDisplayPage;
vm.itemPerPage = HandbookConfiguration.NewsPageSize;
vm.pageSize = HandbookConfiguration.NewsPageSize;
vm.translation = {
title: globalResources.CommonGridColumns.Title,
createdDate: globalResources.CreatedDate,
first: globalResources.First,
last: globalResources.Last,
description: globalResources.Description,
publishedDate: globalResources.Published
};
vm.newsSetting = [];
function newsSetting() {
vm.newsSetting.push({ id: 'title', name: vm.translation.title, width: 30, coldefault: true });
vm.newsSetting.push({ id: 'dtmPublish', name: vm.translation.publishedDate, width: 20, coldefault: true });
vm.newsSetting.push({ id: 'ingress', name: vm.translation.description, width: 50, coldefault: true });
};
initialize();
function initialize() {
newsSetting();
loadAllNews($state.params.pageIndex);
};
function loadNews(id) {
newsService
.updateNewsReadCount(id)
.then(function (result) {
$state.go(handbookActions.StartpageNews, { newsId: id, isPreview: false });
});
};
function loadAllNews(pageIndex, pageSize) {
if (!pageIndex || pageIndex == -1) {
pageIndex = 1;
}
if (pageIndex != vm.startPage) {
user.currentNewsPage = pageIndex;
newsService
.getNewsByCategoryId($state.params.categoryId, E.NewsCategoryShownIn.shownInHandbookFrontend, pageIndex - 1, pageSize || vm.pageSize)
.then(function (result) {
vm.news = result.data.news;
vm.totalResults = result.data.totalResults;
vm.currentPage = pageIndex;
vm.startPage = pageIndex;
addTrustAsHtml();
});
}
};
function addTrustAsHtml() {
if (vm.news != null) {
vm.news.forEach(function (item) {
item.ingress = $sce.trustAsHtml(item.ingress);
});
}
};
$scope.$watch('vm.currentPage', function (newPage) {
if (vm.currentPage != -1) {
loadAllNews(newPage);
}
});
};
})();
;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npShareUrlButton', [function () {
return {
restrict: 'E',
controller: ['$scope', '$timeout', controller],
scope: {
url: '=',
name: '='
},
templateUrl: '/app/shared/shareURL/shareUrl.html',
transclue: true,
controllerAs: 'vm'
};
}]);
function controller($scope, $timeout) {
var vm = this;
vm.translation = globalResources;
vm.tooltip = vm.translation.CopyUserFriendlyUrl;
vm.getShareLink = getShareLink;
function getShareLink() {
angular.element('.shareurl-button').addClass('opacity-0-5');
var shareLink = '' + $scope.name + '';
$('#html-container').text(shareLink);
var htmlEditor = CodeMirror.fromTextArea(document.getElementById('html-container'), {
mode: 'text/html'
});
var cm = $('.CodeMirror')[0].CodeMirror;
$(cm.getWrapperElement()).hide();
copyFormatted(htmlEditor.getValue());
$timeout(function () {
angular.element('.shareurl-button').removeClass('opacity-0-5');
$scope.$apply();
}, 5000, false);
}
function copyFormatted(html) {
// Create an iframe (isolated container) for the HTML
var container = document.createElement('div');
container.innerHTML = html;
// Hide element
container.style.position = 'fixed';
container.style.pointerEvents = 'none';
container.style.opacity = 0;
// Mount the iframe to the DOM to make `contentWindow` available
document.body.appendChild(container);
// Copy to clipboard
window.getSelection().removeAllRanges();
var range = document.createRange();
range.selectNode(container);
window.getSelection().addRange(range);
//copy selected dom
document.execCommand('copy');
// Remove the iframe
document.body.removeChild(container);
}
}
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npCommonGridSetting', ['$document', function ($document) {
return {
restrict: 'E',
controller: ['$scope', 'broadcastService','localStorageService', controller],
scope: {
columnsConfiguration: '=',
color: '@',
gridSettingKey: '@',
columnNotRemove: '=',
showInfoCol: '='
},
templateUrl: '/app/shared/grid/commonGridSetting.html',
replace: true,
link: function (scope, element, attr) {
scope.showGridSettingContextMenu = false;
$('body').click(function (event) {
var isClickedElementChildOfPopup = element
.find(event.target)
.length > 0;
if (isClickedElementChildOfPopup)
return;
scope.showGridSettingContextMenu = false;
});
}
};
}]);
function controller($scope, broadcastService, localStorageService) {
$scope.translation = globalResources;
$scope.optionalColumns = angular.copy($scope.columnsConfiguration);
$scope.initialize = function () {
loadColumnsConfiguration();
}
function loadColumnsConfiguration() {
var localStorage = localStorageService.getItem($scope.gridSettingKey);
if (localStorage != undefined) {
var objectLocalStorage = JSON.parse(localStorage);
$scope.columnsConfiguration = objectLocalStorage;
} else {
$scope.columnsConfiguration = angular.copy($scope.optionalColumns);
}
}
$scope.updateGrid = function ($event) {
localStorageService.setItem($scope.gridSettingKey, JSON.stringify($scope.columnsConfiguration));
$scope.showGridSettingContextMenu = !$scope.showGridSettingContextMenu;
//var gridSetting = getGridSetting($scope.gridSettingKey);
broadcastService($scope.gridSettingKey, {
value: $scope.columnsConfiguration
});
};
$scope.checkItem = function (column) {
if (column.id != $scope.columnNotRemove) {
column.coldefault = !column.coldefault;
}
};
$scope.checkAll = function () {
$scope.columnsConfiguration.forEach(function (item) {
if (item.id != $scope.columnNotRemove) {
item.coldefault = true;
}
});
};
$scope.uncheckAll = function () {
$scope.columnsConfiguration.forEach(function (item) {
if (item.id != $scope.columnNotRemove) {
item.coldefault = false;
}
});
};
$scope.showPopup = function () {
$scope.showGridSettingContextMenu = !$scope.showGridSettingContextMenu;
if ($scope.showGridSettingContextMenu) {
loadColumnsConfiguration();
}
};
}
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npRowInfoTooltip', ['$document', function ($document) {
return {
restrict: 'E',
controller: ['$scope', '$sce', controller],
controllerAs: 'vm',
scope: {
objectTooltip: '=',
backgroundColor: '='
},
templateUrl: '/app/shared/grid/rowInfoTooltip.html',
replace: true
};
}]);
function controller($scope, $sce) {
var vm = this;
vm.htmlText = '';
vm.init = init;
function init() {
var html = '
" + $scope.translation.HearingEmailNotificationTooltip;
html += "
";
html += '
';
vm.hearingEmailNotificationTooltip = $sce.trustAsHtml(html);
$scope.initialize = function () {
vm.donotShowAgain = false;
vm.shouldApplyRecursive = true;
if ($scope.dialogInfo.title == '' || $scope.dialogInfo.title == null) {
switch ($scope.dialogInfo.type) {
case dialogTypes.OK:
$scope.dialogInfo.title = $scope.translation.InformDialogTitle;
break;
case dialogTypes.OK_CANCEL:
case dialogTypes.YES_NO:
$scope.dialogInfo.title = $scope.translation.ConfirmDialogTitle;
break;
default:
$scope.dialogInfo.title = $scope.translation.InformDialogTitle;
break;
}
}
if ($scope.dialogInfo.enableButton != null) {
vm.enableButton = $scope.dialogInfo.enableButton;
}
}
function confirm($event) {
if ($scope.dialogInfo.toggleDonotShowAgain) {
$modalInstance.close({ result: dialogResults.CONFIRM, donotShowAgain: vm.donotShowAgain });
} else if ($scope.dialogInfo.toggleApplyRecursive) {
$modalInstance.close({ result: dialogResults.CONFIRM, shouldApplyRecursive: vm.shouldApplyRecursive });
} if ($scope.dialogInfo.toggleReason) {
$modalInstance.close({ result: dialogResults.CONFIRM, reason: vm.reason, emailNotification: vm.hearingEmailNotification });
} else {
$modalInstance.close(dialogResults.CONFIRM);
}
}
function cancel($event) {
if ($scope.dialogInfo.toggleDonotShowAgain) {
$modalInstance.close({ result: dialogResults.CANCEL, donotShowAgain: vm.donotShowAgain });
} else if ($scope.dialogInfo.toggleApplyRecursive) {
$modalInstance.close({ result: dialogResults.CANCEL, shouldApplyRecursive: vm.shouldApplyRecursive });
} if ($scope.dialogInfo.toggleReason) {
$modalInstance.close({ result: dialogResults.CANCEL, reason: vm.reason });
} else {
$modalInstance.close(dialogResults.CANCEL);
}
}
};
})();
;
(function () {
angular
.module('servicesModule')
.controller('dialogExporter', ['$window', '$scope', '$http', '$stateParams', 'ngDialog', dialogExporter]);
function dialogExporter($window, $scope, $http, $stateParams, ngDialog) {
$scope.resources = globalResources;
$scope.isExportExcel = true;
$scope.fileName = $scope.ngDialogData.fileName;
$scope.submit = submit;
$scope.cancel = cancel;
$scope.toggleExcelExport = toggleExcelExport;
$scope.toggleWordExport = toggleWordExport;
//init current language
$scope.language = getLanguageCulture();
if ($scope.language == null || $scope.language == '') {
$scope.language = LANGUAGES.NORWEGIAN;
}
function toggleExcelExport() {
$scope.isExportWord = false;
}
function toggleWordExport() {
$scope.isExportExcel = false;
}
function submit() {
var url = $scope.isExportExcel
? $scope.ngDialogData.excelExporterUrl
: $scope.ngDialogData.wordExporterUrl;
var extension = $scope.isExportExcel ? "xlsx" : "docx";
$scope.ngDialogData.exportParams.language = $scope.language;
$http({
url: url,
method: 'POST',
data: $scope.ngDialogData.exportParams,
responseType: 'blob'
})
.success(function (data) {
ngDialog.close();
var fileName = $scope.fileName + "." + extension;
$window.saveAs(data, fileName);
});
}
function cancel() {
ngDialog.close();
}
}
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('npDocumentEmailFavorite', function () {
return {
restrict: 'E',
replace: true,
controller: ['$scope', '$http', controller],
controllerAs: 'vm',
templateUrl: '/app/shared/favoriteButton/documentEmailFavorite.html',
scope: {
documentId: '=',
isEmailSubscribe: '='
},
link: function (scope, element, attr) {
}
};
});
function controller($scope, $http) {
var vm = this;
vm.translation = globalResources;
if (vm.translation.SubscribeToChanges.indexOf('\n(CTRL + ALT + E)') <= 0) {
vm.translation.SubscribeToChanges = vm.translation.SubscribeToChanges + '\n(CTRL + ALT + E)';
}
vm.addDocumetEmailSubscription = addDocumetEmailSubscription;
vm.remoteDocumetEmailSubscription = remoteDocumetEmailSubscription;
function addDocumetEmailSubscription() {
var requestUrl = handbookRequests.AddEmailSubscriptionDocument + '/' + $scope.documentId;
$http.post(requestUrl)
.then(function () {
$scope.isEmailSubscribe = !$scope.isEmailSubscribe;
});
};
function remoteDocumetEmailSubscription() {
var requestUrl = handbookRequests.RemoveEmailSubscriptionDocument + '/' + $scope.documentId;
$http.post(requestUrl)
.then(function () {
$scope.isEmailSubscribe = !$scope.isEmailSubscribe;
});
};
$scope.$on(broadcastType.toggleEmailSubscriptionTarget, function (e, target) {
if (angular.element('#document-email-subscribe').hasClass('ng-hide')) {
remoteDocumetEmailSubscription();
} else {
addDocumetEmailSubscription();
}
});
}
})();;
(function () {
var directivesModule = angular.module('customeDirectivesModule');
directivesModule.directive('autoResize', autoResize);
autoResize.$inject = ['$timeout'];
function autoResize($timeout) {
var directive = {
restrict: 'A',
link: function autoResizeLink(scope, element, attributes, controller) {
element.css({ 'height': '100px', 'overflow-y': 'auto' });
element.on('focus', function () {
extendHeight();
});
element.on('input', function () {
extendHeight();
});
scope.$watch(attributes.ngModel, function (newVal) {
if (!newVal) {
element.css({ 'height': '100px'});
}
});
function extendHeight() {
var height = element[0].scrollHeight;
height = (!height || height <= 100) ? 100 : height + 2;
element.css('height', height + 'px');
}
}
};
return directive;
};
})();;
/**
* An Angular module that implements a Publish Subscribe service with support for message history.
* @version v1.0.0 - 2015-04-02
* @link https://github.com/jmnsf/angular-pub-sub
* @author jmnsf
* @license MIT License, http://www.opensource.org/licenses/MIT
*/!function(a,b,c){"use strict";var d=b.module("PubSubModule",[]);d.provider("pubSub",function(){this.maxHistory=10,this.setMaxHistory=function(a){return this.maxHistory=a,this},this.$get=function(){var a=this,b={},d=0,e=function(a,b){var c=k();return a[c]=b,h(a,c)},f=function(b,c){a.maxHistory<=0||(b.history.push(c),b.history.length>a.maxHistory&&b.history.shift())},g=function(){var a={};return Object.defineProperty(a,"history",{value:[],enumerable:!1}),a},h=function(a,b){return function(){delete a[b]}},i=function(a,b){for(var c=[],d=b;d
//
//
//
//
//
// or:
//
//
//
//
//
//
//
//
//
//
//
//
// You can also measure the single element's height/width (including all paddings and margins), and then speficy it as a value
// of the attribute 'vs-repeat'. This can be used if one wants to override the automatically computed element size.
// example:
//
//
//
//
//
//
// IMPORTANT!
//
// - the vsRepeat directive must be applied to a direct parent of an element with ngRepeat
// - the value of vsRepeat attribute is the single element's height/width measured in pixels. If none provided, the directive
// will compute it automatically
// OPTIONAL PARAMETERS (attributes):
// vs-repeat-container="selector" - selector for element containing ng-repeat. (defaults to the current element)
// vs-scroll-parent="selector" - selector to the scrollable container. The directive will look for a closest parent matching
// the given selector (defaults to the current element)
// vs-horizontal - stack repeated elements horizontally instead of vertically
// vs-offset-before="value" - top/left offset in pixels (defaults to 0)
// vs-offset-after="value" - bottom/right offset in pixels (defaults to 0)
// vs-excess="value" - an integer number representing the number of elements to be rendered outside of the current container's viewport
// (defaults to 2)
// vs-size - a property name of the items in collection that is a number denoting the element size (in pixels)
// vs-autoresize - use this attribute without vs-size and without specifying element's size. The automatically computed element style will
// readjust upon window resize if the size is dependable on the viewport size
// vs-scrolled-to-end="callback" - callback will be called when the last item of the list is rendered
// vs-scrolled-to-end-offset="integer" - set this number to trigger the scrolledToEnd callback n items before the last gets rendered
// vs-scrolled-to-beginning="callback" - callback will be called when the first item of the list is rendered
// vs-scrolled-to-beginning-offset="integer" - set this number to trigger the scrolledToBeginning callback n items before the first gets rendered
// EVENTS:
// - 'vsRepeatTrigger' - an event the directive listens for to manually trigger reinitialization
// - 'vsRepeatReinitialized' - an event the directive emits upon reinitialization done
var dde = document.documentElement,
matchingFunction = dde.matches ? 'matches' :
dde.matchesSelector ? 'matchesSelector' :
dde.webkitMatches ? 'webkitMatches' :
dde.webkitMatchesSelector ? 'webkitMatchesSelector' :
dde.msMatches ? 'msMatches' :
dde.msMatchesSelector ? 'msMatchesSelector' :
dde.mozMatches ? 'mozMatches' :
dde.mozMatchesSelector ? 'mozMatchesSelector' : null;
var closestElement = angular.element.prototype.closest || function (selector) {
var el = this[0].parentNode;
while (el !== document.documentElement && el != null && !el[matchingFunction](selector)) {
el = el.parentNode;
}
if (el && el[matchingFunction](selector)) {
return angular.element(el);
}
else {
return angular.element();
}
};
function getWindowScroll() {
if ('pageYOffset' in window) {
return {
scrollTop: pageYOffset,
scrollLeft: pageXOffset
};
}
else {
var sx, sy, d = document, r = d.documentElement, b = d.body;
sx = r.scrollLeft || b.scrollLeft || 0;
sy = r.scrollTop || b.scrollTop || 0;
return {
scrollTop: sy,
scrollLeft: sx
};
}
}
function getClientSize(element, sizeProp) {
if (element === window) {
return sizeProp === 'clientWidth' ? window.innerWidth : window.innerHeight;
}
else {
return element[sizeProp];
}
}
function getScrollPos(element, scrollProp) {
return element === window ? getWindowScroll()[scrollProp] : element[scrollProp];
}
function getScrollOffset(vsElement, scrollElement, isHorizontal) {
var vsPos = vsElement.getBoundingClientRect()[isHorizontal ? 'left' : 'top'];
var scrollPos = scrollElement === window ? 0 : scrollElement.getBoundingClientRect()[isHorizontal ? 'left' : 'top'];
var correction = vsPos - scrollPos +
(scrollElement === window ? getWindowScroll() : scrollElement)[isHorizontal ? 'scrollLeft' : 'scrollTop'];
return correction;
}
var vsRepeatModule = angular.module('vs-repeat', []).directive('vsRepeat', ['$compile', '$parse', function($compile, $parse) {
return {
restrict: 'A',
scope: true,
compile: function($element, $attrs) {
var repeatContainer = angular.isDefined($attrs.vsRepeatContainer) ? angular.element($element[0].querySelector($attrs.vsRepeatContainer)) : $element,
ngRepeatChild = repeatContainer.children().eq(0),
ngRepeatExpression,
childCloneHtml = ngRepeatChild[0].outerHTML,
expressionMatches,
lhs,
rhs,
rhsSuffix,
originalNgRepeatAttr,
collectionName = '$vs_collection',
isNgRepeatStart = false,
attributesDictionary = {
'vsRepeat': 'elementSize',
'vsOffsetBefore': 'offsetBefore',
'vsOffsetAfter': 'offsetAfter',
'vsScrolledToEndOffset': 'scrolledToEndOffset',
'vsScrolledToBeginningOffset': 'scrolledToBeginningOffset',
'vsExcess': 'excess'
};
if (ngRepeatChild.attr('ng-repeat')) {
originalNgRepeatAttr = 'ng-repeat';
ngRepeatExpression = ngRepeatChild.attr('ng-repeat');
}
else if (ngRepeatChild.attr('data-ng-repeat')) {
originalNgRepeatAttr = 'data-ng-repeat';
ngRepeatExpression = ngRepeatChild.attr('data-ng-repeat');
}
else if (ngRepeatChild.attr('ng-repeat-start')) {
isNgRepeatStart = true;
originalNgRepeatAttr = 'ng-repeat-start';
ngRepeatExpression = ngRepeatChild.attr('ng-repeat-start');
}
else if (ngRepeatChild.attr('data-ng-repeat-start')) {
isNgRepeatStart = true;
originalNgRepeatAttr = 'data-ng-repeat-start';
ngRepeatExpression = ngRepeatChild.attr('data-ng-repeat-start');
}
else {
throw new Error('angular-vs-repeat: no ng-repeat directive on a child element');
}
expressionMatches = /^\s*(\S+)\s+in\s+([\S\s]+?)(track\s+by\s+\S+)?$/.exec(ngRepeatExpression);
lhs = expressionMatches[1];
rhs = expressionMatches[2];
rhsSuffix = expressionMatches[3];
if (isNgRepeatStart) {
var index = 0;
var repeaterElement = repeatContainer.children().eq(0);
while(repeaterElement.attr('ng-repeat-end') == null && repeaterElement.attr('data-ng-repeat-end') == null) {
index++;
repeaterElement = repeatContainer.children().eq(index);
childCloneHtml += repeaterElement[0].outerHTML;
}
}
repeatContainer.empty();
return {
pre: function($scope, $element, $attrs) {
var repeatContainer = angular.isDefined($attrs.vsRepeatContainer) ? angular.element($element[0].querySelector($attrs.vsRepeatContainer)) : $element,
childClone = angular.element(childCloneHtml),
childTagName = childClone[0].tagName.toLowerCase(),
originalCollection = [],
originalLength,
$$horizontal = typeof $attrs.vsHorizontal !== 'undefined',
$beforeContent = angular.element('<' + childTagName + ' class="vs-repeat-before-content">' + childTagName + '>'),
$afterContent = angular.element('<' + childTagName + ' class="vs-repeat-after-content">' + childTagName + '>'),
autoSize = !$attrs.vsRepeat,
sizesPropertyExists = !!$attrs.vsSize || !!$attrs.vsSizeProperty,
$scrollParent = $attrs.vsScrollParent ?
$attrs.vsScrollParent === 'window' ? angular.element(window) :
closestElement.call(repeatContainer, $attrs.vsScrollParent) : repeatContainer,
$$options = 'vsOptions' in $attrs ? $scope.$eval($attrs.vsOptions) : {},
clientSize = $$horizontal ? 'clientWidth' : 'clientHeight',
offsetSize = $$horizontal ? 'offsetWidth' : 'offsetHeight',
scrollPos = $$horizontal ? 'scrollLeft' : 'scrollTop';
$scope.totalSize = 0;
if (!('vsSize' in $attrs) && 'vsSizeProperty' in $attrs) {
console.warn('vs-size-property attribute is deprecated. Please use vs-size attribute which also accepts angular expressions.');
}
if ($scrollParent.length === 0) {
throw 'Specified scroll parent selector did not match any element';
}
$scope.$scrollParent = $scrollParent;
if (sizesPropertyExists) {
$scope.sizesCumulative = [];
}
//initial defaults
$scope.elementSize = (+$attrs.vsRepeat) || getClientSize($scrollParent[0], clientSize) || 50;
$scope.offsetBefore = 0;
$scope.offsetAfter = 0;
$scope.excess = 2;
if ($$horizontal) {
$beforeContent.css('height', '100%');
$afterContent.css('height', '100%');
}
else {
$beforeContent.css('width', '100%');
$afterContent.css('width', '100%');
}
Object.keys(attributesDictionary).forEach(function(key) {
if ($attrs[key]) {
$attrs.$observe(key, function(value) {
// '+' serves for getting a number from the string as the attributes are always strings
$scope[attributesDictionary[key]] = +value;
reinitialize();
});
}
});
$scope.$watchCollection(rhs, function(coll) {
originalCollection = coll || [];
refresh();
});
function refresh() {
if (!originalCollection || originalCollection.length < 1) {
$scope[collectionName] = [];
originalLength = 0;
$scope.sizesCumulative = [0];
}
else {
originalLength = originalCollection.length;
if (sizesPropertyExists) {
$scope.sizes = originalCollection.map(function(item) {
var s = $scope.$new(false);
angular.extend(s, item);
s[lhs] = item;
var size = ($attrs.vsSize || $attrs.vsSizeProperty) ?
s.$eval($attrs.vsSize || $attrs.vsSizeProperty) :
$scope.elementSize;
s.$destroy();
return size;
});
var sum = 0;
$scope.sizesCumulative = $scope.sizes.map(function(size) {
var res = sum;
sum += size;
return res;
});
$scope.sizesCumulative.push(sum);
}
else {
setAutoSize();
}
}
reinitialize();
}
function setAutoSize() {
if (autoSize) {
$scope.$$postDigest(function() {
if (repeatContainer[0].offsetHeight || repeatContainer[0].offsetWidth) { // element is visible
var children = repeatContainer.children(),
i = 0,
gotSomething = false,
insideStartEndSequence = false;
while (i < children.length) {
if (children[i].attributes[originalNgRepeatAttr] != null || insideStartEndSequence) {
if (!gotSomething) {
$scope.elementSize = 0;
}
gotSomething = true;
if (children[i][offsetSize]) {
$scope.elementSize += children[i][offsetSize];
}
if (isNgRepeatStart) {
if (children[i].attributes['ng-repeat-end'] != null || children[i].attributes['data-ng-repeat-end'] != null) {
break;
}
else {
insideStartEndSequence = true;
}
}
else {
break;
}
}
i++;
}
if (gotSomething) {
reinitialize();
autoSize = false;
if ($scope.$root && !$scope.$root.$$phase) {
$scope.$apply();
}
}
}
else {
var dereg = $scope.$watch(function() {
if (repeatContainer[0].offsetHeight || repeatContainer[0].offsetWidth) {
dereg();
setAutoSize();
}
});
}
});
}
}
function getLayoutProp() {
var layoutPropPrefix = childTagName === 'tr' ? '' : 'min-';
var layoutProp = $$horizontal ? layoutPropPrefix + 'width' : layoutPropPrefix + 'height';
return layoutProp;
}
childClone.eq(0).attr(originalNgRepeatAttr, lhs + ' in ' + collectionName + (rhsSuffix ? ' ' + rhsSuffix : ''));
childClone.addClass('vs-repeat-repeated-element');
repeatContainer.append($beforeContent);
repeatContainer.append(childClone);
$compile(childClone)($scope);
repeatContainer.append($afterContent);
$scope.startIndex = 0;
$scope.endIndex = 0;
function scrollHandler() {
if (updateInnerCollection()) {
$scope.$digest();
}
}
$scrollParent.on('scroll', scrollHandler);
function onWindowResize() {
if (typeof $attrs.vsAutoresize !== 'undefined') {
autoSize = true;
setAutoSize();
if ($scope.$root && !$scope.$root.$$phase) {
$scope.$apply();
}
}
if (updateInnerCollection()) {
$scope.$apply();
}
}
angular.element(window).on('resize', onWindowResize);
$scope.$on('$destroy', function() {
angular.element(window).off('resize', onWindowResize);
$scrollParent.off('scroll', scrollHandler);
});
$scope.$on('vsRepeatTrigger', refresh);
$scope.$on('vsRepeatResize', function() {
autoSize = true;
setAutoSize();
});
var _prevStartIndex,
_prevEndIndex,
_minStartIndex,
_maxEndIndex;
$scope.$on('vsRenderAll', function() {//e , quantum) {
if($$options.latch) {
setTimeout(function() {
// var __endIndex = Math.min($scope.endIndex + (quantum || 1), originalLength);
var __endIndex = originalLength;
_maxEndIndex = Math.max(__endIndex, _maxEndIndex);
$scope.endIndex = $$options.latch ? _maxEndIndex : __endIndex;
$scope[collectionName] = originalCollection.slice($scope.startIndex, $scope.endIndex);
_prevEndIndex = $scope.endIndex;
$scope.$$postDigest(function() {
$beforeContent.css(getLayoutProp(), 0);
$afterContent.css(getLayoutProp(), 0);
});
$scope.$apply(function() {
$scope.$emit('vsRenderAllDone');
});
});
}
});
function reinitialize() {
_prevStartIndex = void 0;
_prevEndIndex = void 0;
_minStartIndex = originalLength;
_maxEndIndex = 0;
updateTotalSize(sizesPropertyExists ?
$scope.sizesCumulative[originalLength] :
$scope.elementSize * originalLength
);
updateInnerCollection();
$scope.$emit('vsRepeatReinitialized', $scope.startIndex, $scope.endIndex);
}
function updateTotalSize(size) {
$scope.totalSize = $scope.offsetBefore + size + $scope.offsetAfter;
}
var _prevClientSize;
function reinitOnClientHeightChange() {
var ch = getClientSize($scrollParent[0], clientSize);
if (ch !== _prevClientSize) {
reinitialize();
if ($scope.$root && !$scope.$root.$$phase) {
$scope.$apply();
}
}
_prevClientSize = ch;
}
$scope.$watch(function() {
if (typeof window.requestAnimationFrame === 'function') {
window.requestAnimationFrame(reinitOnClientHeightChange);
}
else {
reinitOnClientHeightChange();
}
});
function updateInnerCollection() {
var $scrollPosition = getScrollPos($scrollParent[0], scrollPos);
var $clientSize = getClientSize($scrollParent[0], clientSize);
var scrollOffset = repeatContainer[0] === $scrollParent[0] ? 0 : getScrollOffset(
repeatContainer[0],
$scrollParent[0],
$$horizontal
);
var __startIndex = $scope.startIndex;
var __endIndex = $scope.endIndex;
if (sizesPropertyExists) {
__startIndex = 0;
while ($scope.sizesCumulative[__startIndex] < $scrollPosition - $scope.offsetBefore - scrollOffset) {
__startIndex++;
}
if (__startIndex > 0) { __startIndex--; }
// Adjust the start index according to the excess
__startIndex = Math.max(
Math.floor(__startIndex - $scope.excess / 2),
0
);
__endIndex = __startIndex;
while ($scope.sizesCumulative[__endIndex] < $scrollPosition - $scope.offsetBefore - scrollOffset + $clientSize) {
__endIndex++;
}
// Adjust the end index according to the excess
__endIndex = Math.min(
Math.ceil(__endIndex + $scope.excess / 2),
originalLength
);
}
else {
__startIndex = Math.max(
Math.floor(
($scrollPosition - $scope.offsetBefore - scrollOffset) / $scope.elementSize
) - $scope.excess / 2,
0
);
__endIndex = Math.min(
__startIndex + Math.ceil(
$clientSize / $scope.elementSize
) + $scope.excess,
originalLength
);
}
_minStartIndex = Math.min(__startIndex, _minStartIndex);
_maxEndIndex = Math.max(__endIndex, _maxEndIndex);
$scope.startIndex = $$options.latch ? _minStartIndex : __startIndex;
$scope.endIndex = $$options.latch ? _maxEndIndex : __endIndex;
// Move to the end of the collection if we are now past it
if (_maxEndIndex < $scope.startIndex)
$scope.startIndex = _maxEndIndex;
var digestRequired = false;
if (_prevStartIndex == null) {
digestRequired = true;
}
else if (_prevEndIndex == null) {
digestRequired = true;
}
if (!digestRequired) {
if ($$options.hunked) {
if (Math.abs($scope.startIndex - _prevStartIndex) >= $scope.excess / 2 ||
($scope.startIndex === 0 && _prevStartIndex !== 0)) {
digestRequired = true;
}
else if (Math.abs($scope.endIndex - _prevEndIndex) >= $scope.excess / 2 ||
($scope.endIndex === originalLength && _prevEndIndex !== originalLength)) {
digestRequired = true;
}
}
else {
digestRequired = $scope.startIndex !== _prevStartIndex ||
$scope.endIndex !== _prevEndIndex;
}
}
if (digestRequired) {
$scope[collectionName] = originalCollection.slice($scope.startIndex, $scope.endIndex);
// Emit the event
$scope.$emit('vsRepeatInnerCollectionUpdated', $scope.startIndex, $scope.endIndex, _prevStartIndex, _prevEndIndex);
var triggerIndex;
if ($attrs.vsScrolledToEnd) {
triggerIndex = originalCollection.length - ($scope.scrolledToEndOffset || 0);
if (($scope.endIndex >= triggerIndex && _prevEndIndex < triggerIndex) || (originalCollection.length && $scope.endIndex === originalCollection.length)) {
$scope.$eval($attrs.vsScrolledToEnd);
}
}
if ($attrs.vsScrolledToBeginning) {
triggerIndex = $scope.scrolledToBeginningOffset || 0;
if (($scope.startIndex <= triggerIndex && _prevStartIndex > $scope.startIndex)) {
$scope.$eval($attrs.vsScrolledToBeginning);
}
}
_prevStartIndex = $scope.startIndex;
_prevEndIndex = $scope.endIndex;
var offsetCalculationString = sizesPropertyExists ?
'(sizesCumulative[$index + startIndex] + offsetBefore)' :
'(($index + startIndex) * elementSize + offsetBefore)';
var parsed = $parse(offsetCalculationString);
var o1 = parsed($scope, {$index: 0});
var o2 = parsed($scope, {$index: $scope[collectionName].length});
var total = $scope.totalSize;
$beforeContent.css(getLayoutProp(), o1 + 'px');
$afterContent.css(getLayoutProp(), (total - o2) + 'px');
}
return digestRequired;
}
}
};
}
};
}]);
if (typeof module !== 'undefined' && module.exports) {
module.exports = vsRepeatModule.name;
}
})(window, window.angular);
;