<commit_before>/**
 * UI and function to quick search projects
 */

var $ = require('jquery');
var m = require('mithril');
var $osf = require('js/osfHelpers');

// CSS
require('css/quick-project-search-plugin.css');

// XHR config for apiserver connection
var xhrconfig = function(xhr) {
    xhr.withCredentials = true;
};

var quickSearchProject = {
    controller: function() {
        var self = this;
        self.nodes = m.prop([]); // Pending nodes waiting to be displayed
        self.displayedNodes = m.prop([]); // Nodes that are rendered
        self.nonMatchingNodes = m.prop([]); //Nodes that don't match search query
        self.sortState = m.prop('dateDesc');
        self.countDisplayed = m.prop();
        self.next = m.prop();
        self.loadingComplete = m.prop(false);
        self.contributorMapping = {};
        self.filter = m.prop();
        self.totalLoaded = m.prop();

        // Load first ten nodes
        var url = $osf.apiV2Url('users/me/nodes/', { query : { 'embed': 'contributors'}});
        var promise = m.request({method: 'GET', url : url, config : xhrconfig});
        promise.then(function(result) {
            self.countDisplayed(result.data.length);
            result.data.forEach(function (node) {
                self.nodes().push(node);
                self.retrieveContributors(node)
            });
            self.next(result.links.next);
            self.displayedNodes(self.nodes().splice(0, 10));
            self.totalLoaded(self.displayedNodes().length)
        });
        promise.then(
            function(){
                if (self.next()) {
                    self.recursiveNodes(self.next())
                }
                else {
                    self.loadingComplete(true);
                    m.redraw()
                }
            }
        );

        // Recursively fetches remaining user's nodes
        self.recursiveNodes = function (url) {
            if (self.nodes().length > 0) {
                m.redraw()
            }
             var nextPromise = m.request({method: 'GET', url : url, config : xhrconfig, background : true});
                nextPromise.then(function(result){
                    result.data.forEach(function(node){
                        self.nodes().push(node);
                        self.retrieveContributors(node)
                    });
                    self.next(result.links.next);
                    console.log(self.next());
                    if (self.next()) {
                        self.recursiveNodes(self.next())
                    }
                    else {
                        self.loadingComplete(true);
                        m.redraw()
                    }
        })};

        self.retrieveContributors = function(node) {
            if (node.embeds.contributors.links.meta.total > 10) {
                self.pullOverTenContributorNames(node)
            }
            else {
                var contributors = node.embeds.contributors;
                self.mapNodeToContributors(node, contributors)
                }
        };

        self.pullOverTenContributorNames = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/contributors/', { query : { 'page[size]': 1000 }});
            var promise = m.request({method: 'GET', url : url, config: xhrconfig, background : true});
            promise.then(function(result){
                self.mapNodeToContributors(node, result)
            })
        };

        self.mapNodeToContributors = function (node, contributors){
            var contributorList = [];
            contributors.data.forEach(function(contrib){
                fullName = contrib.embeds.users.data.attributes.full_name;
                contributorList.push(fullName)

            });
            self.contributorMapping[node.id] = contributorList
        };

        self.loadUpToTen = function () {
            var requested = self.nodes().splice(0, 10);
            for (var i = 0; i < requested.length; i++) {
                self.displayedNodes().push(requested[i])
            }
            self.countDisplayed(self.displayedNodes().length);
            return self.displayedNodes()
        };

        self.getFamilyName = function(i, node) {
            return node.embeds.contributors.data[i].embeds.users.data.attributes.family_name
        };

        self.getContributors = function (node) {
            var numContributors = node.embeds.contributors.links.meta.total;
            if (numContributors === 1) {
                return self.getFamilyName(0, node)
            }
            else if (numContributors === 2) {
                return self.getFamilyName(0, node) + ' and ' +
                    self.getFamilyName(1, node)
            }
            else if (numContributors === 3) {
                return self.getFamilyName(0, node) + ', ' +
                    self.getFamilyName(1, node) + ', and ' +
                    self.getFamilyName(2, node)
            }
            else {
                return self.getFamilyName(0, node) + ', ' +
                    self.getFamilyName(1, node) + ', ' +
                    self.getFamilyName(2, node) + ' + ' + (numContributors - 3)
            }

        };

        self.formatDate = function (node) {
            return new $osf.FormattableDate(node.attributes.date_modified).local
        };

        self.restoreToNodeList = function (missingNodes) {
            for (var i = 0; i < missingNodes.length ; i++) {
                self.nodes().push(missingNodes[i])
            }
        };

        self.sortAlphabeticalAscending = function () {
            self.nodes().sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.sortState('alphaAsc');
        };

        self.sortAlphabeticalDescending = function () {
            self.nodes().sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.sortState('alphaDesc');
        };

        self.sortDateAscending = function () {
            self.nodes().sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.sortState('dateAsc')
        };

        self.sortDateDescending = function () {
            self.nodes().sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.sortState('dateDesc');
        };

        self.sortBySortState = function () {
            if (self.sortState() === 'alphaAsc') {
                self.sortAlphabeticalAscending()
            }
            else if (self.sortState() === 'alphaDesc') {
                self.sortAlphabeticalDescending()
            }
            else if (self.sortState() === 'dateAsc') {
                self.sortDateAscending()
            }
            else {
                self.sortDateDescending()
            }
        };

        self.colorSortButtons = function () {
            var sortButtons = ['dateAsc', 'dateDesc', 'alphaAsc', 'alphaDesc']
            console.log(document.getElementById(self.sortState()));
            var button = document.getElementById(self.sortState()).className = 'selected';
            sortButtons.forEach(function(button) {
                console.log(button);
                if (self.sortState() !== button) {
                    console.log(document.getElementById(button));
                    document.getElementById(button).className = 'not-selected'
                }
            })
        };

        self.sortNodesAndModifyDisplay = function () {
            self.restoreToNodeList(self.displayedNodes());
            self.sortBySortState();
            self.colorSortButtons()
            self.displayedNodes(self.nodes().splice(0, self.countDisplayed()))
        };

        self.noTitleMatch = function (node) {
            return (node.attributes.title.toUpperCase().indexOf(self.filter().toUpperCase()) === -1);
        };

        self.noContributorMatch = function (node) {
            var contributors = self.contributorMapping[node.id];

            for (var c = 0; c < contributors.length; c++) {
                if (contributors[c].toUpperCase().indexOf(self.filter().toUpperCase()) !== -1){
                    return false
                }
            }
            return true
        };

        self.filterNodes = function (){
            for (var n = self.nodes().length - 1; n >= 0; n--) {
                var node = self.nodes()[n];
                if (self.noTitleMatch(node) && self.noContributorMatch(node)) {
                    self.nonMatchingNodes().push(node);
                    self.nodes().splice(n, 1)
                }
            }
        };

        self.mouseOver = function (node) {
            node.style.backgroundColor='#E0EBF3'
        };

        self.mouseOut = function (node) {
            node.style.backgroundColor='#fcfcfc'
        }

        self.quickSearch = function () {
            self.filter(document.getElementById('searchQuery').value);
            self.restoreToNodeList(self.nonMatchingNodes());
            self.restoreToNodeList(self.displayedNodes());
            self.displayedNodes([]);
            self.nonMatchingNodes([]);
            // if backspace completely, previous nodes with prior sorting/count will be displayed
            if (self.filter() === '') {
                self.sortNodesAndModifyDisplay();
                return self.displayedNodes()
            }
            else {
                self.filterNodes();
                self.sortBySortState();
                var numDisplay = Math.min(self.nodes().length, self.countDisplayed());
                for (var i = 0; i < numDisplay; i++) {
                    self.displayedNodes().push(self.nodes()[i])
                }
                self.nodes().splice(0, numDisplay);
                return self.displayedNodes()
            }

        };

    },
    view : function(ctrl) {
        function loadMoreButton() {
            if (ctrl.nodes().length !== 0){
                return m('button', {class: 'col-sm-12 text-muted', onclick: function() {
                        ctrl.loadUpToTen()}
                },
                m('i', {class: 'fa fa-caret-down load-nodes'}))
            }
        }

        function sortAlphaAsc() {
            if (ctrl.loadingComplete()) {
                return m('button', {id: 'alphaAsc', class: 'not-selected', onclick: function() {
                    ctrl.sortState('alphaAsc');
                    ctrl.sortNodesAndModifyDisplay();
                }},
                    m('i', {class: 'fa fa-angle-up'})
)
            }
        }

        function sortAlphaDesc(){
            if (ctrl.loadingComplete()){
                return m('button', {id: 'alphaDesc', class: 'not-selected', onclick: function() {
                    ctrl.sortState('alphaDesc');
                    ctrl.sortNodesAndModifyDisplay();
                }},
                m('i', {class: 'fa fa-angle-down'}))
            }
        }

        function sortDateAsc(){
            if (ctrl.loadingComplete()){
                 return m('button', {id: 'dateAsc', class: 'not-selected', onclick: function() {
                     ctrl.sortState('dateAsc');
                     ctrl.sortNodesAndModifyDisplay()}},
                 m('i', {class: 'fa fa-angle-up'}))
            }
        }
        function sortDateDesc(){
            if (ctrl.loadingComplete()){
                return m('button', {id: 'dateDesc', class: 'selected', onclick: function() {
                    ctrl.sortState('dateDesc');
                    ctrl.sortNodesAndModifyDisplay();
               }},
                m('i', {class: 'fa fa-angle-down'}))
            }
        }

        function searchBar() {
            if (ctrl.loadingComplete()){
                return m('div', {class : 'input-group'}, [
                    m('span', {class: 'input-group-addon'}, m('i', {class: 'fa fa-search'})),
                    m('input[type=search]', {class: 'form-control', id: 'searchQuery', placeholder: 'Quick search projects', onkeyup: function() {ctrl.quickSearch()}})
                ])
            }
        }

        function displayNodes() {
            if (ctrl.displayedNodes().length == 0 && ctrl.filter() != null) {
                return m('div', {class: 'row m-v-sm'}, m('div', {class: 'col-sm-10 col-sm-offset-1'},
                    m('div', {class: 'row'}, [
                        m('div', {class: 'col-sm-1'}),
                        m('div', {class: 'col-sm-11'},[m('p', {class :'fa fa-exclamation-triangle'}, m('em', '  No results found!'))])
                    ])
                ))
            }
            else {
                return ctrl.displayedNodes().map(function(n){
                    return projectView(n)
                })
            }
        }

        function projectView(project) {
            console.log('pending: ' + ctrl.nodes().length, ', displayed: ' + ctrl.displayedNodes().length, ', non-matching: ' + ctrl.nonMatchingNodes().length, ctrl.sortState());
            return m('div', {class: 'row m-v-sm'}, m('div', {class: 'col-sm-10 col-sm-offset-1'},
                m('div', {class: 'row node-styling',  onmouseover: function(){ctrl.mouseOver(this)}, onmouseout: function(){ctrl.mouseOut(this)}}, [
                    m('div', {class: 'col-sm-1 p-v-xs'}),
                    m('div', {class: 'col-sm-4 p-v-xs'}, m("a", {href: '/'+ project.id}, project.attributes.title)),
                    m('div', {class: 'col-sm-4 text-muted  p-v-xs'}, ctrl.getContributors(project)),
                    m('div', {class: 'col-sm-3 p-v-xs'}, ctrl.formatDate(project)),
                ])
            ))
        }

        function resultsFound(){
            return m('div', {class: 'container'}, [
                m('div', {class: 'row'}, [
                    m('div', {'class': 'col-sm-1'}),
                    m('div', {'class': 'col-sm-11'}, m('h3', 'My Projects'))
                ]),
                m('div', {class: 'row'},
                    m('div', {class: 'col-sm-3'}),
                    m('div', {class: 'col-sm-6 m-b-md text-center'}, [
                        searchBar(),
                        ctrl.loadingComplete() ? '' : m('.spinner-div', m('div', {class:'logo-spin logo-sm m-r-lg'}), 'Loading projects...')
                    ]),
                    m('div', {class: 'col-sm-3'})),

                m('div', {class: 'row'}, m('div', {class: 'col-sm-10 col-sm-offset-1'},
                m('div', {class: 'row'}, [
                    m('div', {class: 'col-sm-1 p-v-xs'}),
                    m('div', {class: 'col-sm-4 p-v-xs, f-w-xl'}, 'Name', sortAlphaAsc(), sortAlphaDesc()),
                    m('div', {class: 'col-sm-4 f-w-xl p-v-xs'}, 'Contributors'),
                    m('div', {class: 'col-sm-3 f-w-xl p-v-xs'}, 'Date Modified', sortDateAsc(), sortDateDesc()),
                ])
                )),

                displayNodes(),
                m('div', {class: 'row'}, [
                    m('div', {class: 'col-sm-5'}),
                    m('div', {class: 'col-sm-2'}, loadMoreButton()),
                    m('div', {class: 'col-sm-5'})
                ])
            ]);
        }

        if (ctrl.displayedNodes().length == 0 && ctrl.filter() == null) {
            return m('div', {class: 'container'}, [
                m('div', {class: 'row'}, [
                    m('div', {'class': 'col-sm-1'}),
                    m('div', {'class': 'col-sm-11'}, m('h3', 'My Projects'))
                ]),
                m('div', {class: 'row m-v-md'},
                    m('div', {class: 'col-sm-1'}),
                    m('div', {class: 'col-sm-11'}, m('h4', 'You have no projects. Go here to create one.'))
            )]
        )}
        else {
            return resultsFound()
        }
    }
};
module.exports = quickSearchProject;

