<commit_before>//used for the media picker dialog
angular.module("umbraco")
    .controller("Umbraco.Overlays.MediaPickerController",
    function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, mediaTypeHelper, eventsService, treeService, $element, $timeout, userService, $cookies, localStorageService, localizationService) {

            if (!$scope.model.title) {
                $scope.model.title = localizationService.localize("defaultdialogs_selectMedia");
            }

            var dialogOptions = $scope.model;

            $scope.disableFolderSelect = dialogOptions.disableFolderSelect;
            $scope.onlyImages = dialogOptions.onlyImages;
            $scope.showDetails = dialogOptions.showDetails;
            $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false;
            $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1;
            $scope.cropSize = dialogOptions.cropSize;
            $scope.lastOpenedNode = localStorageService.get("umbLastOpenedMediaNodeId");
            $scope.lockedFolder = true;

            var userStartNodes = [];

            var umbracoSettings = Umbraco.Sys.ServerVariables.umbracoSettings;
            var allowedUploadFiles = mediaHelper.formatFileTypes(umbracoSettings.allowedUploadFiles);
            if ($scope.onlyImages) {
                $scope.acceptedFileTypes = mediaHelper.formatFileTypes(umbracoSettings.imageFileTypes);
            } else {
                // Use whitelist of allowed file types if provided
                if (allowedUploadFiles !== '') {
                    $scope.acceptedFileTypes = allowedUploadFiles;
                } else {
                    // If no whitelist, we pass in a blacklist by adding ! to the file extensions, allowing everything EXCEPT for disallowedUploadFiles
                    $scope.acceptedFileTypes = !mediaHelper.formatFileTypes(umbracoSettings.disallowedUploadFiles);
                }
            }

            $scope.maxFileSize = umbracoSettings.maxFileSize + "KB";

            $scope.model.selectedImages = [];

            $scope.acceptedMediatypes = [];
            mediaTypeHelper.getAllowedImagetypes($scope.startNodeId)
                .then(function(types) {
                    $scope.acceptedMediatypes = types;
                });

            $scope.searchOptions = {
                pageNumber: 1,
                pageSize: 100,
                totalItems: 0,
                totalPages: 0,
                filter: '',
                dataTypeId: $scope.model.dataTypeId
            };

            //preload selected item
            $scope.target = undefined;
            if (dialogOptions.currentTarget) {
                $scope.target = dialogOptions.currentTarget;
            }

            function onInit() {
                userService.getCurrentUser().then(function (userData) {
                    userStartNodes = userData.startMediaIds;

                    if ($scope.startNodeId !== -1) {
                        entityResource.getById($scope.startNodeId, "media")
                            .then(function (ent) {
                                $scope.startNodeId = ent.id;
                                run();
                            });
                    } else {
                        run();
                    }
                });
            }

            function run() {
                //default root item
                if (!$scope.target) {
                    if ($scope.lastOpenedNode && $scope.lastOpenedNode !== -1) {
                        entityResource.getById($scope.lastOpenedNode, "media")
                            .then(ensureWithinStartNode, gotoStartNode);
                    } else {
                        gotoStartNode();
                    }
                } else {
                    //if a target is specified, go look it up - generally this target will just contain ids not the actual full
                    //media object so we need to look it up
                    var id = $scope.target.udi ? $scope.target.udi : $scope.target.id
                    var altText = $scope.target.altText;
                    if (id) {
                        entityResource.getById(id, "Media")
                            .then(function (node) {
                                $scope.target = node;
                                if (ensureWithinStartNode(node)) {
                                    selectImage(node);
                                    $scope.target.url = mediaHelper.resolveFile(node);
                                    $scope.target.altText = altText;
                                    $scope.openDetailsDialog();
                                }
                            },
                                gotoStartNode);
                    } else {
                        gotoStartNode();
                    }
                }
            }

            $scope.upload = function(v) {
                angular.element(".umb-file-dropzone-directive .file-select").click();
            };

            $scope.dragLeave = function(el, event) {
                $scope.activeDrag = false;
            };

            $scope.dragEnter = function(el, event) {
                $scope.activeDrag = true;
            };

            $scope.submitFolder = function() {
                if ($scope.newFolderName) {
                    $scope.creatingFolder = true;
                    mediaResource
                        .addFolder($scope.newFolderName, $scope.currentFolder.id)
                        .then(function(data) {
                            //we've added a new folder so lets clear the tree cache for that specific item
                            treeService.clearCache({
                                cacheKey: "__media", //this is the main media tree cache key
                                childrenOf: data.parentId //clear the children of the parent
                            });
                            $scope.creatingFolder = false;
                            $scope.gotoFolder(data);
                            $scope.showFolderInput = false;
                            $scope.newFolderName = "";
                        });
                } else {
                    $scope.showFolderInput = false;
                }
            };

            $scope.enterSubmitFolder = function(event) {
                if (event.keyCode === 13) {
                    $scope.submitFolder();
                    event.stopPropagation();
                }
            };

            $scope.gotoFolder = function(folder) {
                if (!$scope.multiPicker) {
                    deselectAllImages($scope.model.selectedImages);
                }

                if (!folder) {
                    folder = { id: -1, name: "Media", icon: "icon-folder" };
                }

                if (folder.id > 0) {
                    entityResource.getAncestors(folder.id, "media", { dataTypeId: $scope.model.dataTypeId })
                        .then(function(anc) {
                            $scope.path = _.filter(anc,
                                function(f) {
                                    return f.path.indexOf($scope.startNodeId) !== -1;
                                });
                        });

                } else {
                    $scope.path = [];
                }

                mediaTypeHelper.getAllowedImagetypes(folder.id)
                    .then(function (types) {
                        $scope.acceptedMediatypes = types;
                    });

                $scope.lockedFolder = (folder.id === -1 && $scope.model.startNodeIsVirtual) || hasFolderAccess(folder) === false;

                $scope.currentFolder = folder;
                localStorageService.set("umbLastOpenedMediaNodeId", folder.id);
                return getChildren(folder.id);
            };

            $scope.clickHandler = function(image, event, index) {
                if (image.isFolder) {
                    if ($scope.disableFolderSelect) {
                        $scope.gotoFolder(image);
                    } else {
                        eventsService.emit("dialogs.mediaPicker.select", image);
                        selectImage(image);
                    }
                } else {
                    eventsService.emit("dialogs.mediaPicker.select", image);
                    if ($scope.showDetails) {

                        $scope.target = image;

                        // handle both entity and full media object
                        if (image.image) {
                            $scope.target.url = image.image;
                        } else {
                            $scope.target.url = mediaHelper.resolveFile(image);
                        }

                        $scope.openDetailsDialog();
                    } else {
                        selectImage(image);
                    }
                }
            };

            $scope.clickItemName = function(item) {
                if (item.isFolder) {
                    $scope.gotoFolder(item);
                }
            };

            function selectImage(image) {
                if (image.selected) {
                    for (var i = 0; $scope.model.selectedImages.length > i; i++) {
                        var imageInSelection = $scope.model.selectedImages[i];
                        if (image.key === imageInSelection.key) {
                            image.selected = false;
                            $scope.model.selectedImages.splice(i, 1);
                        }
                    }
                } else {
                    if (!$scope.multiPicker) {
                        deselectAllImages($scope.model.selectedImages);
                    }
                    image.selected = true;
                    $scope.model.selectedImages.push(image);
                }
            }

            function deselectAllImages(images) {
                for (var i = 0; i < images.length; i++) {
                    var image = images[i];
                    image.selected = false;
                }
                images.length = 0;
            }

            $scope.onUploadComplete = function(files) {
                $scope.gotoFolder($scope.currentFolder).then(function() {
                    if (files.length === 1 && $scope.model.selectedImages.length === 0) {
                        var image = $scope.images[$scope.images.length - 1];
                        $scope.target = image;
                        $scope.target.url = mediaHelper.resolveFile(image);
                        selectImage(image);
                    }
                });
            };

            $scope.onFilesQueue = function() {
                $scope.activeDrag = false;
            };

            function ensureWithinStartNode(node) {
                // make sure that last opened node is on the same path as start node
                var nodePath = node.path.split(",");

                // also make sure the node is not trashed
                if (nodePath.indexOf($scope.startNodeId.toString()) !== -1 && node.trashed === false) {
                    $scope.gotoFolder({ id: $scope.lastOpenedNode, name: "Media", icon: "icon-folder" });
                    return true;
                } else {
                    $scope.gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" });
                    return false;
                }
            }

            function hasFolderAccess(node) {
                var nodePath = node.path ? node.path.split(',') : [node.id];

                for (var i = 0; i < nodePath.length; i++) {
                    if (userStartNodes.indexOf(parseInt(nodePath[i])) !== -1)
                        return true;
                }

                return false;
            }

            function gotoStartNode(err) {
                $scope.gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" });
            }

            $scope.openDetailsDialog = function() {

                $scope.mediaPickerDetailsOverlay = {};
                $scope.mediaPickerDetailsOverlay.show = true;

                $scope.mediaPickerDetailsOverlay.submit = function(model) {
                    $scope.model.selectedImages.push($scope.target);
                    $scope.model.submit($scope.model);

                    $scope.mediaPickerDetailsOverlay.show = false;
                    $scope.mediaPickerDetailsOverlay = null;
                };

                $scope.mediaPickerDetailsOverlay.close = function(oldModel) {
                    $scope.mediaPickerDetailsOverlay.show = false;
                    $scope.mediaPickerDetailsOverlay = null;
                };
            };

            var debounceSearchMedia = _.debounce(function() {
                    $scope.$apply(function() {
                        if ($scope.searchOptions.filter) {
                            searchMedia();
                        } else {
                            // reset pagination
                            $scope.searchOptions = {
                                pageNumber: 1,
                                pageSize: 100,
                                totalItems: 0,
                                totalPages: 0,
                                filter: '',
                                dataTypeId: $scope.model.dataTypeId
                            };
                            getChildren($scope.currentFolder.id);
                        }
                    });
                }, 500);

            $scope.changeSearch = function() {
                $scope.loading = true;
                debounceSearchMedia();
            };

            $scope.toggle = function() {
                // Make sure to activate the changeSearch function everytime the toggle is clicked
                $scope.changeSearch();
            }

            $scope.changePagination = function(pageNumber) {
                $scope.loading = true;
                $scope.searchOptions.pageNumber = pageNumber;
                searchMedia();
            };

            function searchMedia() {
                $scope.loading = true;
                entityResource.getPagedDescendants($scope.currentFolder.id, "Media", $scope.searchOptions)
                    .then(function(data) {
                        // update image data to work with image grid
                        angular.forEach(data.items,
                            function(mediaItem) {
                                // set thumbnail and src
                                mediaItem.thumbnail = mediaHelper.resolveFileFromEntity(mediaItem, true);
                                mediaItem.image = mediaHelper.resolveFileFromEntity(mediaItem, false);
                                // set properties to match a media object
                                mediaItem.properties = [];
                                if (mediaItem.metaData) {
                                    if (mediaItem.metaData.umbracoWidth && mediaItem.metaData.umbracoHeight) {
                                        mediaItem.properties.push({
                                            alias: "umbracoWidth",
                                            value: mediaItem.metaData.umbracoWidth.Value
                                        });
                                        mediaItem.properties.push({
                                            alias: "umbracoHeight",
                                            value: mediaItem.metaData.umbracoHeight.Value
                                        });
                                    }
                                    if (mediaItem.metaData.umbracoFile) {
                                        mediaItem.properties.push({
                                            alias: "umbracoFile",
                                            editor: mediaItem.metaData.umbracoFile.PropertyEditorAlias,
                                            value: mediaItem.metaData.umbracoFile.Value
                                        });
                                    }
                                }
                            });
                        // update images
                        $scope.images = data.items ? data.items : [];
                        // update pagination
                        if (data.pageNumber > 0)
                            $scope.searchOptions.pageNumber = data.pageNumber;
                        if (data.pageSize > 0)
                            $scope.searchOptions.pageSize = data.pageSize;
                        $scope.searchOptions.totalItems = data.totalItems;
                        $scope.searchOptions.totalPages = data.totalPages;
                        // set already selected images to selected
                        preSelectImages();
                        $scope.loading = false;
                    });
            }

            function getChildren(id) {
                $scope.loading = true;
                return entityResource.getChildren(id, "Media", $scope.searchOptions)
                    .then(function(data) {

                        for (i=0;i<data.length;i++){
                            if(data[i].metaData.MediaPath !== null){
                                data[i].thumbnail = mediaHelper.resolveFileFromEntity(data[i], true);
                                data[i].image = mediaHelper.resolveFileFromEntity(data[i], false);
                            }
                        }
                        $scope.searchOptions.filter = "";
                        $scope.images = data ? data : [];
                        // set already selected images to selected
                        preSelectImages();
                        $scope.loading = false;
                    });
            }

            function preSelectImages() {
                for (var folderImageIndex = 0; folderImageIndex < $scope.images.length; folderImageIndex++) {
                    var folderImage = $scope.images[folderImageIndex];
                    var imageIsSelected = false;

                    if ($scope.model && angular.isArray($scope.model.selectedImages)) {
                        for (var selectedImageIndex = 0;
                            selectedImageIndex < $scope.model.selectedImages.length;
                            selectedImageIndex++) {
                            var selectedImage = $scope.model.selectedImages[selectedImageIndex];

                            if (folderImage.key === selectedImage.key) {
                                imageIsSelected = true;
                            }
                        }
                    }

                    if (imageIsSelected) {
                        folderImage.selected = true;
                    }
                }
            }

            onInit();

        });