<commit_msg>Rename node 'name' to 'title'.  User could confuse "name" with contributor name.<commit_after>/**
 * UI and function to quick search projects
 */

var $ = require('jquery');
var m = require('mithril');
var $osf = require('js/osfHelpers');

// CSS
require('css/quick-project-search-plugin.css');

// XHR config for apiserver connection
var xhrconfig = function(xhr) {
    xhr.withCredentials = true;
};

var quickSearchProject = {
    controller: function() {
        var self = this;
        self.nodes = m.prop([]); // Pending nodes waiting to be displayed
        self.displayedNodes = m.prop([]); // Nodes that are rendered
        self.nonMatchingNodes = m.prop([]); //Nodes that don't match search query
        self.sortState = m.prop('dateDesc');
        self.countDisplayed = m.prop();
        self.next = m.prop();
        self.loadingComplete = m.prop(false);
        self.contributorMapping = {};
        self.filter = m.prop();
        self.totalLoaded = m.prop();

        // Load first ten nodes
        var url = $osf.apiV2Url('users/me/nodes/', { query : { 'embed': 'contributors'}});
        var promise = m.request({method: 'GET', url : url, config : xhrconfig});
        promise.then(function(result) {
            self.countDisplayed(result.data.length);
            result.data.forEach(function (node) {
                self.nodes().push(node);
                self.retrieveContributors(node)
            });
            self.next(result.links.next);
            self.displayedNodes(self.nodes().splice(0, 10));
            self.totalLoaded(self.displayedNodes().length)
        });
        promise.then(
            function(){
                if (self.next()) {
                    self.recursiveNodes(self.next())
                }
                else {
                    self.loadingComplete(true);
                    m.redraw()
                }
            }
        );

        // Recursively fetches remaining user's nodes
        self.recursiveNodes = function (url) {
            if (self.nodes().length > 0) {
                m.redraw()
            }
             var nextPromise = m.request({method: 'GET', url : url, config : xhrconfig, background : true});
                nextPromise.then(function(result){
                    result.data.forEach(function(node){
                        self.nodes().push(node);
                        self.retrieveContributors(node)
                    });
                    self.next(result.links.next);
                    console.log(self.next());
                    if (self.next()) {
                        self.recursiveNodes(self.next())
                    }
                    else {
                        self.loadingComplete(true);
                        m.redraw()
                    }
        })};

        self.retrieveContributors = function(node) {
            if (node.embeds.contributors.links.meta.total > 10) {
                self.pullOverTenContributorNames(node)
            }
            else {
                var contributors = node.embeds.contributors;
                self.mapNodeToContributors(node, contributors)
                }
        };

        self.pullOverTenContributorNames = function (node) {
            var url = $osf.apiV2Url('nodes/' + node.id + '/contributors/', { query : { 'page[size]': 1000 }});
            var promise = m.request({method: 'GET', url : url, config: xhrconfig, background : true});
            promise.then(function(result){
                self.mapNodeToContributors(node, result)
            })
        };

        self.mapNodeToContributors = function (node, contributors){
            var contributorList = [];
            contributors.data.forEach(function(contrib){
                fullName = contrib.embeds.users.data.attributes.full_name;
                contributorList.push(fullName)

            });
            self.contributorMapping[node.id] = contributorList
        };

        self.loadUpToTen = function () {
            var requested = self.nodes().splice(0, 10);
            for (var i = 0; i < requested.length; i++) {
                self.displayedNodes().push(requested[i])
            }
            self.countDisplayed(self.displayedNodes().length);
            return self.displayedNodes()
        };

        self.getFamilyName = function(i, node) {
            return node.embeds.contributors.data[i].embeds.users.data.attributes.family_name
        };

        self.getContributors = function (node) {
            var numContributors = node.embeds.contributors.links.meta.total;
            if (numContributors === 1) {
                return self.getFamilyName(0, node)
            }
            else if (numContributors === 2) {
                return self.getFamilyName(0, node) + ' and ' +
                    self.getFamilyName(1, node)
            }
            else if (numContributors === 3) {
                return self.getFamilyName(0, node) + ', ' +
                    self.getFamilyName(1, node) + ', and ' +
                    self.getFamilyName(2, node)
            }
            else {
                return self.getFamilyName(0, node) + ', ' +
                    self.getFamilyName(1, node) + ', ' +
                    self.getFamilyName(2, node) + ' + ' + (numContributors - 3)
            }

        };

        self.formatDate = function (node) {
            return new $osf.FormattableDate(node.attributes.date_modified).local
        };

        self.restoreToNodeList = function (missingNodes) {
            for (var i = 0; i < missingNodes.length ; i++) {
                self.nodes().push(missingNodes[i])
            }
        };

        self.sortAlphabeticalAscending = function () {
            self.nodes().sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.sortState('alphaAsc');
        };

        self.sortAlphabeticalDescending = function () {
            self.nodes().sort(function(a,b){
                var A = a.attributes.title.toUpperCase();
                var B = b.attributes.title.toUpperCase();
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.sortState('alphaDesc');
        };

        self.sortDateAscending = function () {
            self.nodes().sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A < B) ? -1 : (A > B) ? 1 : 0;
            });
            self.sortState('dateAsc')
        };

        self.sortDateDescending = function () {
            self.nodes().sort(function(a,b){
                var A = a.attributes.date_modified;
                var B = b.attributes.date_modified;
                return (A > B) ? -1 : (A < B) ? 1 : 0;
            });
            self.sortState('dateDesc');
        };

        self.sortBySortState = function () {
            if (self.sortState() === 'alphaAsc') {
                self.sortAlphabeticalAscending()
            }
            else if (self.sortState() === 'alphaDesc') {
                self.sortAlphabeticalDescending()
            }
            else if (self.sortState() === 'dateAsc') {
                self.sortDateAscending()
            }
            else {
                self.sortDateDescending()
            }
        };

        self.colorSortButtons = function () {
            var sortButtons = ['dateAsc', 'dateDesc', 'alphaAsc', 'alphaDesc']
            console.log(document.getElementById(self.sortState()));
            var button = document.getElementById(self.sortState()).className = 'selected';
            sortButtons.forEach(function(button) {
                console.log(button);
                if (self.sortState() !== button) {
                    console.log(document.getElementById(button));
                    document.getElementById(button).className = 'not-selected'
                }
            })
        };

        self.sortNodesAndModifyDisplay = function () {
            self.restoreToNodeList(self.displayedNodes());
            self.sortBySortState();
            self.colorSortButtons()
            self.displayedNodes(self.nodes().splice(0, self.countDisplayed()))
        };

        self.noTitleMatch = function (node) {
            return (node.attributes.title.toUpperCase().indexOf(self.filter().toUpperCase()) === -1);
        };

        self.noContributorMatch = function (node) {
            var contributors = self.contributorMapping[node.id];

            for (var c = 0; c < contributors.length; c++) {
                if (contributors[c].toUpperCase().indexOf(self.filter().toUpperCase()) !== -1){
                    return false
                }
            }
            return true
        };

        self.filterNodes = function (){
            for (var n = self.nodes().length - 1; n >= 0; n--) {
                var node = self.nodes()[n];
                if (self.noTitleMatch(node) && self.noContributorMatch(node)) {
                    self.nonMatchingNodes().push(node);
                    self.nodes().splice(n, 1)
                }
            }
        };

        self.mouseOver = function (node) {
            node.style.backgroundColor='#E0EBF3'
        };

        self.mouseOut = function (node) {
            node.style.backgroundColor='#fcfcfc'
        }

        self.quickSearch = function () {
            self.filter(document.getElementById('searchQuery').value);
            self.restoreToNodeList(self.nonMatchingNodes());
            self.restoreToNodeList(self.displayedNodes());
            self.displayedNodes([]);
            self.nonMatchingNodes([]);
            // if backspace completely, previous nodes with prior sorting/count will be displayed
            if (self.filter() === '') {
                self.sortNodesAndModifyDisplay();
                return self.displayedNodes()
            }
            else {
                self.filterNodes();
                self.sortBySortState();
                var numDisplay = Math.min(self.nodes().length, self.countDisplayed());
                for (var i = 0; i < numDisplay; i++) {
                    self.displayedNodes().push(self.nodes()[i])
                }
                self.nodes().splice(0, numDisplay);
                return self.displayedNodes()
            }

        };

    },
    view : function(ctrl) {
        function loadMoreButton() {
            if (ctrl.nodes().length !== 0){
                return m('button', {class: 'col-sm-12 text-muted', onclick: function() {
                        ctrl.loadUpToTen()}
                },
                m('i', {class: 'fa fa-caret-down load-nodes'}))
            }
        }

        function sortAlphaAsc() {
            if (ctrl.loadingComplete()) {
                return m('button', {id: 'alphaAsc', class: 'not-selected', onclick: function() {
                    ctrl.sortState('alphaAsc');
                    ctrl.sortNodesAndModifyDisplay();
                }},
                    m('i', {class: 'fa fa-angle-up'})
)
            }
        }

        function sortAlphaDesc(){
            if (ctrl.loadingComplete()){
                return m('button', {id: 'alphaDesc', class: 'not-selected', onclick: function() {
                    ctrl.sortState('alphaDesc');
                    ctrl.sortNodesAndModifyDisplay();
                }},
                m('i', {class: 'fa fa-angle-down'}))
            }
        }

        function sortDateAsc(){
            if (ctrl.loadingComplete()){
                 return m('button', {id: 'dateAsc', class: 'not-selected', onclick: function() {
                     ctrl.sortState('dateAsc');
                     ctrl.sortNodesAndModifyDisplay()}},
                 m('i', {class: 'fa fa-angle-up'}))
            }
        }
        function sortDateDesc(){
            if (ctrl.loadingComplete()){
                return m('button', {id: 'dateDesc', class: 'selected', onclick: function() {
                    ctrl.sortState('dateDesc');
                    ctrl.sortNodesAndModifyDisplay();
               }},
                m('i', {class: 'fa fa-angle-down'}))
            }
        }

        function searchBar() {
            if (ctrl.loadingComplete()){
                return m('div', {class : 'input-group'}, [
                    m('span', {class: 'input-group-addon'}, m('i', {class: 'fa fa-search'})),
                    m('input[type=search]', {class: 'form-control', id: 'searchQuery', placeholder: 'Quick search projects', onkeyup: function() {ctrl.quickSearch()}})
                ])
            }
        }

        function displayNodes() {
            if (ctrl.displayedNodes().length == 0 && ctrl.filter() != null) {
                return m('div', {class: 'row m-v-sm'}, m('div', {class: 'col-sm-10 col-sm-offset-1'},
                    m('div', {class: 'row'}, [
                        m('div', {class: 'col-sm-1'}),
                        m('div', {class: 'col-sm-11'},[m('p', {class :'fa fa-exclamation-triangle'}, m('em', '  No results found!'))])
                    ])
                ))
            }
            else {
                return ctrl.displayedNodes().map(function(n){
                    return projectView(n)
                })
            }
        }

        function projectView(project) {
            console.log('pending: ' + ctrl.nodes().length, ', displayed: ' + ctrl.displayedNodes().length, ', non-matching: ' + ctrl.nonMatchingNodes().length, ctrl.sortState());
            return m('div', {class: 'row m-v-sm'}, m('div', {class: 'col-sm-10 col-sm-offset-1'},
                m('div', {class: 'row node-styling',  onmouseover: function(){ctrl.mouseOver(this)}, onmouseout: function(){ctrl.mouseOut(this)}}, [
                    m('div', {class: 'col-sm-1 p-v-xs'}),
                    m('div', {class: 'col-sm-4 p-v-xs'}, m("a", {href: '/'+ project.id}, project.attributes.title)),
                    m('div', {class: 'col-sm-4 text-muted  p-v-xs'}, ctrl.getContributors(project)),
                    m('div', {class: 'col-sm-3 p-v-xs'}, ctrl.formatDate(project)),
                ])
            ))
        }

        function resultsFound(){
            return m('div', {class: 'container'}, [
                m('div', {class: 'row'}, [
                    m('div', {'class': 'col-sm-1'}),
                    m('div', {'class': 'col-sm-11'}, m('h3', 'My Projects'))
                ]),
                m('div', {class: 'row'},
                    m('div', {class: 'col-sm-3'}),
                    m('div', {class: 'col-sm-6 m-b-md text-center'}, [
                        searchBar(),
                        ctrl.loadingComplete() ? '' : m('.spinner-div', m('div', {class:'logo-spin logo-sm m-r-lg'}), 'Loading projects...')
                    ]),
                    m('div', {class: 'col-sm-3'})),

                m('div', {class: 'row'}, m('div', {class: 'col-sm-10 col-sm-offset-1'},
                m('div', {class: 'row'}, [
                    m('div', {class: 'col-sm-1 p-v-xs'}),
                    m('div', {class: 'col-sm-4 p-v-xs, f-w-xl'}, 'Title', sortAlphaAsc(), sortAlphaDesc()),
                    m('div', {class: 'col-sm-4 f-w-xl p-v-xs'}, 'Contributors'),
                    m('div', {class: 'col-sm-3 f-w-xl p-v-xs'}, 'Date Modified', sortDateAsc(), sortDateDesc()),
                ])
                )),

                displayNodes(),
                m('div', {class: 'row'}, [
                    m('div', {class: 'col-sm-5'}),
                    m('div', {class: 'col-sm-2'}, loadMoreButton()),
                    m('div', {class: 'col-sm-5'})
                ])
            ]);
        }

        if (ctrl.displayedNodes().length == 0 && ctrl.filter() == null) {
            return m('div', {class: 'container'}, [
                m('div', {class: 'row'}, [
                    m('div', {'class': 'col-sm-1'}),
                    m('div', {'class': 'col-sm-11'}, m('h3', 'My Projects'))
                ]),
                m('div', {class: 'row m-v-md'},
                    m('div', {class: 'col-sm-1'}),
                    m('div', {class: 'col-sm-11'}, m('h4', 'You have no projects. Go here to create one.'))
            )]
        )}
        else {
            return resultsFound()
        }
    }
};
module.exports = quickSearchProject;