<commit_msg>fixes missing 'var'<commit_after>//used for the media picker dialog
angular.module("umbraco")
    .controller("Umbraco.Overlays.MediaPickerController",
        function ($scope, mediaResource, umbRequestHelper, entityResource, $log, mediaHelper, mediaTypeHelper, eventsService, treeService, $element, $timeout, userService, $cookies, localStorageService, localizationService) {

            if (!$scope.model.title) {
                $scope.model.title = localizationService.localize("defaultdialogs_selectMedia");
            }

            var dialogOptions = $scope.model;

            $scope.disableFolderSelect = dialogOptions.disableFolderSelect;
            $scope.onlyImages = dialogOptions.onlyImages;
            $scope.showDetails = dialogOptions.showDetails;
            $scope.multiPicker = (dialogOptions.multiPicker && dialogOptions.multiPicker !== "0") ? true : false;
            $scope.startNodeId = dialogOptions.startNodeId ? dialogOptions.startNodeId : -1;
            $scope.cropSize = dialogOptions.cropSize;
            $scope.lastOpenedNode = localStorageService.get("umbLastOpenedMediaNodeId");
            $scope.lockedFolder = true;

            var userStartNodes = [];

            var umbracoSettings = Umbraco.Sys.ServerVariables.umbracoSettings;
            var allowedUploadFiles = mediaHelper.formatFileTypes(umbracoSettings.allowedUploadFiles);
            if ($scope.onlyImages) {
                $scope.acceptedFileTypes = mediaHelper.formatFileTypes(umbracoSettings.imageFileTypes);
            } else {
                // Use whitelist of allowed file types if provided
                if (allowedUploadFiles !== '') {
                    $scope.acceptedFileTypes = allowedUploadFiles;
                } else {
                    // If no whitelist, we pass in a blacklist by adding ! to the file extensions, allowing everything EXCEPT for disallowedUploadFiles
                    $scope.acceptedFileTypes = !mediaHelper.formatFileTypes(umbracoSettings.disallowedUploadFiles);
                }
            }

            $scope.maxFileSize = umbracoSettings.maxFileSize + "KB";

            $scope.model.selectedImages = [];

            $scope.acceptedMediatypes = [];
            mediaTypeHelper.getAllowedImagetypes($scope.startNodeId)
                .then(function (types) {
                    $scope.acceptedMediatypes = types;
                });

            $scope.searchOptions = {
                pageNumber: 1,
                pageSize: 100,
                totalItems: 0,
                totalPages: 0,
                filter: '',
                dataTypeId: $scope.model.dataTypeId
            };

            //preload selected item
            $scope.target = undefined;
            if (dialogOptions.currentTarget) {
                $scope.target = dialogOptions.currentTarget;
            }

            function onInit() {
                userService.getCurrentUser().then(function (userData) {
                    userStartNodes = userData.startMediaIds;

                    if ($scope.startNodeId !== -1) {
                        entityResource.getById($scope.startNodeId, "media")
                            .then(function (ent) {
                                $scope.startNodeId = ent.id;
                                run();
                            });
                    } else {
                        run();
                    }
                });
            }

            function run() {
                //default root item
                if (!$scope.target) {
                    if ($scope.lastOpenedNode && $scope.lastOpenedNode !== -1) {
                        entityResource.getById($scope.lastOpenedNode, "media")
                            .then(ensureWithinStartNode, gotoStartNode);
                    } else {
                        gotoStartNode();
                    }
                } else {
                    //if a target is specified, go look it up - generally this target will just contain ids not the actual full
                    //media object so we need to look it up
                    var id = $scope.target.udi ? $scope.target.udi : $scope.target.id
                    var altText = $scope.target.altText;
                    if (id) {
                        entityResource.getById(id, "Media")
                            .then(function (node) {
                                $scope.target = node;
                                if (ensureWithinStartNode(node)) {
                                    selectImage(node);
                                    $scope.target.url = mediaHelper.resolveFile(node);
                                    $scope.target.altText = altText;
                                    $scope.openDetailsDialog();
                                }
                            },
                                gotoStartNode);
                    } else {
                        gotoStartNode();
                    }
                }
            }

            $scope.upload = function (v) {
                angular.element(".umb-file-dropzone-directive .file-select").click();
            };

            $scope.dragLeave = function (el, event) {
                $scope.activeDrag = false;
            };

            $scope.dragEnter = function (el, event) {
                $scope.activeDrag = true;
            };

            $scope.submitFolder = function () {
                if ($scope.newFolderName) {
                    $scope.creatingFolder = true;
                    mediaResource
                        .addFolder($scope.newFolderName, $scope.currentFolder.id)
                        .then(function (data) {
                            //we've added a new folder so lets clear the tree cache for that specific item
                            treeService.clearCache({
                                cacheKey: "__media", //this is the main media tree cache key
                                childrenOf: data.parentId //clear the children of the parent
                            });
                            $scope.creatingFolder = false;
                            $scope.gotoFolder(data);
                            $scope.showFolderInput = false;
                            $scope.newFolderName = "";
                        });
                } else {
                    $scope.showFolderInput = false;
                }
            };

            $scope.enterSubmitFolder = function (event) {
                if (event.keyCode === 13) {
                    $scope.submitFolder();
                    event.stopPropagation();
                }
            };

            $scope.gotoFolder = function (folder) {
                if (!$scope.multiPicker) {
                    deselectAllImages($scope.model.selectedImages);
                }

                if (!folder) {
                    folder = { id: -1, name: "Media", icon: "icon-folder" };
                }

                if (folder.id > 0) {
                    entityResource.getAncestors(folder.id, "media", { dataTypeId: $scope.model.dataTypeId })
                        .then(function (anc) {
                            $scope.path = _.filter(anc,
                                function (f) {
                                    return f.path.indexOf($scope.startNodeId) !== -1;
                                });
                        });

                } else {
                    $scope.path = [];
                }

                mediaTypeHelper.getAllowedImagetypes(folder.id)
                    .then(function (types) {
                        $scope.acceptedMediatypes = types;
                    });

                $scope.lockedFolder = (folder.id === -1 && $scope.model.startNodeIsVirtual) || hasFolderAccess(folder) === false;

                $scope.currentFolder = folder;
                localStorageService.set("umbLastOpenedMediaNodeId", folder.id);
                return getChildren(folder.id);
            };

            $scope.clickHandler = function (image, event, index) {
                if (image.isFolder) {
                    if ($scope.disableFolderSelect) {
                        $scope.gotoFolder(image);
                    } else {
                        eventsService.emit("dialogs.mediaPicker.select", image);
                        selectImage(image);
                    }
                } else {
                    eventsService.emit("dialogs.mediaPicker.select", image);
                    if ($scope.showDetails) {

                        $scope.target = image;

                        // handle both entity and full media object
                        if (image.image) {
                            $scope.target.url = image.image;
                        } else {
                            $scope.target.url = mediaHelper.resolveFile(image);
                        }

                        $scope.openDetailsDialog();
                    } else {
                        selectImage(image);
                    }
                }
            };

            $scope.clickItemName = function (item) {
                if (item.isFolder) {
                    $scope.gotoFolder(item);
                }
            };

            function selectImage(image) {
                if (image.selected) {
                    for (var i = 0; $scope.model.selectedImages.length > i; i++) {
                        var imageInSelection = $scope.model.selectedImages[i];
                        if (image.key === imageInSelection.key) {
                            image.selected = false;
                            $scope.model.selectedImages.splice(i, 1);
                        }
                    }
                } else {
                    if (!$scope.multiPicker) {
                        deselectAllImages($scope.model.selectedImages);
                    }
                    image.selected = true;
                    $scope.model.selectedImages.push(image);
                }
            }

            function deselectAllImages(images) {
                for (var i = 0; i < images.length; i++) {
                    var image = images[i];
                    image.selected = false;
                }
                images.length = 0;
            }

            $scope.onUploadComplete = function (files) {
                $scope.gotoFolder($scope.currentFolder).then(function () {
                    if (files.length === 1 && $scope.model.selectedImages.length === 0) {
                        var image = $scope.images[$scope.images.length - 1];
                        $scope.target = image;
                        $scope.target.url = mediaHelper.resolveFile(image);
                        selectImage(image);
                    }
                });
            };

            $scope.onFilesQueue = function () {
                $scope.activeDrag = false;
            };

            function ensureWithinStartNode(node) {
                // make sure that last opened node is on the same path as start node
                var nodePath = node.path.split(",");

                // also make sure the node is not trashed
                if (nodePath.indexOf($scope.startNodeId.toString()) !== -1 && node.trashed === false) {
                    $scope.gotoFolder({ id: $scope.lastOpenedNode, name: "Media", icon: "icon-folder" });
                    return true;
                } else {
                    $scope.gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" });
                    return false;
                }
            }

            function hasFolderAccess(node) {
                var nodePath = node.path ? node.path.split(',') : [node.id];

                for (var i = 0; i < nodePath.length; i++) {
                    if (userStartNodes.indexOf(parseInt(nodePath[i])) !== -1)
                        return true;
                }

                return false;
            }

            function gotoStartNode(err) {
                $scope.gotoFolder({ id: $scope.startNodeId, name: "Media", icon: "icon-folder" });
            }

            $scope.openDetailsDialog = function () {

                $scope.mediaPickerDetailsOverlay = {};
                $scope.mediaPickerDetailsOverlay.show = true;

                $scope.mediaPickerDetailsOverlay.submit = function (model) {
                    $scope.model.selectedImages.push($scope.target);
                    $scope.model.submit($scope.model);

                    $scope.mediaPickerDetailsOverlay.show = false;
                    $scope.mediaPickerDetailsOverlay = null;
                };

                $scope.mediaPickerDetailsOverlay.close = function (oldModel) {
                    $scope.mediaPickerDetailsOverlay.show = false;
                    $scope.mediaPickerDetailsOverlay = null;
                };
            };

            var debounceSearchMedia = _.debounce(function () {
                $scope.$apply(function () {
                    if ($scope.searchOptions.filter) {
                        searchMedia();
                    } else {
                        // reset pagination
                        $scope.searchOptions = {
                            pageNumber: 1,
                            pageSize: 100,
                            totalItems: 0,
                            totalPages: 0,
                            filter: '',
                            dataTypeId: $scope.model.dataTypeId
                        };
                        getChildren($scope.currentFolder.id);
                    }
                });
            }, 500);

            $scope.changeSearch = function () {
                $scope.loading = true;
                debounceSearchMedia();
            };

            $scope.toggle = function () {
                // Make sure to activate the changeSearch function everytime the toggle is clicked
                $scope.changeSearch();
            }

            $scope.changePagination = function (pageNumber) {
                $scope.loading = true;
                $scope.searchOptions.pageNumber = pageNumber;
                searchMedia();
            };

            function searchMedia() {
                $scope.loading = true;
                entityResource.getPagedDescendants($scope.currentFolder.id, "Media", $scope.searchOptions)
                    .then(function (data) {
                        // update image data to work with image grid
                        angular.forEach(data.items,
                            function (mediaItem) {
                                // set thumbnail and src
                                mediaItem.thumbnail = mediaHelper.resolveFileFromEntity(mediaItem, true);
                                mediaItem.image = mediaHelper.resolveFileFromEntity(mediaItem, false);
                                // set properties to match a media object
                                mediaItem.properties = [];
                                if (mediaItem.metaData) {
                                    if (mediaItem.metaData.umbracoWidth && mediaItem.metaData.umbracoHeight) {
                                        mediaItem.properties.push({
                                            alias: "umbracoWidth",
                                            value: mediaItem.metaData.umbracoWidth.Value
                                        });
                                        mediaItem.properties.push({
                                            alias: "umbracoHeight",
                                            value: mediaItem.metaData.umbracoHeight.Value
                                        });
                                    }
                                    if (mediaItem.metaData.umbracoFile) {
                                        mediaItem.properties.push({
                                            alias: "umbracoFile",
                                            editor: mediaItem.metaData.umbracoFile.PropertyEditorAlias,
                                            value: mediaItem.metaData.umbracoFile.Value
                                        });
                                    }
                                }
                            });
                        // update images
                        $scope.images = data.items ? data.items : [];
                        // update pagination
                        if (data.pageNumber > 0)
                            $scope.searchOptions.pageNumber = data.pageNumber;
                        if (data.pageSize > 0)
                            $scope.searchOptions.pageSize = data.pageSize;
                        $scope.searchOptions.totalItems = data.totalItems;
                        $scope.searchOptions.totalPages = data.totalPages;
                        // set already selected images to selected
                        preSelectImages();
                        $scope.loading = false;
                    });
            }

            function getChildren(id) {
                $scope.loading = true;
                return entityResource.getChildren(id, "Media", $scope.searchOptions)
                    .then(function (data) {

                        for (var i = 0; i < data.length; i++) {
                            if (data[i].metaData.MediaPath !== null) {
                                data[i].thumbnail = mediaHelper.resolveFileFromEntity(data[i], true);
                                data[i].image = mediaHelper.resolveFileFromEntity(data[i], false);
                            }
                        }
                        $scope.searchOptions.filter = "";
                        $scope.images = data ? data : [];
                        // set already selected images to selected
                        preSelectImages();
                        $scope.loading = false;
                    });
            }

            function preSelectImages() {
                for (var folderImageIndex = 0; folderImageIndex < $scope.images.length; folderImageIndex++) {
                    var folderImage = $scope.images[folderImageIndex];
                    var imageIsSelected = false;

                    if ($scope.model && angular.isArray($scope.model.selectedImages)) {
                        for (var selectedImageIndex = 0;
                            selectedImageIndex < $scope.model.selectedImages.length;
                            selectedImageIndex++) {
                            var selectedImage = $scope.model.selectedImages[selectedImageIndex];

                            if (folderImage.key === selectedImage.key) {
                                imageIsSelected = true;
                            }
                        }
                    }

                    if (imageIsSelected) {
                        folderImage.selected = true;
                    }
                }
            }

            onInit();

        });
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react'
import { Input, Button, Col, Row, Well, FormGroup, ControlLabel, FormControl } from 'react-bootstrap'