<|endoftext|>


<commit_before>var valise = require( "valise" )
	, nconf = valise( "lib:config-util" ).nconf
	, _ = require( "underscore" )
	, trackers = nconf.get( "monitor" ).snapshot.trackers
	, logUtil = valise( "lib:log-util" )
	, getStatLogger = valise( "lib:trackers-util" ).getStatLogger
	;

exports.index = function( req, res ) {
	res.render( "snapshot/index", {
		trackers: trackers
	});
};

exports.trackerValue = function( req, res ) {
	// -----------------------------------------------------
	// Get the tracker value and send it
	// -----------------------------------------------------
	var trackerId = req.params.tracker
		, tracker = valise( "trackers:" + trackerId )
		, stats = tracker.getStats()
		, respObj = { data: [] }
		, startTime = new Date()
		, done
		;

	res.type( "application/json" );

	// -----------------------------------------------------
	// Run the tracker
	// -----------------------------------------------------
	tracker( function() {
		// -----------------------------------------------------
		// The resp obj
		// -----------------------------------------------------
		done = _.after( stats.length, function() {
			res.end( JSON.stringify( respObj ) );
		});

		// -----------------------------------------------------
		// For each of its exposed stats fetch a value
		// -----------------------------------------------------
		stats.forEach( function( statObj ) {
			getStatLogger( trackerId, statObj.id ).query({
					"from": startTime,
					"until": new Date()
				}, function( err, results ) {
					var logs = results.file
						, success = !err && logs.length
						;

					respObj.data.push({
						name: statObj.name,
						value: success ? logs[0].message : "N/A"
					});
					done();
				}
			);
		});
	});
};
<commit_msg>fixed snapshot for memmon.  Query by date wasn't working (seemingly because it ran too fast or because winston is fussy), but starting at -1 did.<commit_after>var valise = require( "valise" )
	, nconf = valise( "lib:config-util" ).nconf
	, _ = require( "underscore" )
	, trackers = nconf.get( "monitor" ).snapshot.trackers
	, logUtil = valise( "lib:log-util" )
	, getStatLogger = valise( "lib:trackers-util" ).getStatLogger
	;

exports.index = function( req, res ) {
	res.render( "snapshot/index", {
		trackers: trackers
	});
};

exports.trackerValue = function( req, res ) {
	// -----------------------------------------------------
	// Get the tracker value and send it
	// -----------------------------------------------------
	var trackerId = req.params.tracker
		, tracker = valise( "trackers:" + trackerId )
		, stats = tracker.getStats()
		, respObj = { data: [] }
		, done
		;

	res.type( "application/json" );

	// -----------------------------------------------------
	// Run the tracker
	// -----------------------------------------------------
	tracker( function() {
		// -----------------------------------------------------
		// The resp obj
		// -----------------------------------------------------
		done = _.after( stats.length, function() {
			res.end( JSON.stringify( respObj ) );
		});

		// -----------------------------------------------------
		// For each of its exposed stats fetch a value
		// -----------------------------------------------------
		stats.forEach( function( statObj ) {
			getStatLogger( trackerId, statObj.id ).query({
					start:-1
				}, function( err, results ) {
					var logs = results.file
						, success = !err && logs.length
						;

					respObj.data.push({
						name: statObj.name,
						value: success ? logs[0].message : "N/A"
					});
					done();
				}
			);
		});
	});
};
<|endoftext|>


<commit_before>import $ from 'jquery';
import Ember from 'ember';
import EmberError from '@ember/error';
import Service, {inject as service} from '@ember/service';
import {computed} from '@ember/object';
import {set} from '@ember/object';

export function feature(name, options = {}) {
    let {user, onChange} = options;
    let watchedProps = user ? [`accessibility.${name}`] : [`config.${name}`, `labs.${name}`];

    return computed.apply(Ember, watchedProps.concat({
        get() {
            let enabled = false;

            if (user) {
                enabled = this.get(`accessibility.${name}`);
            } else if (this.get(`config.${name}`)) {
                enabled = this.get(`config.${name}`);
            } else {
                enabled = this.get(`labs.${name}`) || false;
            }

            if (options.developer) {
                enabled = enabled && this.get('config.enableDeveloperExperiments');
            }

            return enabled;
        },
        set(key, value) {
            this.update(key, value, options);

            if (onChange) {
                // value must be passed here because the value isn't set until
                // the setter function returns
                this.get(onChange).bind(this)(value);
            }

            return value;
        }
    }));
}

export default Service.extend({
    store: service(),
    config: service(),
    session: service(),
    settings: service(),
    notifications: service(),
    lazyLoader: service(),

    emailAnalytics: feature('emailAnalytics'),
    nightShift: feature('nightShift', {user: true, onChange: '_setAdminTheme'}),
    multipleProducts: feature('multipleProducts'),
    oauthLogin: feature('oauthLogin', {developer: true}),
    customThemeSettings: feature('customThemeSettings'),
    membersActivity: feature('membersActivity', {developer: true}),
    cardSettingsPanel: feature('cardSettingsPanel', {developer: true}),
    membersAutoLogin: feature('membersAutoLogin', {developer: true}),
    urlCache: feature('urlCache', {developer: true}),
    mediaAPI: feature('mediaAPI', {developer: true}),
    filesAPI: feature('filesAPI', {developer: true}),
    calloutCard: feature('calloutCard', {developer: true}),
    nftCard: feature('nftCard', {developer: true}),
    accordionCard: feature('accordionCard', {developer: true}),
    fileCard: feature('fileCard', {developer: true}),
    audioCard: feature('audioCard', {developer: true}),
    videoCard: feature('videoCard', {developer: true}),
    productCard: feature('productCard', {developer: true}),
    quoteStyles: feature('quoteStyles', {developer: true}),

    _user: null,

    labs: computed('settings.labs', function () {
        let labs = this.get('settings.labs');

        try {
            return JSON.parse(labs) || {};
        } catch (e) {
            return {};
        }
    }),

    accessibility: computed('_user.accessibility', function () {
        let accessibility = this.get('_user.accessibility');

        try {
            return JSON.parse(accessibility) || {};
        } catch (e) {
            return {};
        }
    }),

    fetch() {
        return this.settings.fetch().then(() => {
            this.set('_user', this.session.user);
            return this._setAdminTheme().then(() => true);
        });
    },

    update(key, value, options = {}) {
        let serviceProperty = options.user ? 'accessibility' : 'labs';
        let model = this.get(options.user ? '_user' : 'settings');
        let featureObject = this.get(serviceProperty);

        // set the new key value for either the labs property or the accessibility property
        set(featureObject, key, value);

        if (options.requires && value === true) {
            options.requires.forEach((flag) => {
                set(featureObject, flag, true);
            });
        }

        // update the 'labs' or 'accessibility' key of the model
        model.set(serviceProperty, JSON.stringify(featureObject));

        return model.save().then(() => {
            // return the labs key value that we get from the server
            this.notifyPropertyChange(serviceProperty);
            return this.get(`${serviceProperty}.${key}`);
        }).catch((error) => {
            model.rollbackAttributes();
            this.notifyPropertyChange(serviceProperty);

            // we'll always have an errors object unless we hit a
            // validation error
            if (!error) {
                throw new EmberError(`Validation of the feature service ${options.user ? 'user' : 'settings'} model failed when updating ${serviceProperty}.`);
            }

            this.notifications.showAPIError(error);

            return this.get(`${serviceProperty}.${key}`);
        });
    },

    _setAdminTheme(enabled) {
        let nightShift = enabled;

        if (typeof nightShift === 'undefined') {
            nightShift = enabled || this.nightShift;
        }

        return this.lazyLoader.loadStyle('dark', 'assets/ghost-dark.css', true).then(() => {
            $('link[title=dark]').prop('disabled', !nightShift);
        }).catch(() => {
            //TODO: Also disable toggle from settings and Labs hover
            $('link[title=dark]').prop('disabled', true);
        });
    }
});
<commit_msg>Removed developer requirement from nftCard flag<commit_after>import $ from 'jquery';
import Ember from 'ember';
import EmberError from '@ember/error';
import Service, {inject as service} from '@ember/service';
import {computed} from '@ember/object';
import {set} from '@ember/object';

export function feature(name, options = {}) {
    let {user, onChange} = options;
    let watchedProps = user ? [`accessibility.${name}`] : [`config.${name}`, `labs.${name}`];

    return computed.apply(Ember, watchedProps.concat({
        get() {
            let enabled = false;

            if (user) {
                enabled = this.get(`accessibility.${name}`);
            } else if (this.get(`config.${name}`)) {
                enabled = this.get(`config.${name}`);
            } else {
                enabled = this.get(`labs.${name}`) || false;
            }

            if (options.developer) {
                enabled = enabled && this.get('config.enableDeveloperExperiments');
            }

            return enabled;
        },
        set(key, value) {
            this.update(key, value, options);

            if (onChange) {
                // value must be passed here because the value isn't set until
                // the setter function returns
                this.get(onChange).bind(this)(value);
            }

            return value;
        }
    }));
}

export default Service.extend({
    store: service(),
    config: service(),
    session: service(),
    settings: service(),
    notifications: service(),
    lazyLoader: service(),

    emailAnalytics: feature('emailAnalytics'),
    nightShift: feature('nightShift', {user: true, onChange: '_setAdminTheme'}),
    multipleProducts: feature('multipleProducts'),
    oauthLogin: feature('oauthLogin', {developer: true}),
    customThemeSettings: feature('customThemeSettings'),
    membersActivity: feature('membersActivity', {developer: true}),
    cardSettingsPanel: feature('cardSettingsPanel', {developer: true}),
    membersAutoLogin: feature('membersAutoLogin', {developer: true}),
    urlCache: feature('urlCache', {developer: true}),
    mediaAPI: feature('mediaAPI', {developer: true}),
    filesAPI: feature('filesAPI', {developer: true}),
    calloutCard: feature('calloutCard', {developer: true}),
    nftCard: feature('nftCard'),
    accordionCard: feature('accordionCard', {developer: true}),
    fileCard: feature('fileCard', {developer: true}),
    audioCard: feature('audioCard', {developer: true}),
    videoCard: feature('videoCard', {developer: true}),
    productCard: feature('productCard', {developer: true}),
    quoteStyles: feature('quoteStyles', {developer: true}),

    _user: null,

    labs: computed('settings.labs', function () {
        let labs = this.get('settings.labs');

        try {
            return JSON.parse(labs) || {};
        } catch (e) {
            return {};
        }
    }),

    accessibility: computed('_user.accessibility', function () {
        let accessibility = this.get('_user.accessibility');

        try {
            return JSON.parse(accessibility) || {};
        } catch (e) {
            return {};
        }
    }),

    fetch() {
        return this.settings.fetch().then(() => {
            this.set('_user', this.session.user);
            return this._setAdminTheme().then(() => true);
        });
    },

    update(key, value, options = {}) {
        let serviceProperty = options.user ? 'accessibility' : 'labs';
        let model = this.get(options.user ? '_user' : 'settings');
        let featureObject = this.get(serviceProperty);

        // set the new key value for either the labs property or the accessibility property
        set(featureObject, key, value);

        if (options.requires && value === true) {
            options.requires.forEach((flag) => {
                set(featureObject, flag, true);
            });
        }

        // update the 'labs' or 'accessibility' key of the model
        model.set(serviceProperty, JSON.stringify(featureObject));

        return model.save().then(() => {
            // return the labs key value that we get from the server
            this.notifyPropertyChange(serviceProperty);
            return this.get(`${serviceProperty}.${key}`);
        }).catch((error) => {
            model.rollbackAttributes();
            this.notifyPropertyChange(serviceProperty);

            // we'll always have an errors object unless we hit a
            // validation error
            if (!error) {
                throw new EmberError(`Validation of the feature service ${options.user ? 'user' : 'settings'} model failed when updating ${serviceProperty}.`);
            }

            this.notifications.showAPIError(error);

            return this.get(`${serviceProperty}.${key}`);
        });
    },

    _setAdminTheme(enabled) {
        let nightShift = enabled;

        if (typeof nightShift === 'undefined') {
            nightShift = enabled || this.nightShift;
        }

        return this.lazyLoader.loadStyle('dark', 'assets/ghost-dark.css', true).then(() => {
            $('link[title=dark]').prop('disabled', !nightShift);
        }).catch(() => {
            //TODO: Also disable toggle from settings and Labs hover
            $('link[title=dark]').prop('disabled', true);
        });
    }
});
<|endoftext|>


<commit_before>/* * * * * * * * * * * * * * * * * *
 * * * * *  gDiv Message * * * * * *
 need Bootstrap alert and some css:
 .withAlert {left: 15%; position: fixed !important; text-align: center; top: 55px; width: 70%; z-index: 5000;}
 * * * * * * * * * * * * * * * * * */