type Props = {
  saveValues: PropTypes.func,
  nextStep: PropTypes.func,
  previousStep: PropTypes.func,
  formReset: PropTypes.func,
  survey: PropTypes.object,
  mapClickHandler: PropTypes.func
}

class CitizenSurveyLocation extends React.Component {
  props: Props;
  constructor (props) {
    super(props)
    this.nextStep = this.nextStep.bind(this)
    this.previousStep = this.previousStep.bind(this)
    this.onChange = this.onChange.bind(this)
  }
  previousStep (e) {
    e.preventDefault()
    this.props.formReset()
  }
  nextStep (e) {
    this.onChange()
    this.props.nextStep()
  }
  onChange (e) {
    let data = {
      // geoCoordinates: [this.refs.lon.props.value, this.refs.lat.props.value]
      geoCoordinates: [this.refs.lon.getValue(), this.refs.lat.getValue()]
    }
    this.props.saveValues(data)
  }

  render () {
    const { survey } = this.props
    return (

Citizen Survey - Survey Location

        <Well>

            Begin a Citizen Survey by clicking the map to select a location.

            This could be the location the survey was taken, or the household location of the respondent.
            Additionally, the Latitude and Longitude can be entered directly if known.

        </Well>

        <Row>
          <Col md={6}>
            {/*<FormGroup controlId='lat'>
              <ControlLabel>Latitude</ControlLabel>
              <FormControl
                ref='lat'
                type='number'
                value={survey && survey.geoCoordinates ? survey.geoCoordinates[1] : ''}
                step='.00001'
                placeholder='Enter Latitude'
                onChange={this.onChange}
              />
            </FormGroup>*/}
            <Input type='text' ref='lat'
              label='Latitude'
              placeholder='Enter Latitude'
              value={survey && survey.geoCoordinates ? survey.geoCoordinates[1] : ''}
              onChange={this.onChange}
              />
          </Col>
          <Col md={6}>
            {/*<FormGroup controlId='lon'>
              <ControlLabel>Longitude</ControlLabel>
              <FormControl
                ref='lon'
                type='number'
                value={survey && survey.geoCoordinates ? survey.geoCoordinates[0] : ''}
                step='.00001'
                placeholder='Enter Longitude'
                onChange={this.onChange}
              />
            </FormGroup>*/}
            <Input type='text' ref='lon'
              label='Longitude'
              placeholder='Enter Longitude'
              value={survey && survey.geoCoordinates ? survey.geoCoordinates[0] : ''}
              onChange={this.onChange}
              />
          </Col>
        </Row>

        <Row>
          <Col xs={6} sm={6} md={6}>
            <Button bsStyle='info' onClick={this.previousStep} block>
               Start Over
            </Button>
          </Col>
          <Col xs={6} sm={6} md={6} >
            <Button bsStyle='success' onClick={this.nextStep} block>
              Continue
            </Button>
          </Col>
        </Row>

    )
  }

  componentDidMount () {
    console.log('im the survey location did mount')
    this.props.mapClickHandler('surveyLocation', {saveValues: this.props.saveValues})
  }
  componentWillReceiveProps (np) {
    console.log('im the survey location will receive props')
    if (np.activeInput === 'Survey' && np.inputOpened) {
      this.props.mapClickHandler('surveyLocation', {saveValues: this.props.saveValues})
    } else if (!np.inputOpened) {
      if (typeof np.map.getLayer('point') !== 'undefined') np.map.removeLayer('point')
      this.props.mapClickHandler('featureSelection')
    }
  }
  componentWillUnmount () {
    this.props.mapClickHandler('featureSelection')
  }
}

export default CitizenSurveyLocation
<commit_msg>remove console.log statements from survey locations<commit_after>import React, { PropTypes } from 'react'
import { Input, Button, Col, Row, Well, FormGroup, ControlLabel, FormControl } from 'react-bootstrap'

type Props = {
  saveValues: PropTypes.func,
  nextStep: PropTypes.func,
  previousStep: PropTypes.func,
  formReset: PropTypes.func,
  survey: PropTypes.object,
  mapClickHandler: PropTypes.func
}

class CitizenSurveyLocation extends React.Component {
  props: Props;
  constructor (props) {
    super(props)
    this.nextStep = this.nextStep.bind(this)
    this.previousStep = this.previousStep.bind(this)
    this.onChange = this.onChange.bind(this)
  }
  previousStep (e) {
    e.preventDefault()
    this.props.formReset()
  }
  nextStep (e) {
    this.onChange()
    this.props.nextStep()
  }
  onChange (e) {
    let data = {
      // geoCoordinates: [this.refs.lon.props.value, this.refs.lat.props.value]
      geoCoordinates: [this.refs.lon.getValue(), this.refs.lat.getValue()]
    }
    this.props.saveValues(data)
  }

  render () {
    const { survey } = this.props
    return (

Citizen Survey - Survey Location

        <Well>

            Begin a Citizen Survey by clicking the map to select a location.

            This could be the location the survey was taken, or the household location of the respondent.
            Additionally, the Latitude and Longitude can be entered directly if known.

        </Well>

        <Row>
          <Col md={6}>
            {/*<FormGroup controlId='lat'>
              <ControlLabel>Latitude</ControlLabel>
              <FormControl
                ref='lat'
                type='number'
                value={survey && survey.geoCoordinates ? survey.geoCoordinates[1] : ''}
                step='.00001'
                placeholder='Enter Latitude'
                onChange={this.onChange}
              />
            </FormGroup>*/}
            <Input type='text' ref='lat'
              label='Latitude'
              placeholder='Enter Latitude'
              value={survey && survey.geoCoordinates ? survey.geoCoordinates[1] : ''}
              onChange={this.onChange}
              />
          </Col>
          <Col md={6}>
            {/*<FormGroup controlId='lon'>
              <ControlLabel>Longitude</ControlLabel>
              <FormControl
                ref='lon'
                type='number'
                value={survey && survey.geoCoordinates ? survey.geoCoordinates[0] : ''}
                step='.00001'
                placeholder='Enter Longitude'
                onChange={this.onChange}
              />
            </FormGroup>*/}
            <Input type='text' ref='lon'
              label='Longitude'
              placeholder='Enter Longitude'
              value={survey && survey.geoCoordinates ? survey.geoCoordinates[0] : ''}
              onChange={this.onChange}
              />
          </Col>
        </Row>

        <Row>
          <Col xs={6} sm={6} md={6}>
            <Button bsStyle='info' onClick={this.previousStep} block>
               Start Over
            </Button>
          </Col>
          <Col xs={6} sm={6} md={6} >
            <Button bsStyle='success' onClick={this.nextStep} block>
              Continue
            </Button>
          </Col>
        </Row>

    )
  }

  componentDidMount () {
    this.props.mapClickHandler('surveyLocation', {saveValues: this.props.saveValues})
  }
  componentWillReceiveProps (np) {
    if (np.activeInput === 'Survey' && np.inputOpened) {
      this.props.mapClickHandler('surveyLocation', {saveValues: this.props.saveValues})
    } else if (!np.inputOpened) {
      if (typeof np.map.getLayer('point') !== 'undefined') np.map.removeLayer('point')
      this.props.mapClickHandler('featureSelection')
    }
  }
  componentWillUnmount () {
    this.props.mapClickHandler('featureSelection')
  }
}

export default CitizenSurveyLocation
<|endoftext|>


<commit_before><commit_msg>First Unique Character in a String solution added<commit_after><|endoftext|>