(function ($) {
    $.fn.gdivMessage = function (message, type, options) {
        var defaults = {autohide: true, hidetime: 4000};
        var opts = $.extend(defaults, options);
        var zindex = 5001, top = 40, alert_count = 1;
        if (!message) {
            message = 'Errore inaspettato. Scusate per il disagio. (Unexpected Error)';
        }
        if (!type) {
            type = 'warning';
        }

        alert_count = parseInt($(".withAlert").length);
        zindex = alert_count + 5001;
        top = alert_count * top;
        if (top > 100) {
            top = 100 + (alert_count * 3);
            if (top > 150) {
                top = 150;
            }
        }

        // qui creiamo il codice del alert
        var element = '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + message + '

';

        var eobj = $(element).clone();

        $(eobj).appendTo("body");
        if (opts.autohide) {
            setTimeout(function () {
                $(eobj).hide('slow', function () {
                    $(this).remove();
                });
            }, opts.hidetime);
        }
    };
})(jQuery);
$("body").on('click', ".withAlert .close", function () {
    $(this).parent().hide('slow', function () {
        $(this).remove();
    });
});
/* * * * ----- gDiv Message ----- * * */

/* jQuery plugins and other thing that need to be run after the document is load */
$(document).ready(function () {
    // this is for loader
    if ($(".loader-wrapper").length > 0) {
        $('#mainMenu a:not([target="_blank"]):not([href^=#]), a.animation-link').on("click", function () {
            // Grab the link's href
            var href = this.href;

            $(".loader").fadeIn(300);
            // Slide up the content you want to slide up
            $(".loader-wrapper").fadeIn(function () {
                // Slide is finished, navigate
                location.href = href;
            });

            // Prevent the default action of the link
            return false;
        });

        $(window).load(function () {
            $(".loader:not(.demo-loader)").fadeOut(200);
            $(".loader-wrapper:not(.demo-loader)").delay(100).fadeOut(400);
        });
    }

    /**
     * Form that need be send with Ajax and with CakePHP 3.x
     $(".ajaxform").on('submit', function(e){
        e.preventDefault();
        var area_code = $(this).data('areacode'), thisForm = $(this);

        $('input, select, textarea').parent().removeClass('has-error').find('.help-block').remove();

        $.ajax({
            url: $(this).attr('action'),
            method: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            success: function(json){
                if(json.success)
				{
                    $("body").gdivMessage(json.message, 'success');

					if($(thisForm).data('scallback').length > 0)
					{
						eval($(thisForm).data('scallback'));
					}
                } else {
                    $("body").gdivMessage(json.message, 'danger');

                    for(err in json.errors){
                        $('.form-'+err, $('#tab_'+area_code))
                            .after(''+ json.errors[err] +'')
                            .parent().addClass('has-error');
                    }

					if($(thisForm).data('ecallback').length > 0)
					{
						eval($(thisForm).data('ecallback'));
					}
                }
            },
            error: function(){
                $("body").gdivMessage();

				if($(thisForm).data('fcallback').length > 0)
				{
					eval($(thisForm).data('fcallback'));
				}
            }
        });

		//if($(thisForm).data('callback').length > 0)
		//{
		//	eval($(thisForm).data('callback'));
		//}

        return false;
    });*/

    /** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
     # # # # # # # hash-navigation # for bootstrap tabs # # # # # # # # #
     ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **/
    var hash = window.location.hash;
    if (hash.length > 0 && $('#hash-navigation').length > 0) {
        $('a[href=' + hash + ']').tab('show');
    }
    // # look for changes in navigation and add it to url
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        return location.hash = $(e.target).attr('href').substr(1);
    });
    /** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
     # # # # # # # # # # # hash-navigation # END # # # # # # # # # # # # #
     ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **/

    // #jQuery.plugin - bootstrap tooltips
    if ($().tooltip) {
        $('[data-toggle=tooltip]').tooltip();
    } // END - #jQuery.tooltip

    // #jQuery.plugin - selectize for list options
    if ($().selectize) {
        $('.selectize').selectize();
    } // END - #jQuery.selectize

    // #jQuery.plugin - bootstrap switch for radio button
    if ($().bootstrapSwitch) {
        $(".bootstrapSwitch").bootstrapSwitch();
    } // END - #jQuery.bootstrapSwitch

    // #jQuery.plugin - daterangepicker for date select
    if ($().daterangepicker) {
        var dtrp_locales = {
            "it": {
                "format": 'DD/MM/YYYY',
                "separator": " - ",
                "applyLabel": "Applica",
                "cancelLabel": "Annulla",
                "fromLabel": "Dal",
                "toLabel": "Al",
                "customRangeLabel": "Custom",
                "daysOfWeek": [
                    "Do",
                    "Lu",
                    "Ma",
                    "Me",
                    "Gi",
                    "Ve",
                    "Sa"
                ],
                "monthNames": [
                    "Gennaio",
                    "Febbraiio",
                    "Marzo",
                    "Aprile",
                    "Maggio",
                    "Giugno",
                    "Luglio",
                    "Agosto",
                    "Settembre",
                    "Ottobre",
                    "Novembre",
                    "Dicembre"
                ],
                "firstDay": 1
            },
            'fr': {
                "format": 'DD/MM/YYYY',
                "separator": " - ",
                "applyLabel": "Applica",
                "cancelLabel": "Annulla",
                "fromLabel": "Dal",
                "toLabel": "Al",
                "customRangeLabel": "Custom",
                "daysOfWeek": [
                    "Do",
                    "Lu",
                    "Ma",
                    "Me",
                    "Gi",
                    "Ve",
                    "Sa"
                ],
                "monthNames": [
                    "Gennaro",
                    "Febbraro",
                    "Mrco",
                    "April",
                    "Maj",
                    "Giugn",
                    "Lugl",
                    "Agost",
                    "Septembre",
                    "Ottober",
                    "Noveber",
                    "Dicember"
                ],
                "firstDay": 1
            }
        }, lang_code = $("html").attr('lang');
        // datepicker
        $('.withDatepicker').daterangepicker({
            locale: dtrp_locales[lang_code]
        });
    } // END - #jQuery.daterangepicker

    // #jQuery.plugin - Nicescroll
    if ($().niceScroll) {
        var nice = $("html").niceScroll({
            cursorcolor: "#ccc",
            cursorborder: "0px solid #fff",
            railpadding: {top: 0, right: 0, left: 0, bottom: 0},
            cursorwidth: "5px",
            cursorborderradius: "0px",
            cursoropacitymin: 0,
            cursoropacitymax: 0.7,
            boxzoom: true,
            horizrailenabled: false,
            autohidemode: false
        });

        $(".withNicescroll").niceScroll();
        $('html').addClass('no-overflow-y');
    } // END - jQuery.nicescroll

    /**
     * Add target highlight to something
     */
    $("body").on('click', '.targetLink', function () {
        var elem = $(this).data('target');
        $(elem).addClass('target');
        if ($(this).data('auto-close') != 'false') {
            var ac = parseInt($(this).data('auto-close'));
            if (ac == 0) {
                ac = 3500;
            }
            setTimeout(function () {
                $(elem).removeClass('target');
            }, ac);
        }
    });

    /**
     * START: Layout Go2Top
     */
    var LayoutGo2Top = function () {
        var handle = function () {
            var currentWindowPosition = $(window).scrollTop(); // current vertical position
            if (currentWindowPosition > 300) {
                $(".go2top").show();
            } else {
                $(".go2top").hide();
            }
        };

        return {
            //main function to initiate the module
            init: function () {
                handle(); // call headerFix() when the page was loaded
                if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
                    $(window).bind("touchend touchcancel touchleave", function (e) {
                        handle();
                    });
                } else {
                    $(window).scroll(function () {
                        handle();
                    });
                }

                $(".go2top").on('click', function (e) {
                    e.preventDefault();
                    $("html, body").animate({
                        scrollTop: 0
                    }, 600);
                });
            }
        };
    }();
    LayoutGo2Top.init();
    /** END: Layout Go2Top */

    // #jQuery.plugin - raty for a star rating view
    if ($().raty) {
        /**
         * Raty - https://github.com/wbotelhos/raty
         * with data API initialization from https://github.com/wbotelhos/raty/pull/168
         * get only the star type or set my prefered icon type and all others from data-api:
         *
         *
         */
        $('.getraty').each(function () {
            var startype = $(this).data('startype');
            if (typeof startype == 'undefined' || startype.length == 0)
                startype = 'i';
            $(this).raty({starType: startype});
        });
    } // END - #jQuery.raty

    /**
     * withBox
     * #showhide https://gist.github.com/arturmamedov/2bdfc3f69828ac37a7a1
     */
    $(".withBox").on('click', ".showhideBox", function () {
        var thisBox = $(this), parent = false;
        while (parent == false) {
            thisBox = thisBox.parent();
            if (thisBox.hasClass('withBox')) {
                parent = true;
            }
        }

        $(".shBox", thisBox).toggle(200);
        $(".shSwitch", thisBox).toggle(1, function () {
            if ($(this).hasClass('set'))
                $(this).removeClass('set');
            else
                $(this).addClass('set');
        });
    });
    // no close on himself click
    $(".withBox.collapsable").mouseup(function () {
        return false;
    });
    // close on document click
    $(document).mouseup(function () {
        $(".shBox", $(".withBox.collapsable")).slideUp();
        var shSwitch = $(".shSwitch", $(".withBox.collapsable"));
        if (shSwitch.hasClass('set'))
            shSwitch.toggle(1, function () {
                if ($(this).hasClass('set'))
                    $(this).removeClass('set');
                else
                    $(this).addClass('set');
            });
    });
});
<commit_msg>withPlugins - Bugfix alert_count counter was blocking at first alert.<commit_after>/* * * * * * * * * * * * * * * * * *
 * * * * *  gDiv Message * * * * * *
 need Bootstrap alert and some css:
 .withAlert {left: 15%; position: fixed !important; text-align: center; top: 55px; width: 70%; z-index: 5000;}
 * * * * * * * * * * * * * * * * * */
(function ($) {
    $.fn.gdivMessage = function (message, type, options) {
        var defaults = {autohide: true, hidetime: 4000};
        var opts = $.extend(defaults, options);
        var zindex = 5001, top = 40, alert_count = 1;
        if (!message) {
            message = 'Errore inaspettato. Scusate per il disagio. (Unexpected Error)';
        }
        if (!type) {
            type = 'warning';
        }

        _alert_count = parseInt($(".withAlert").length);
        if (_alert_count > 0) {
            alert_count = _alert_count;
        }
        zindex = alert_count + 5001;
        top = alert_count * top;
        if (top > 100) {
            top = 100 + (alert_count * 3);
            if (top > 150) {
                top = 150;
            }
        }

        // qui creiamo il codice del alert
        var element = '
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + message + '

';

        var eobj = $(element).clone();

        $(eobj).appendTo("body");
        if (opts.autohide) {
            setTimeout(function () {
                $(eobj).hide('slow', function () {
                    $(this).remove();
                });
            }, opts.hidetime);
        }
    };
})(jQuery);
$("body").on('click', ".withAlert .close", function () {
    $(this).parent().hide('slow', function () {
        $(this).remove();
    });
});
/* * * * ----- gDiv Message ----- * * */

/* jQuery plugins and other thing that need to be run after the document is load */
$(document).ready(function () {
    // this is for loader
    if ($(".loader-wrapper").length > 0) {
        $('#mainMenu a:not([target="_blank"]):not([href^=#]), a.animation-link').on("click", function () {
            // Grab the link's href
            var href = this.href;

            $(".loader").fadeIn(300);
            // Slide up the content you want to slide up
            $(".loader-wrapper").fadeIn(function () {
                // Slide is finished, navigate
                location.href = href;
            });

            // Prevent the default action of the link
            return false;
        });

        $(window).load(function () {
            $(".loader:not(.demo-loader)").fadeOut(200);
            $(".loader-wrapper:not(.demo-loader)").delay(100).fadeOut(400);
        });
    }

    /**
     * Form that need be send with Ajax and with CakePHP 3.x
     $(".ajaxform").on('submit', function(e){
        e.preventDefault();
        var area_code = $(this).data('areacode'), thisForm = $(this);

        $('input, select, textarea').parent().removeClass('has-error').find('.help-block').remove();

        $.ajax({
            url: $(this).attr('action'),
            method: 'POST',
            dataType: 'json',
            data: $(this).serialize(),
            success: function(json){
                if(json.success)
				{
                    $("body").gdivMessage(json.message, 'success');

					if($(thisForm).data('scallback').length > 0)
					{
						eval($(thisForm).data('scallback'));
					}
                } else {
                    $("body").gdivMessage(json.message, 'danger');

                    for(err in json.errors){
                        $('.form-'+err, $('#tab_'+area_code))
                            .after(''+ json.errors[err] +'')
                            .parent().addClass('has-error');
                    }

					if($(thisForm).data('ecallback').length > 0)
					{
						eval($(thisForm).data('ecallback'));
					}
                }
            },
            error: function(){
                $("body").gdivMessage();

				if($(thisForm).data('fcallback').length > 0)
				{
					eval($(thisForm).data('fcallback'));
				}
            }
        });

		//if($(thisForm).data('callback').length > 0)
		//{
		//	eval($(thisForm).data('callback'));
		//}

        return false;
    });*/

    /** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
     # # # # # # # hash-navigation # for bootstrap tabs # # # # # # # # #
     ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **/
    var hash = window.location.hash;
    if (hash.length > 0 && $('#hash-navigation').length > 0) {
        $('a[href=' + hash + ']').tab('show');
    }
    // # look for changes in navigation and add it to url
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        return location.hash = $(e.target).attr('href').substr(1);
    });
    /** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
     # # # # # # # # # # # hash-navigation # END # # # # # # # # # # # # #
     ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **/

    // #jQuery.plugin - bootstrap tooltips
    if ($().tooltip) {
        $('[data-toggle=tooltip]').tooltip();
    } // END - #jQuery.tooltip

    // #jQuery.plugin - selectize for list options
    if ($().selectize) {
        $('.selectize').selectize();
    } // END - #jQuery.selectize

    // #jQuery.plugin - bootstrap switch for radio button
    if ($().bootstrapSwitch) {
        $(".bootstrapSwitch").bootstrapSwitch();
    } // END - #jQuery.bootstrapSwitch

    // #jQuery.plugin - daterangepicker for date select
    if ($().daterangepicker) {
        var dtrp_locales = {
            "it": {
                "format": 'DD/MM/YYYY',
                "separator": " - ",
                "applyLabel": "Applica",
                "cancelLabel": "Annulla",
                "fromLabel": "Dal",
                "toLabel": "Al",
                "customRangeLabel": "Custom",
                "daysOfWeek": [
                    "Do",
                    "Lu",
                    "Ma",
                    "Me",
                    "Gi",
                    "Ve",
                    "Sa"
                ],
                "monthNames": [
                    "Gennaio",
                    "Febbraiio",
                    "Marzo",
                    "Aprile",
                    "Maggio",
                    "Giugno",
                    "Luglio",
                    "Agosto",
                    "Settembre",
                    "Ottobre",
                    "Novembre",
                    "Dicembre"
                ],
                "firstDay": 1
            },
            'fr': {
                "format": 'DD/MM/YYYY',
                "separator": " - ",
                "applyLabel": "Applica",
                "cancelLabel": "Annulla",
                "fromLabel": "Dal",
                "toLabel": "Al",
                "customRangeLabel": "Custom",
                "daysOfWeek": [
                    "Do",
                    "Lu",
                    "Ma",
                    "Me",
                    "Gi",
                    "Ve",
                    "Sa"
                ],
                "monthNames": [
                    "Gennaro",
                    "Febbraro",
                    "Mrco",
                    "April",
                    "Maj",
                    "Giugn",
                    "Lugl",
                    "Agost",
                    "Septembre",
                    "Ottober",
                    "Noveber",
                    "Dicember"
                ],
                "firstDay": 1
            }
        }, lang_code = $("html").attr('lang');
        // datepicker
        $('.withDatepicker').daterangepicker({
            locale: dtrp_locales[lang_code]
        });
    } // END - #jQuery.daterangepicker

    // #jQuery.plugin - Nicescroll
    if ($().niceScroll) {
        var nice = $("html").niceScroll({
            cursorcolor: "#ccc",
            cursorborder: "0px solid #fff",
            railpadding: {top: 0, right: 0, left: 0, bottom: 0},
            cursorwidth: "5px",
            cursorborderradius: "0px",
            cursoropacitymin: 0,
            cursoropacitymax: 0.7,
            boxzoom: true,
            horizrailenabled: false,
            autohidemode: false
        });

        $(".withNicescroll").niceScroll();
        $('html').addClass('no-overflow-y');
    } // END - jQuery.nicescroll

    /**
     * Add target highlight to something
     */
    $("body").on('click', '.targetLink', function () {
        var elem = $(this).data('target');
        $(elem).addClass('target');
        if ($(this).data('auto-close') != 'false') {
            var ac = parseInt($(this).data('auto-close'));
            if (ac == 0) {
                ac = 3500;
            }
            setTimeout(function () {
                $(elem).removeClass('target');
            }, ac);
        }
    });

    /**
     * START: Layout Go2Top
     */
    var LayoutGo2Top = function () {
        var handle = function () {
            var currentWindowPosition = $(window).scrollTop(); // current vertical position
            if (currentWindowPosition > 300) {
                $(".go2top").show();
            } else {
                $(".go2top").hide();
            }
        };

        return {
            //main function to initiate the module
            init: function () {
                handle(); // call headerFix() when the page was loaded
                if (navigator.userAgent.match(/iPhone|iPad|iPod/i)) {
                    $(window).bind("touchend touchcancel touchleave", function (e) {
                        handle();
                    });
                } else {
                    $(window).scroll(function () {
                        handle();
                    });
                }

                $(".go2top").on('click', function (e) {
                    e.preventDefault();
                    $("html, body").animate({
                        scrollTop: 0
                    }, 600);
                });
            }
        };
    }();
    LayoutGo2Top.init();
    /** END: Layout Go2Top */

    // #jQuery.plugin - raty for a star rating view
    if ($().raty) {
        /**
         * Raty - https://github.com/wbotelhos/raty
         * with data API initialization from https://github.com/wbotelhos/raty/pull/168
         * get only the star type or set my prefered icon type and all others from data-api:
         *
         *
         */
        $('.getraty').each(function () {
            var startype = $(this).data('startype');
            if (typeof startype == 'undefined' || startype.length == 0)
                startype = 'i';
            $(this).raty({starType: startype});
        });
    } // END - #jQuery.raty

    /**
     * withBox
     * #showhide https://gist.github.com/arturmamedov/2bdfc3f69828ac37a7a1
     */
    $(".withBox").on('click', ".showhideBox", function () {
        var thisBox = $(this), parent = false;
        while (parent == false) {
            thisBox = thisBox.parent();
            if (thisBox.hasClass('withBox')) {
                parent = true;
            }
        }

        $(".shBox", thisBox).toggle(200);
        $(".shSwitch", thisBox).toggle(1, function () {
            if ($(this).hasClass('set'))
                $(this).removeClass('set');
            else
                $(this).addClass('set');
        });
    });
    // no close on himself click
    $(".withBox.collapsable").mouseup(function () {
        return false;
    });
    // close on document click
    $(document).mouseup(function () {
        $(".shBox", $(".withBox.collapsable")).slideUp();
        var shSwitch = $(".shSwitch", $(".withBox.collapsable"));
        if (shSwitch.hasClass('set'))
            shSwitch.toggle(1, function () {
                if ($(this).hasClass('set'))
                    $(this).removeClass('set');
                else
                    $(this).addClass('set');
            });
    });
});
<|endoftext|>