<commit_before>(function (angular) {
    "use strict";
    angular.module('dashboard.analytics')
        .controller('discoveryResourcesCtrl', ['$scope', '$rootScope', '$state','analyticsServices', 'genericServices','$timeout','toastr','$modal', function ($scope,$rootScope,$state,analyticsServices,genSevs,$timeout,toastr,$modal){
            var disResrc=this;
            $scope.instanceType=null;
            $scope.selectInstanceRow=[];
            $scope.TagName={
                environment:[],
                bg:[],
                project:[] ,bgTag:'',
                environmentTag:'',
                projectTag:''
            };
            // get gat name  Start
            disResrc.getAllTagNames=function () {
                $scope.TagName={
                    environment:[],
                    bg:[],
                    project:[],
                    bgTag:'bg',
                    environmentTag:'env',
                    projectTag:'pro'
                };
                // environment
                var param = {
                    url: '/providers/' + fltrObj.provider.id + '/tag-mappings/environment'
                };
                genSevs.promiseGet(param).then(function (instResult) {
                    $scope.TagName.environmentTag=instResult.tagName+'-en';
                    $scope.TagName.envFild='tags.'+instResult.tagName;
                    angular.forEach(instResult.tagValues,function(val){
                        $scope.TagName.environment.push({id:val,name:val})
                    });
                });
                // Bu
                var param = {
                    url: '/providers/' + fltrObj.provider.id + '/tag-mappings/businessGroup'
                };
                genSevs.promiseGet(param).then(function (instResult) {
                    $scope.TagName.bgTag=instResult.tagName+'-bu';
                    $scope.TagName.bgFild='tags.'+instResult.tagName;
                    angular.forEach(instResult.tagValues,function(val){
                        $scope.TagName.bg.push({id:val,name:val})
                    });
                });
                // project
                var param = {
                    url: '/providers/' + fltrObj.provider.id + '/tag-mappings/project'
                };
                genSevs.promiseGet(param).then(function (instResult) {
                    $scope.TagName.projectTag=instResult.tagName+'-pr';
                    $scope.TagName.projFild='tags.'+instResult.tagName;
                    angular.forEach(instResult.tagValues,function(val){
                        $scope.TagName.project.push({id:val,name:val})
                    });

                });

                // get gat name  End##########
            };
            disResrc.init=function () {
                if(fltrObj && fltrObj.provider && fltrObj.provider.id) {
                    disResrc.getAllTagNames();

                    $timeout(function () {
                        console.log( $scope.TagName);
                        disResrc.gridOptionInstances = {
                            allowCellFocus : false,
                            paginationPageSizes: [25, 50, 100],
                            paginationPageSize:25,
                            columnDefs: [],
                            onRegisterApi: function (gridApi) {
                                gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDef, newValue, oldValue) {
                                    console.log( colDef.name,'---',colDef.name.substring(0, colDef.name.length-3));
                                    var tagna=colDef.name.substring(0, colDef.name.length-3);
                                        var param = {
                                            url: '/providers/' + fltrObj.provider.id + '/unassigned-instances/' + rowEntity._id,
                                            data: {
                                                tags:{}
                                            }
                                        };
                                    param.data.tags[tagna]=newValue;
                                    console.log(param);
                                    if(newValue !== oldValue) {
                                        genSevs.promisePatch(param).then(function () {
                                            toastr.success('Successfully updated.', 'Update');
                                        });
                                    }
                                });
                                gridApi.selection.on.rowSelectionChanged($scope,function(row){
                                    if(row.isSelected){
                                        $scope.selectInstanceRow.push(row.entity._id);
                                    } else {
                                        $scope.selectInstanceRow.splice(row.entity._id,1);
                                    }

                                });
                                gridApi.selection.on.rowSelectionChangedBatch($scope,function(rows){
                                    angular.forEach(rows,function(row){
                                        if(row.isSelected){
                                            $scope.selectInstanceRow.push(row.entity._id);
                                        } else {
                                            $scope.selectInstanceRow.splice(row.entity._id,1);
                                        }
                                    });
                                });
                            }
                        };
                        disResrc.gridOptionInstances.data = [];
                        if($rootScope.organNewEnt.instanceType === 'Managed') {
                            $scope.instanceType= 'managedInstances';
                        } else if($rootScope.organNewEnt.instanceType === 'Assigned'){
                            disResrc.gridOptionInstances.enableFiltering=true;
                            disResrc.gridOptionInstances.columnDefs=[
                                {name: 'InstanceId', field: 'platformId',enableCellEditOnFocus: false,
                                    enableCellEdit: false,enableFiltering: true},
                                {name: 'os', enableFiltering: true,displayName: 'OS', enableCellEdit: false, type: 'number',enableCellEditOnFocus: false},
                                {name: 'privateIpAddress',enableFiltering: true, displayName: 'IP Address',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {name: 'state',enableFiltering: true, displayName: 'Status',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {
                                    name: 'Region',enableFiltering: true,
                                    displayName: 'Region',
                                    field: 'providerData.region_name',
                                    cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                },
                                {name: 'orgName', enableFiltering: true,displayName: 'Org Name', field: 'orgName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {
                                    name: 'bgName',
                                    displayName: 'BG Name',enableFiltering: true,
                                    field: 'bgName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                },
                                {
                                    name: 'projectName',enableFiltering: true,
                                    displayName: 'Project Name',
                                    field: 'projectName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                },
                                {
                                    name: 'environmentName',enableFiltering: true,
                                    displayName: 'Env Name',
                                    field: 'environmentName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                }
                            ];
                            $scope.instanceType= 'unmanagedInstances';
                        } else if($rootScope.organNewEnt.instanceType === 'Unassigned'){
                            disResrc.gridOptionInstances.enableFiltering=false;
                            disResrc.gridOptionInstances.columnDefs= [
                                {name: 'InstanceId', field: 'platformId',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {name: 'os', displayName: 'OS', enableCellEdit: false, type: 'number',enableCellEditOnFocus: false},
                                {name: 'privateIpAddress', displayName: 'IP Address',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {name: 'state', displayName: 'Status',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {
                                    name: 'Region',
                                    displayName: 'Region',
                                    field: 'providerData.region_name',
                                    cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                },
                                {name: 'orgName', displayName: 'Org Name', field: 'orgName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {
                                    name: $scope.TagName.bgTag,
                                    field:$scope.TagName.bgFild,
                                    displayName: 'BG Tag Value',
                                    width: 200,
                                    cellClass: 'editCell',
                                    enableCellEditOnFocus: true,
                                    enableCellEdit: true,
                                    editableCellTemplate: 'ui-grid/dropdownEditor',
                                    editDropdownOptionsArray: $scope.TagName.bg,
                                    editDropdownIdLabel: 'name',
                                    editDropdownValueLabel: 'id'
                                },
                                {
                                    name: $scope.TagName.projectTag,
                                    field:$scope.TagName.projFild,
                                    displayName: 'Project Tag Value',
                                    cellClass: 'editCell',
                                    width: 200,
                                    enableCellEditOnFocus: true,
                                    enableCellEdit: true,
                                    editableCellTemplate: 'ui-grid/dropdownEditor',
                                    editDropdownOptionsArray: $scope.TagName.project,
                                    editDropdownIdLabel: 'name',
                                    editDropdownValueLabel: 'id'
                                },
                                {
                                    name: $scope.TagName.environmentTag,
                                    field:$scope.TagName.envFild,
                                    displayName: 'Env Tag Value',
                                    cellClass: 'editCell',
                                    width: 200,
                                    enableCellEditOnFocus: true,
                                    enableCellEdit: true,
                                    editableCellTemplate: 'ui-grid/dropdownEditor',
                                    editDropdownOptionsArray: $scope.TagName.environment,
                                    editDropdownIdLabel: 'name',
                                    editDropdownValueLabel: 'id'
                                }
                            ];
                            $scope.instanceType= 'unassigned-instances';
                        }
                            var param = {
                                url: '/providers/' + fltrObj.provider.id + '/' + $scope.instanceType
                            };
                            genSevs.promiseGet(param).then(function (instResult) {
                                if($rootScope.organNewEnt.instanceType === 'Managed') {
                                    disResrc.gridOptionInstances.data = instResult.managedInstances;
                                } else if($rootScope.organNewEnt.instanceType === 'Assigned'){
                                    disResrc.gridOptionInstances.data = instResult.unmanagedInstances;
                                } else if($rootScope.organNewEnt.instanceType === 'Unassigned'){
                                    disResrc.gridOptionInstances.data = instResult.data;
                                }
                                disResrc.gridOptionInstances.isRowSelectable = function(row){
                                    if(row.entity.state !== 'running'){
                                        return false;
                                    } else {
                                        return true;
                                    }
                                };
                            });
                    }, 200);
                }
            };
            disResrc.importInstance =function ($event) {
                var modalInstance = $modal.open({
                    animation: true,
                    templateUrl: 'src/partials/sections/dashboard/analytics/view/instanceManage.html',
                    controller: 'instanceManageCtrl as insMang',
                    backdrop: 'static',
                    keyboard: false,
                    resolve: {
                        items: function() {
                            return  $scope.selectInstanceRow;
                        }
                    }
                });
                modalInstance.result.then(function() {

                }, function() {

                });
            };
            $rootScope.stateItems = $state.params;
            $rootScope.organNewEnt.provider='0';
            $rootScope.organNewEnt.instanceType='Unassigned';
            if($rootScope.organNewEnt.instanceType === 'Managed') {
                $scope.instanceType= 'unmanagedInstances';
            } else if($rootScope.organNewEnt.instanceType === 'Assigned'){
                $scope.instanceType= 'unmanagedInstances';
            } else if($rootScope.organNewEnt.instanceType === 'Unassigned'){
                $scope.instanceType= 'unassigned-instances';
            }
            analyticsServices.applyFilter(true,null);
            var treeNames = ['Cloud Management','Discovery','Resources'];
            $rootScope.$emit('treeNameUpdate', treeNames);
            var fltrObj=$rootScope.filterNewEnt;
            $rootScope.applyFilter =function(filterApp,period){
                analyticsServices.applyFilter(true,null);
                disResrc.init();
            };
            disResrc.init();

        }]).controller('instanceManageCtrl',['$scope','$rootScope','items','$modalInstance','genericServices',function ($scope,$rootScope,items,$modalInstance,genericServices) {
        $scope.items=items;
        $scope.IMGNewEnt={
            passType:'password',
            org:$rootScope.organObject[0]
        };
        //get configmanagement
        var params={
            url:'/organization/'+$scope.IMGNewEnt.org.orgid+'/configmanagement/list'
        }
        genericServices.promiseGet(params).then(function (list) {
            $scope.configOptions=list;
        });
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    }]);
})(angular);
<commit_msg>Previously selected tag value is not showing in Unassigned tab after refresh<commit_after>(function (angular) {
    "use strict";
    angular.module('dashboard.analytics')
        .controller('discoveryResourcesCtrl', ['$scope', '$rootScope', '$state','analyticsServices', 'genericServices','$timeout','toastr','$modal', function ($scope,$rootScope,$state,analyticsServices,genSevs,$timeout,toastr,$modal){
            var disResrc=this;
            $scope.instanceType=null;
            $scope.selectInstanceRow=[];
            $scope.TagName={
                environment:[],
                bg:[],
                project:[] ,bgTag:'',
                environmentTag:'',
                projectTag:''
            };
            // get gat name  Start
            disResrc.getAllTagNames=function () {
                $scope.TagName={
                    environment:[],
                    bg:[],
                    project:[],
                    bgTag:'bg',
                    environmentTag:'env',
                    projectTag:'pro'
                };
                // environment
                var param = {
                    url: '/providers/' + fltrObj.provider.id + '/tag-mappings/environment'
                };
                genSevs.promiseGet(param).then(function (instResult) {
                    $scope.TagName.environmentTag=instResult.tagName+'-en';
                    $scope.TagName.envFild='tags.'+instResult.tagName;
                    angular.forEach(instResult.tagValues,function(val){
                        $scope.TagName.environment.push({id:val,name:val})
                    });
                });
                // Bu
                var param = {
                    url: '/providers/' + fltrObj.provider.id + '/tag-mappings/businessGroup'
                };
                genSevs.promiseGet(param).then(function (instResult) {
                    $scope.TagName.bgTag=instResult.tagName+'-bu';
                    $scope.TagName.bgFild='tags.'+instResult.tagName;
                    angular.forEach(instResult.tagValues,function(val){
                        $scope.TagName.bg.push({id:val,name:val})
                    });
                });
                // project
                var param = {
                    url: '/providers/' + fltrObj.provider.id + '/tag-mappings/project'
                };
                genSevs.promiseGet(param).then(function (instResult) {
                    $scope.TagName.projectTag=instResult.tagName+'-pr';
                    $scope.TagName.projFild='tags.'+instResult.tagName;
                    angular.forEach(instResult.tagValues,function(val){
                        $scope.TagName.project.push({id:val,name:val})
                    });

                });

                // get gat name  End##########
            };
            disResrc.init=function () {
                if(fltrObj && fltrObj.provider && fltrObj.provider.id) {
                    disResrc.getAllTagNames();

                    $timeout(function () {
                        console.log( $scope.TagName);
                        disResrc.gridOptionInstances = {
                            allowCellFocus : false,
                            paginationPageSizes: [25, 50, 100],
                            paginationPageSize:25,
                            columnDefs: [],
                            onRegisterApi: function (gridApi) {
                                gridApi.edit.on.afterCellEdit($scope, function (rowEntity, colDefa, newValue, oldValue) {
                                    console.log( colDefa.name,'---',colDefa.name.substring(0, colDefa.name.length-3));
                                    var tagna=colDefa.name.substring(0, colDefa.name.length-3);
                                        var param = {
                                            url: '/providers/' + fltrObj.provider.id + '/unassigned-instances/' + rowEntity._id,
                                            data: {
                                                tags:{}
                                            }
                                        };
                                    param.data.tags[tagna]=newValue;
                                    console.log(param);
                                    if(newValue !== oldValue) {
                                        genSevs.promisePatch(param).then(function () {
                                            toastr.success('Successfully updated.', 'Update');
                                        });
                                    }
                                });
                                gridApi.selection.on.rowSelectionChanged($scope,function(row){
                                    if(row.isSelected){
                                        $scope.selectInstanceRow.push(row.entity._id);
                                    } else {
                                        $scope.selectInstanceRow.splice(row.entity._id,1);
                                    }

                                });
                                gridApi.selection.on.rowSelectionChangedBatch($scope,function(rows){
                                    angular.forEach(rows,function(row){
                                        if(row.isSelected){
                                            $scope.selectInstanceRow.push(row.entity._id);
                                        } else {
                                            $scope.selectInstanceRow.splice(row.entity._id,1);
                                        }
                                    });
                                });
                            }
                        };
                        disResrc.gridOptionInstances.data = [];
                        if($rootScope.organNewEnt.instanceType === 'Managed') {
                            $scope.instanceType= 'managedInstances';
                        } else if($rootScope.organNewEnt.instanceType === 'Assigned'){
                            disResrc.gridOptionInstances.enableFiltering=true;
                            disResrc.gridOptionInstances.columnDefs=[
                                {name: 'InstanceId', field: 'platformId',enableCellEditOnFocus: false,
                                    enableCellEdit: false,enableFiltering: true},
                                {name: 'os', enableFiltering: true,displayName: 'OS', enableCellEdit: false, type: 'number',enableCellEditOnFocus: false},
                                {name: 'privateIpAddress',enableFiltering: true, displayName: 'IP Address',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {name: 'state',enableFiltering: true, displayName: 'Status',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {
                                    name: 'Region',enableFiltering: true,
                                    displayName: 'Region',
                                    field: 'providerData.region_name',
                                    cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                },
                                {name: 'orgName', enableFiltering: true,displayName: 'Org Name', field: 'orgName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {
                                    name: 'bgName',
                                    displayName: 'BG Name',enableFiltering: true,
                                    field: 'bgName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                },
                                {
                                    name: 'projectName',enableFiltering: true,
                                    displayName: 'Project Name',
                                    field: 'projectName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                },
                                {
                                    name: 'environmentName',enableFiltering: true,
                                    displayName: 'Env Name',
                                    field: 'environmentName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                }
                            ];
                            $scope.instanceType= 'unmanagedInstances';
                        } else if($rootScope.organNewEnt.instanceType === 'Unassigned'){
                            disResrc.gridOptionInstances.enableFiltering=false;
                            disResrc.gridOptionInstances.columnDefs= [
                                {name: 'InstanceId', field: 'platformId',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {name: 'os', displayName: 'OS', enableCellEdit: false, type: 'number',enableCellEditOnFocus: false},
                                {name: 'privateIpAddress', displayName: 'IP Address',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {name: 'state', displayName: 'Status',enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {
                                    name: 'Region',
                                    displayName: 'Region',
                                    field: 'providerData.region_name',
                                    cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false
                                },
                                {name: 'orgName', displayName: 'Org Name', field: 'orgName', cellTooltip: true,enableCellEditOnFocus: false,
                                    enableCellEdit: false},
                                {
                                    name: $scope.TagName.bgTag,
                                    field:$scope.TagName.bgFild,
                                    displayName: 'BG Tag Value',
                                    width: 200,
                                    cellClass: 'editCell',
                                    enableCellEditOnFocus: true,
                                    enableCellEdit: true,
                                    editableCellTemplate: 'ui-grid/dropdownEditor',
                                    editDropdownOptionsArray: $scope.TagName.bg,
                                    editDropdownIdLabel: 'name',
                                    editDropdownValueLabel: 'id'
                                },
                                {
                                    name: $scope.TagName.projectTag,
                                    field:$scope.TagName.projFild,
                                    displayName: 'Project Tag Value',
                                    cellClass: 'editCell',
                                    width: 200,
                                    enableCellEditOnFocus: true,
                                    enableCellEdit: true,
                                    editableCellTemplate: 'ui-grid/dropdownEditor',
                                    editDropdownOptionsArray: $scope.TagName.project,
                                    editDropdownIdLabel: 'name',
                                    editDropdownValueLabel: 'id'
                                },
                                {
                                    name: $scope.TagName.environmentTag,
                                    field:$scope.TagName.envFild,
                                    displayName: 'Env Tag Value',
                                    cellClass: 'editCell',
                                    width: 200,
                                    enableCellEditOnFocus: true,
                                    enableCellEdit: true,
                                    editableCellTemplate: 'ui-grid/dropdownEditor',
                                    editDropdownOptionsArray: $scope.TagName.environment,
                                    editDropdownIdLabel: 'name',
                                    editDropdownValueLabel: 'id'
                                }
                            ];
                            $scope.instanceType= 'unassigned-instances';
                        }
                            var param = {
                                url: '/providers/' + fltrObj.provider.id + '/' + $scope.instanceType
                            };
                            genSevs.promiseGet(param).then(function (instResult) {
                                if($rootScope.organNewEnt.instanceType === 'Managed') {
                                    disResrc.gridOptionInstances.data = instResult.managedInstances;
                                } else if($rootScope.organNewEnt.instanceType === 'Assigned'){
                                    disResrc.gridOptionInstances.data = instResult.unmanagedInstances;
                                } else if($rootScope.organNewEnt.instanceType === 'Unassigned'){
                                    disResrc.gridOptionInstances.data = instResult.data;
                                }
                                disResrc.gridOptionInstances.isRowSelectable = function(row){
                                    if(row.entity.state !== 'running'){
                                        return false;
                                    } else {
                                        return true;
                                    }
                                };
                            });
                    }, 200);
                }
            };
            disResrc.importInstance =function ($event) {
                var modalInstance = $modal.open({
                    animation: true,
                    templateUrl: 'src/partials/sections/dashboard/analytics/view/instanceManage.html',
                    controller: 'instanceManageCtrl as insMang',
                    backdrop: 'static',
                    keyboard: false,
                    resolve: {
                        items: function() {
                            return  $scope.selectInstanceRow;
                        }
                    }
                });
                modalInstance.result.then(function() {

                }, function() {

                });
            };
            $rootScope.stateItems = $state.params;
            $rootScope.organNewEnt.provider='0';
            $rootScope.organNewEnt.instanceType='Unassigned';
            if($rootScope.organNewEnt.instanceType === 'Managed') {
                $scope.instanceType= 'unmanagedInstances';
            } else if($rootScope.organNewEnt.instanceType === 'Assigned'){
                $scope.instanceType= 'unmanagedInstances';
            } else if($rootScope.organNewEnt.instanceType === 'Unassigned'){
                $scope.instanceType= 'unassigned-instances';
            }
            analyticsServices.applyFilter(true,null);
            var treeNames = ['Cloud Management','Discovery','Resources'];
            $rootScope.$emit('treeNameUpdate', treeNames);
            var fltrObj=$rootScope.filterNewEnt;
            $rootScope.applyFilter =function(filterApp,period){
                analyticsServices.applyFilter(true,null);
                disResrc.init();
            };
            disResrc.init();

        }]).controller('instanceManageCtrl',['$scope','$rootScope','items','$modalInstance','genericServices',function ($scope,$rootScope,items,$modalInstance,genericServices) {
        $scope.items=items;
        $scope.IMGNewEnt={
            passType:'password',
            org:$rootScope.organObject[0]
        };
        //get configmanagement
        var params={
            url:'/organization/'+$scope.IMGNewEnt.org.orgid+'/configmanagement/list'
        }
        genericServices.promiseGet(params).then(function (list) {
            $scope.configOptions=list;
        });
        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };
    }]);
})(angular);
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2013-2017 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jshint node: true */

'use strict';

var assert = require('assert');
var chalk = require('chalk');
var config = require('../config');

var RX_LEVELS = /^(debug|info|warn|error|crit)$/i;
var level = config.get('level') || 0;
var levels = {
        debug: 1,
        info: 2,
        warn: 4,
        error: 5,
        crit: 6
    };
var eq = ': ';
var qt = '';
var prefix = ' ';
var separator = '; ';

chalk.debug = chalk.gray;
chalk.info = chalk.green;
chalk.warn = chalk.yellow;
chalk.error = chalk.magenta;
chalk.crit = chalk.red;

/* This function has too many statements. */
/* jshint -W071 */

/* This function's cyclomatic complexity is too high. */
/* jshint -W074 */

/**
 * Format log entry with request data
 * @param entry
 * @param level
 * @returns {*}
 */
function format(entry, level) {
    assert.ok(typeof entry === 'object', '`entry` is expected to be an object');
    assert.ok(RX_LEVELS.test(level), '`level` is expected to be any of `debug`, `info`, `warn`, `error` or `crit`');
    // JSON.stringify(new Error('Oops)) === {} and we do not want to clutter our logs with 'undefined'
    // So we need to capture the properties we want after testing that they exist
    var ret = {};
    // Message
    if (entry.message) {
        ret.message = entry.message;
    } else if (entry.error instanceof Error) {
        ret.message = entry.error.message;
    }
    // Level
    ret.level = level.toLowerCase();
    // Application
    var application = config.get('application:name');
    if (application) {
        ret.application = application;
    }
    if (entry.module) {
        ret.module = entry.module;
    }
    if (entry.method) {
        ret.method = entry.method;
    }
    // Host
    if (process.env.HOSTNAME) {
        ret.host = process.env.HOSTNAME;
    }
    var request = entry.request;
    // IP Address
    if (request && request.ip) {
        ret.ip = request.ip;
    }
    // User Agent
    if (request && request.header && request.headers['user-agent']) {
        ret.agent = request.headers['user-agent'];
    }
    // Trace
    if (entry.trace) {
        ret.trace = entry.trace;
    } else if (request && request.trace) {
        ret.trace = request.trace;
    }
    // Url
    if (entry.url) {
        ret.url = entry.url;
    } else if (request && request.url) {
        ret.url = request.url;
    }
    // Query
    if (entry.query) {
        ret.query = entry.query;
    } else if (request && request.query) {
        ret.query = request.query;
    }
    // Error message and stack
    if (entry.stack) {
        if (entry.message) {
            ret.error = entry.message;
        }
        ret.stack = entry.stack;
    } else if (entry.error && entry.error.stack) {
        if (entry.error.message) {
            ret.error = entry.error.message;
        } else if (entry.error.originalError && entry.error.originalError.message) {
            // entry.error.originalError is not necessarily an instance of Error because we use deepExtend
            // TODO: CHeck that this actually occurs
            ret.error = entry.error.originalError.message;
        }
        ret.stack = entry.error.stack;
    }
    // entry.date = (new Date()).toISOString();
    // Note: such an entry is not only ready to print to console but also to be sent as JSON
    return ret;
}

/**
* Print a log entry to the console
* Note: we have discarded coloured solutions because they do not print well in Webstorm console
* @param entry
*/
function print(entry) {
    /* jshint maxstatements: 49 */
    /* jshint maxcomplexity: 35 */
    var message = (isNaN(Date.parse(entry.date)) ? new Date() : new Date(entry.date)).toISOString();
    message += prefix + '[' + entry.level.toUpperCase() + ']' + (entry.level.length > 4 ? '' : ' ');
    var first = true;
    if (entry.application) {
        message += (first ? prefix : separator) + 'application' + eq + qt + entry.application + qt;
        first = false;
    }
    if (entry.host) {
        message += (first ? prefix : separator) + 'host' + eq + qt + entry.host + qt;
        first = false;
    }
    if (entry.message) {
        message += (first ? prefix : separator) + 'message' + eq + qt + entry.message + qt;
        first = false;
    }
    if (entry.originalMessage) {
        message += (first ? prefix : separator) + 'originalMessage' + eq + qt + entry.originalMessage + qt;
        first = false;
    }
    if (entry.module) {
        message += (first ? prefix : separator) + 'module' + eq + qt + entry.module + qt;
        first = false;
    }
    if (entry.method) {
        message += (first ? prefix : separator) + 'method' + eq + qt + entry.method + qt;
        first = false;
    }
    if (entry.data) {
        try {
            message += (first ? prefix : separator) + 'data' + eq + qt + JSON.stringify(entry.data) + qt;
        } catch (ex) {
            if (typeof entry.data.toString === 'function') {
                message += (first ? prefix : separator) + 'data' + eq + qt + entry.data.toString() + qt;
            }
        }
        first = false;
    }
    if (entry.url) {
        message += (first ? prefix : separator) + 'url' + eq + qt + entry.url + qt;
        first = false;
    }
    if (entry.query) {
        try {
            message += (first ? prefix : separator) + 'query' + eq + qt + JSON.stringify(entry.query) + qt;
        } catch (ex) {
            if (typeof entry.data.toString === 'function') {
                message += (first ? prefix : separator) + 'query' + eq + qt + entry.query.toString() + qt;
            }
        }
        first = false;
    }
    if (entry.trace) {
        message += (first ? prefix : separator) + 'trace' + eq + qt + entry.trace + qt;
        first = false;
    }
    if (entry.ip) {
        message += (first ? prefix : separator) + 'ip' + eq + qt + entry.ip + qt;
        first = false;
    }
    if (entry.agent) {
        message += (first ? prefix : separator) + 'agent' + eq + qt + entry.agent + qt;
        first = false;
    }
    if (entry.stack) {
        message += (first ? prefix : separator) + 'stack' + eq + qt + entry.stack.split('\n').join(', ').replace(/\s+/g, ' ') + qt;
    }
    console.log(chalk.supportsColor ? chalk[entry.level || 'debug'](message) : message);
    return message;
}

/* jshint +W074 */
/* jshint +W071 */

module.exports = exports = {

    /**
     * Export level for tests
     */
    level: level,

    /**
     * Log a debug entry
     * Only output if debug===true
     * @param entry
     */
    debug: function (entry) {
        if (exports.level > levels.debug) {
            return false;
        }
        print(format(entry, 'debug'));
        return true;
    },

    /**
     * Log an info entry
     * @param entry
     */
    info: function (entry) {
        if (exports.level > levels.info) {
            return false;
        }
        print(format(entry, 'info'));
        return true;
    },

    /**
     * Log a warning entry
     * @param entry
     */
    warn: function (entry) {
        if (exports.level > levels.warn) {
            return false;
        }
        print(format(entry, 'warn'));
        return true;
    },

    /**
     * Log an error entry
     * @param entry
     */
    error: function (entry) {
        if (exports.level > levels.error) {
            return false;
        }
        print(format(entry, 'error'));
        return true;
    },

    /**
     * Log a critical entry
     * @param entry
     */
    critical: function (entry) {
        if (exports.level > levels.crit) {
            return false;
        }
        var plugins = require('../plugins');
        var formatted = format(entry, 'crit');
        print(formatted);
        plugins.emit('slack', {
            slack: {
                channel: config.get('slack:channels:weberrors'),
                level: formatted.level,
                text: formatted.message
            },
            model: formatted
        });
        return true;
    },

    /**
     * Shortcut for critical
     */
    crit: function (entry) {
        exports.critical(entry);
    }

};
<commit_msg>Copied from Kidoju-Server after fixing logging in production mode when config read from S3.<commit_after>/**
 * Copyright (c) 2013-2017 Memba Sarl. All rights reserved.
 * Sources at https://github.com/Memba
 */

/* jshint node: true */

'use strict';

var assert = require('assert');
var chalk = require('chalk');
var config = require('../config');

var RX_LEVELS = /^(debug|info|warn|error|crit)$/i;
var levels = {
        debug: 1,
        info: 2,
        warn: 4,
        error: 5,
        crit: 6
    };
var eq = ': ';
var qt = '';
var prefix = ' ';
var separator = '; ';

chalk.debug = chalk.gray;
chalk.info = chalk.green;
chalk.warn = chalk.yellow;
chalk.error = chalk.magenta;
chalk.crit = chalk.red;

/* This function has too many statements. */
/* jshint -W071 */

/* This function's cyclomatic complexity is too high. */
/* jshint -W074 */

/**
 * Format log entry with request data
 * @param entry
 * @param level
 * @returns {*}
 */
function format(entry, level) {
    assert.ok(typeof entry === 'object', '`entry` is expected to be an object');
    assert.ok(RX_LEVELS.test(level), '`level` is expected to be any of `debug`, `info`, `warn`, `error` or `crit`');
    // JSON.stringify(new Error('Oops)) === {} and we do not want to clutter our logs with 'undefined'
    // So we need to capture the properties we want after testing that they exist
    var ret = {};
    // Message
    if (entry.message) {
        ret.message = entry.message;
    } else if (entry.error instanceof Error) {
        ret.message = entry.error.message;
    }
    // Level
    ret.level = level.toLowerCase();
    // Application
    var application = config.get('application:name');
    if (application) {
        ret.application = application;
    }
    if (entry.module) {
        ret.module = entry.module;
    }
    if (entry.method) {
        ret.method = entry.method;
    }
    // Host
    if (process.env.HOSTNAME) {
        ret.host = process.env.HOSTNAME;
    }
    var request = entry.request;
    // IP Address
    if (request && request.ip) {
        ret.ip = request.ip;
    }
    // User Agent
    if (request && request.header && request.headers['user-agent']) {
        ret.agent = request.headers['user-agent'];
    }
    // Trace
    if (entry.trace) {
        ret.trace = entry.trace;
    } else if (request && request.trace) {
        ret.trace = request.trace;
    }
    // Url
    if (entry.url) {
        ret.url = entry.url;
    } else if (request && request.url) {
        ret.url = request.url;
    }
    // Query
    if (entry.query) {
        ret.query = entry.query;
    } else if (request && request.query) {
        ret.query = request.query;
    }
    // Error message and stack
    if (entry.stack) {
        if (entry.message) {
            ret.error = entry.message;
        }
        ret.stack = entry.stack;
    } else if (entry.error && entry.error.stack) {
        if (entry.error.message) {
            ret.error = entry.error.message;
        } else if (entry.error.originalError && entry.error.originalError.message) {
            // entry.error.originalError is not necessarily an instance of Error because we use deepExtend
            // TODO: CHeck that this actually occurs
            ret.error = entry.error.originalError.message;
        }
        ret.stack = entry.error.stack;
    }
    // entry.date = (new Date()).toISOString();
    // Note: such an entry is not only ready to print to console but also to be sent as JSON
    return ret;
}

/**
* Print a log entry to the console
* Note: we have discarded coloured solutions because they do not print well in Webstorm console
* @param entry
*/
function print(entry) {
    /* jshint maxstatements: 49 */
    /* jshint maxcomplexity: 35 */
    var message = (isNaN(Date.parse(entry.date)) ? new Date() : new Date(entry.date)).toISOString();
    message += prefix + '[' + entry.level.toUpperCase() + ']' + (entry.level.length > 4 ? '' : ' ');
    var first = true;
    if (entry.application) {
        message += (first ? prefix : separator) + 'application' + eq + qt + entry.application + qt;
        first = false;
    }
    if (entry.host) {
        message += (first ? prefix : separator) + 'host' + eq + qt + entry.host + qt;
        first = false;
    }
    if (entry.message) {
        message += (first ? prefix : separator) + 'message' + eq + qt + entry.message + qt;
        first = false;
    }
    if (entry.originalMessage) {
        message += (first ? prefix : separator) + 'originalMessage' + eq + qt + entry.originalMessage + qt;
        first = false;
    }
    if (entry.module) {
        message += (first ? prefix : separator) + 'module' + eq + qt + entry.module + qt;
        first = false;
    }
    if (entry.method) {
        message += (first ? prefix : separator) + 'method' + eq + qt + entry.method + qt;
        first = false;
    }
    if (entry.data) {
        try {
            message += (first ? prefix : separator) + 'data' + eq + qt + JSON.stringify(entry.data) + qt;
        } catch (ex) {
            if (typeof entry.data.toString === 'function') {
                message += (first ? prefix : separator) + 'data' + eq + qt + entry.data.toString() + qt;
            }
        }
        first = false;
    }
    if (entry.url) {
        message += (first ? prefix : separator) + 'url' + eq + qt + entry.url + qt;
        first = false;
    }
    if (entry.query) {
        try {
            message += (first ? prefix : separator) + 'query' + eq + qt + JSON.stringify(entry.query) + qt;
        } catch (ex) {
            if (typeof entry.data.toString === 'function') {
                message += (first ? prefix : separator) + 'query' + eq + qt + entry.query.toString() + qt;
            }
        }
        first = false;
    }
    if (entry.trace) {
        message += (first ? prefix : separator) + 'trace' + eq + qt + entry.trace + qt;
        first = false;
    }
    if (entry.ip) {
        message += (first ? prefix : separator) + 'ip' + eq + qt + entry.ip + qt;
        first = false;
    }
    if (entry.agent) {
        message += (first ? prefix : separator) + 'agent' + eq + qt + entry.agent + qt;
        first = false;
    }
    if (entry.stack) {
        message += (first ? prefix : separator) + 'stack' + eq + qt + entry.stack.split('\n').join(', ').replace(/\s+/g, ' ') + qt;
    }
    console.log(chalk.supportsColor ? chalk[entry.level || 'debug'](message) : message);
    return message;
}

/* jshint +W074 */
/* jshint +W071 */

module.exports = exports = {

    /**
     * Log a debug entry
     * Only output if debug===true
     * @param entry
     */
    debug: function (entry) {
        // Note: config.get('level') cannot be cached in a module variable because it is not available when the module loads when loading production.json from AWS S3
        if ((config.get('level') || 0) > levels.debug) {
            return false;
        }
        print(format(entry, 'debug'));
        return true;
    },

    /**
     * Log an info entry
     * @param entry
     */
    info: function (entry) {
        if ((config.get('level') || 0) > levels.info) {
            return false;
        }
        print(format(entry, 'info'));
        return true;
    },

    /**
     * Log a warning entry
     * @param entry
     */
    warn: function (entry) {
        if ((config.get('level') || 0) > levels.warn) {
            return false;
        }
        print(format(entry, 'warn'));
        return true;
    },

    /**
     * Log an error entry
     * @param entry
     */
    error: function (entry) {
        if ((config.get('level') || 0) > levels.error) {
            return false;
        }
        print(format(entry, 'error'));
        return true;
    },

    /**
     * Log a critical entry
     * @param entry
     */
    critical: function (entry) {
        if (exports.level > levels.crit) {
            return false;
        }
        var plugins = require('../plugins');
        var formatted = format(entry, 'crit');
        print(formatted);
        plugins.emit('slack', {
            slack: {
                channel: config.get('slack:channels:weberrors'),
                level: formatted.level,
                text: formatted.message
            },
            model: formatted
        });
        return true;
    },

    /**
     * Shortcut for critical
     */
    crit: function (entry) {
        exports.critical(entry);
    }

};
<|endoftext|>