<commit_before>define(function (require) {

	var Utils = {

		CreateShape: function (root, s, resourceManager,charId,ObjectId,placeAfter,transform)
		{
			var pathContainer = s.g();
			pathContainer.attr({token: parseInt(ObjectId)});

			for(var k =0;k<resourceManager.m_data.DOMDocument.Shape.length;k++)
			{
				if(resourceManager.m_data.DOMDocument.Shape[k].charid == charId)
				{
					for(var j=0;j<resourceManager.m_data.DOMDocument.Shape[k].path.length;j++)
					{
						var clr,clrOpacity;
						var shape1 = s.path();
						var path = resourceManager.m_data.DOMDocument.Shape[k].path[j].d;
						shape1.attr({fill: 'transparent'});
						shape1.attr({d: path});

						if(resourceManager.m_data.DOMDocument.Shape[k].path[j].pathType == "Fill")
						{
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].color)
							{
								clr = resourceManager.m_data.DOMDocument.Shape[k].path[j].color;
		                        var r = parseInt(clr.substring(1, 3), 16);
		                        var g = parseInt(clr.substring(3, 5), 16);
		                        var b = parseInt(clr.substring(5, 7), 16);
		                        var colStr = 'rgba(' + r + ',' + g + ',' + b + ',' + resourceManager.m_data.DOMDocument.Shape[k].path[j].colorOpacity + ')';
								shape1.attr({fill: colStr});
							}
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].image)
							{
								var patternArray = resourceManager.m_data.DOMDocument.Shape[k].path[j].image.patternTransform.split(",");
								var p = 0;
								var mat = new Snap.Matrix(patternArray[p],patternArray[p+1],patternArray[p+1],patternArray[p+3],patternArray[p+4],patternArray[p+5]);
								var src = resourceManager.m_data.DOMDocument.Shape[k].path[j].image.bitmapPath;

								function newPattern() {
									var image = s.image(src);
									var pattern = image.pattern(0, 0, resourceManager.m_data.DOMDocument.Shape[k].path[j].image.width, resourceManager.m_data.DOMDocument.Shape[k].path[j].image.height);
									pattern.attr({x: mat.e, y: mat.f});
									shape1.attr({fill: pattern});
								}

								var exists = root.select('defs pattern image');

								if (exists) {
									if (exists.attr('href') == src) {	//check if image href matches as well as other props
										shape1.attr({fill: exists.parent()});
									} else {
										newPattern();
									}
								} else {
									newPattern();
								}

							}
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient)
							{
								var _x = parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.x1);
								var _y = parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.y1);
								var _x2 = parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.x2);
								var _y2 = parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.y2);
								var gradientString = "L(";
								gradientString += _x + ", ";
								gradientString += _y + ", ";
								gradientString += _x2 + ", ";
								gradientString += _y2 + ")";

								for(var i=0; i<resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop.length; i++)
								{
									gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop[i].stopColor;
									gradientString += ":";
									gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop[i].offset;
									if (i !== resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop.length-1) {
										gradientString += "-";
									}
								}
								var _g = root.gradient(gradientString);
								shape1.attr({fill: _g});
							}

							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient)
							{
								var _x = (shape1.getBBox().x + shape1.getBBox().width / 2) + resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.cx / 10;
								var _y = (shape1.getBBox().y + shape1.getBBox().height / 2) + resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.cy / 10;
								var _fx = (shape1.getBBox().x + shape1.getBBox().width / 2) + parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.fx);
								var _fy = (shape1.getBBox().y + shape1.getBBox().height / 2) + parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.fy);

								var gradientString = "R(";
								gradientString += _x + ", ";
								gradientString += _y + ", ";
								gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.r + ", ";
								gradientString += _fx + ", ";
								gradientString += _fy + ")";

								for(var i=0; i<resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.stop.length; i++)
								{
									gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.stop[i].stopColor;
									gradientString += ":";
									gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.stop[i].offset;
									if (i !== resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.stop.length-1) {
										gradientString += "-";
									}
								}

								var _g = root.gradient(gradientString);
								shape1.attr({fill: _g});
							}
						}
						else if(resourceManager.m_data.DOMDocument.Shape[k].path[j].pathType == "Stroke")
						{
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].color)
							{
								clr = resourceManager.m_data.DOMDocument.Shape[k].path[j].color;

		                        var r = parseInt(clr.substring(1, 3), 16);
		                        var g = parseInt(clr.substring(3, 5), 16);
		                        var b = parseInt(clr.substring(5, 7), 16);

		                        var colStr = 'rgba(' + r + ',' + g + ',' + b + ',' + resourceManager.m_data.DOMDocument.Shape[k].path[j].colorOpacity + ')';

								shape1.attr({stroke: colStr, strokeWidth: resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeWidth});
							}
							/*
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].image)
							{
								var patternArray = resourceManager.m_data.DOMDocument.Shape[k].path[j].image.patternTransform.split(",");
								var p = 0;
								var mat = new createjs.Matrix2D(patternArray[p],patternArray[p+1],patternArray[p+1],patternArray[p+3],patternArray[p+4],patternArray[p+5]);
								var image = new Image();
								image.src = resourceManager.m_data.DOMDocument.Shape[k].path[j].image.bitmapPath;
								shape1.graphics.beginBitmapStroke(image,"no-repeat").beginStroke().setStrokeStyle(data.DOMDocument.Shape[k].path[j].strokeWidth,resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeLinecap,resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeLinejoin);
							}
							*/
							/*
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient)
							{
								var stopArray = new Array();
								var offSetArray = new Array();
								for(var s=0;s<resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop.length;s++)
								{
									stopArray[s] = resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop[s].stopColor;
									offSetArray[s] = resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop[s].offset/100;
								}
								shape1.graphics.ls(stopArray,offSetArray,resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.x1,resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.y1,resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.x2,resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.y2).setStrokeStyle(resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeWidth,resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeLinecap,resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeLinejoin);;
							}
							*/
						}
						//var path = resourceManager.m_data.DOMDocument.Shape[k].path[j].d;
						//shape1.attr({d: path});
						pathContainer.add(shape1);
					}
				}
			}

			var transformArray = transform.split(",");
			var TransformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);

			pathContainer.transform(TransformMat.toTransformString());

			if(s != undefined)
			{
				if(placeAfter != 0)
				{
					children = s.selectAll('[token="' + placeAfter + '"]');
					for (i = 0; i < children.length; i += 1) {
						if (children[i].parent().id == s.id) { //ensure child of current movie clip
							children[i].before(pathContainer);
							break;
						}
					}
				}
				else
				{
					s.add(pathContainer);
				}

			}
		},

		CreateBitmap: function(root, s,resourceManager,charId,ObjectId,placeAfter,transform)
		{

		var bmContainer = s.g();
		bmContainer.attr({token: parseInt(ObjectId)});

		for(var b =0;b<resourceManager.m_data.DOMDocument.Bitmaps.length;b++)
			{
				if(resourceManager.m_data.DOMDocument.Bitmaps[b].charid == charId)
				{
					var path = resourceManager.m_data.DOMDocument.Bitmaps[b].bitmapPath;
					var bitmap = s.image(path);
				}
				bmContainer.add(bitmap);
			}

			var transformArray = transform.split(",");
			var TransformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);
			bmContainer.transform(TransformMat.toTransformString());

			if(s != undefined)
			{
				if(placeAfter != 0)
				{
					children = s.selectAll('[token="' + placeAfter + '"]');
					for (i = 0; i < children.length; i += 1) {
						if (children[i].parent().id == s.id) { //ensure child of current movie clip
							children[i].before(bmContainer);
							break;
						}
					}
				}
				else
				{
					s.add(bmContainer);
				}
				/*
				while(parentMC.mode != undefined)
				{
					parentMC.getStage();
					parentMC = parentMC.parent;
				}

				parentMC.update();
				*/
			}
			/*
			else
			{
				s.add(bmContainer);
				//stage.update();
			}
			*/
		},

		CreateText: function (root, s,resourceManager,charId,ObjectId,placeAfter,transform)
		{
			var textContainer = s.g();
			textContainer.attr({token: parseInt(ObjectId)});

			for(var b =0;b<resourceManager.m_data.DOMDocument.Text.length;b++)
			{
				if(resourceManager.m_data.DOMDocument.Text[b].charid == charId)
				{
					var displayString = resourceManager.m_data.DOMDocument.Text[b].displayText;
					var txt = displayString.replace(/\\r/g,"\r");
					var font = resourceManager.m_data.DOMDocument.Text[b].font;
					var fontArray = font.split(' ', 2);
					var fontStyle = fontArray[0];
					var fontSize = fontArray[1];
					var fontFamily = /\'(.*?)\'/.exec(font)[1];
					var fontColor = resourceManager.m_data.DOMDocument.Text[b].color;
					var textOutput = s.text(0, 0, txt);
					textOutput.attr({
						fill: fontColor,
						fontFamily:
						fontFamily,
						fontSize: fontSize,
						fontStyle: fontStyle
					});

					console.log(resourceManager.m_data.DOMDocument.Text[b]);
					textContainer.add(textOutput);
				}
			}

			var transformArray = transform.split(",");
			var TransformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);
			textContainer.transform(TransformMat.toTransformString());

			if(s != undefined)
			{
				if(placeAfter != 0)
				{
					children = s.selectAll('[token="' + placeAfter + '"]');
					for (i = 0; i < children.length; i += 1) {
						if (children[i].parent().id == s.id) { //ensure child of current movie clip
							children[i].before(textContainer);
							break;
						}
					}
				}
				else
				{
					s.add(textContainer);
				}
				/*
				while(s.mode != undefined)
				{
					parentMC.getStage();
					parentMC = parentMC.parent;
				}

				parentMC.update();
				*/
			}
			/*
			else
			{
				stage.addChildAt(textOutput);
				stage.update();
			}
			*/
		}

	}

	return Utils;
});<commit_msg>update text with working layout<commit_after>define(function (require) {

	var Utils = {

		CreateShape: function (root, s, resourceManager,charId,ObjectId,placeAfter,transform)
		{
			var pathContainer = s.g();
			pathContainer.attr({token: parseInt(ObjectId)});

			for(var k =0;k<resourceManager.m_data.DOMDocument.Shape.length;k++)
			{
				if(resourceManager.m_data.DOMDocument.Shape[k].charid == charId)
				{
					for(var j=0;j<resourceManager.m_data.DOMDocument.Shape[k].path.length;j++)
					{
						var clr,clrOpacity;
						var shape1 = s.path();
						var path = resourceManager.m_data.DOMDocument.Shape[k].path[j].d;
						shape1.attr({fill: 'transparent'});
						shape1.attr({d: path});

						if(resourceManager.m_data.DOMDocument.Shape[k].path[j].pathType == "Fill")
						{
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].color)
							{
								clr = resourceManager.m_data.DOMDocument.Shape[k].path[j].color;
		                        var r = parseInt(clr.substring(1, 3), 16);
		                        var g = parseInt(clr.substring(3, 5), 16);
		                        var b = parseInt(clr.substring(5, 7), 16);
		                        var colStr = 'rgba(' + r + ',' + g + ',' + b + ',' + resourceManager.m_data.DOMDocument.Shape[k].path[j].colorOpacity + ')';
								shape1.attr({fill: colStr});
							}
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].image)
							{
								var patternArray = resourceManager.m_data.DOMDocument.Shape[k].path[j].image.patternTransform.split(",");
								var p = 0;
								var mat = new Snap.Matrix(patternArray[p],patternArray[p+1],patternArray[p+1],patternArray[p+3],patternArray[p+4],patternArray[p+5]);
								var src = resourceManager.m_data.DOMDocument.Shape[k].path[j].image.bitmapPath;

								function newPattern() {
									var image = s.image(src);
									var pattern = image.pattern(0, 0, resourceManager.m_data.DOMDocument.Shape[k].path[j].image.width, resourceManager.m_data.DOMDocument.Shape[k].path[j].image.height);
									pattern.attr({x: mat.e, y: mat.f});
									shape1.attr({fill: pattern});
								}

								var exists = root.select('defs pattern image');

								if (exists) {
									if (exists.attr('href') == src) {	//check if image href matches as well as other props
										shape1.attr({fill: exists.parent()});
									} else {
										newPattern();
									}
								} else {
									newPattern();
								}

							}
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient)
							{
								var _x = parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.x1);
								var _y = parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.y1);
								var _x2 = parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.x2);
								var _y2 = parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.y2);
								var gradientString = "L(";
								gradientString += _x + ", ";
								gradientString += _y + ", ";
								gradientString += _x2 + ", ";
								gradientString += _y2 + ")";

								for(var i=0; i<resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop.length; i++)
								{
									gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop[i].stopColor;
									gradientString += ":";
									gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop[i].offset;
									if (i !== resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop.length-1) {
										gradientString += "-";
									}
								}
								var _g = root.gradient(gradientString);
								shape1.attr({fill: _g});
							}

							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient)
							{
								var _x = (shape1.getBBox().x + shape1.getBBox().width / 2) + resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.cx / 10;
								var _y = (shape1.getBBox().y + shape1.getBBox().height / 2) + resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.cy / 10;
								var _fx = (shape1.getBBox().x + shape1.getBBox().width / 2) + parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.fx);
								var _fy = (shape1.getBBox().y + shape1.getBBox().height / 2) + parseFloat(resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.fy);

								var gradientString = "R(";
								gradientString += _x + ", ";
								gradientString += _y + ", ";
								gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.r + ", ";
								gradientString += _fx + ", ";
								gradientString += _fy + ")";

								for(var i=0; i<resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.stop.length; i++)
								{
									gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.stop[i].stopColor;
									gradientString += ":";
									gradientString += resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.stop[i].offset;
									if (i !== resourceManager.m_data.DOMDocument.Shape[k].path[j].radialGradient.stop.length-1) {
										gradientString += "-";
									}
								}

								var _g = root.gradient(gradientString);
								shape1.attr({fill: _g});
							}
						}
						else if(resourceManager.m_data.DOMDocument.Shape[k].path[j].pathType == "Stroke")
						{
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].color)
							{
								clr = resourceManager.m_data.DOMDocument.Shape[k].path[j].color;

		                        var r = parseInt(clr.substring(1, 3), 16);
		                        var g = parseInt(clr.substring(3, 5), 16);
		                        var b = parseInt(clr.substring(5, 7), 16);

		                        var colStr = 'rgba(' + r + ',' + g + ',' + b + ',' + resourceManager.m_data.DOMDocument.Shape[k].path[j].colorOpacity + ')';

								shape1.attr({stroke: colStr, strokeWidth: resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeWidth});
							}
							/*
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].image)
							{
								var patternArray = resourceManager.m_data.DOMDocument.Shape[k].path[j].image.patternTransform.split(",");
								var p = 0;
								var mat = new createjs.Matrix2D(patternArray[p],patternArray[p+1],patternArray[p+1],patternArray[p+3],patternArray[p+4],patternArray[p+5]);
								var image = new Image();
								image.src = resourceManager.m_data.DOMDocument.Shape[k].path[j].image.bitmapPath;
								shape1.graphics.beginBitmapStroke(image,"no-repeat").beginStroke().setStrokeStyle(data.DOMDocument.Shape[k].path[j].strokeWidth,resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeLinecap,resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeLinejoin);
							}
							*/
							/*
							if(resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient)
							{
								var stopArray = new Array();
								var offSetArray = new Array();
								for(var s=0;s<resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop.length;s++)
								{
									stopArray[s] = resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop[s].stopColor;
									offSetArray[s] = resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.stop[s].offset/100;
								}
								shape1.graphics.ls(stopArray,offSetArray,resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.x1,resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.y1,resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.x2,resourceManager.m_data.DOMDocument.Shape[k].path[j].linearGradient.y2).setStrokeStyle(resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeWidth,resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeLinecap,resourceManager.m_data.DOMDocument.Shape[k].path[j].strokeLinejoin);;
							}
							*/
						}
						//var path = resourceManager.m_data.DOMDocument.Shape[k].path[j].d;
						//shape1.attr({d: path});
						pathContainer.add(shape1);
					}
				}
			}

			var transformArray = transform.split(",");
			var TransformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);

			pathContainer.transform(TransformMat.toTransformString());

			if(s != undefined)
			{
				if(placeAfter != 0)
				{
					children = s.selectAll('[token="' + placeAfter + '"]');
					for (i = 0; i < children.length; i += 1) {
						if (children[i].parent().id == s.id) { //ensure child of current movie clip
							children[i].before(pathContainer);
							break;
						}
					}
				}
				else
				{
					s.add(pathContainer);
				}

			}
		},

		CreateBitmap: function(root, s,resourceManager,charId,ObjectId,placeAfter,transform)
		{

		var bmContainer = s.g();
		bmContainer.attr({token: parseInt(ObjectId)});

		for(var b =0;b<resourceManager.m_data.DOMDocument.Bitmaps.length;b++)
			{
				if(resourceManager.m_data.DOMDocument.Bitmaps[b].charid == charId)
				{
					var path = resourceManager.m_data.DOMDocument.Bitmaps[b].bitmapPath;
					var bitmap = s.image(path);
				}
				bmContainer.add(bitmap);
			}

			var transformArray = transform.split(",");
			var TransformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);
			bmContainer.transform(TransformMat.toTransformString());

			if(s != undefined)
			{
				if(placeAfter != 0)
				{
					children = s.selectAll('[token="' + placeAfter + '"]');
					for (i = 0; i < children.length; i += 1) {
						if (children[i].parent().id == s.id) { //ensure child of current movie clip
							children[i].before(bmContainer);
							break;
						}
					}
				}
				else
				{
					s.add(bmContainer);
				}
				/*
				while(parentMC.mode != undefined)
				{
					parentMC.getStage();
					parentMC = parentMC.parent;
				}

				parentMC.update();
				*/
			}
			/*
			else
			{
				s.add(bmContainer);
				//stage.update();
			}
			*/
		},

		CreateText: function (root, s,resourceManager,charId,ObjectId,placeAfter,transform)
		{
			var textContainer = s.g();
			textContainer.attr({token: parseInt(ObjectId)});

			for(var b =0;b<resourceManager.m_data.DOMDocument.Text.length;b++)
			{
				if(resourceManager.m_data.DOMDocument.Text[b].charid == charId)
				{
					var displayString = resourceManager.m_data.DOMDocument.Text[b].txt;
					var txt = displayString.replace(/\\r/g,"\r");
					var fontFamily = resourceManager.m_data.DOMDocument.Text[b].paras[0].textRun[0].style.fontName;
					var fontStyle = resourceManager.m_data.DOMDocument.Text[b].paras[0].textRun[0].style.fontStyle;
					var fontSize = resourceManager.m_data.DOMDocument.Text[b].paras[0].textRun[0].style.fontSize;
					var fontColor = resourceManager.m_data.DOMDocument.Text[b].paras[0].textRun[0].style.fontColor;
					var textOutput = s.text(0, 0, txt);
					textOutput.attr({
						fill: fontColor,
						fontFamily: fontFamily,
						fontSize: fontSize,
						fontStyle: fontStyle
					});

					textContainer.add(textOutput);
				}
			}

			var transformArray = transform.split(",");
			var TransformMat = new Snap.Matrix(transformArray[0],transformArray[1],transformArray[2],transformArray[3],transformArray[4],transformArray[5]);
			textContainer.transform(TransformMat.toTransformString());

			if(s != undefined)
			{
				if(placeAfter != 0)
				{
					children = s.selectAll('[token="' + placeAfter + '"]');
					for (i = 0; i < children.length; i += 1) {
						if (children[i].parent().id == s.id) { //ensure child of current movie clip
							children[i].before(textContainer);
							break;
						}
					}
				}
				else
				{
					s.add(textContainer);
				}
				/*
				while(s.mode != undefined)
				{
					parentMC.getStage();
					parentMC = parentMC.parent;
				}

				parentMC.update();
				*/
			}
			/*
			else
			{
				stage.addChildAt(textOutput);
				stage.update();
			}
			*/
		}

	}

	return Utils;
});<|endoftext|>


<commit_before>module.exports = function (wallaby) {
    return {
        debug: true,
        files: [
            'src/**/*.js',
            { pattern: 'test/fixtures/**/*', instrument: true, load: false },
            { pattern: 'test/**/*.js', ignore: true }
        ],

        tests: [
            'test/**/*.js'
        ],

        compilers: {
            '**/*.js': wallaby.compilers.babel()
        },

        env: {
            type: 'node'
        }
    }
}
<commit_msg>Updated wallaby config<commit_after>module.exports = function (wallaby) {
    return {
        debug: true,
        files: [
            'src/**/*.js',
            'test/**/*',
            { pattern: 'test/**/*.js', ignore: true }
        ],

        tests: [
            'test/**/*.js'
        ],

        compilers: {
            '**/*.js': wallaby.compilers.babel()
        },

        env: {
            type: 'node'
        }
    }
}
<|endoftext|>