<commit_before>
// <<<<<<<<<<<<<<<<<   http://plnkr.co/edit/V5alqOODGmnLbKiK2YY7?p=preview  >>>>>>>>>>>>>>>>>>

(function() {
    "use strict";

    console.log('SPACtrl setup');
    define(['angular', 'lib/fsm', 'lib/utils'], function(angular, finstatmach, utils) {
        console.log('SPACtrl define');

        function SPACtrl($scope) {
            console.debug('SPACtrl - initialize collapsed bool');
            $scope.isNavigatorCollapsed = false;
            $scope.verbageExpandCollapse = "Expand";
            $scope.webSiteVisible = "Collapse";

            $scope.ExpandSite = "Hide WebSite";
            $scope.ExpandPlug = "Show Plugin";
            $scope.VerbVis = "none";
            $scope.MasterSiteVis = "inline";
            $scope.SiteVis = "flex";
            $scope.mapColWidth = "inherit";

            var status = {
                'website' : "flex",
                'plugin' : "none",
                'navigator' : 'flex'
                };

            var verbageWidth = {
                true : '70%',
                false : '0%'
                };
            var websiteVisibility = {
                true : 'true',
                false : 'false'
                };
            var innerTableAdjustment = 40;

            function printStatus(msg){
                var msgstr = String.format("{0}... site ? : {1}, plugin ? : {2}",
                         msg, status['website'], status['plugin']);
                console.log(msgstr)
                msgstr = String.format("verbage {0}, website {1}", verbageWidth[status['plugin'] == 'flex'], websiteVisibility[status['website'] == 'flex']);
                console.log(msgstr)
             }

                $scope.verbageExpandCollapse =  status['plugin'] == 'flex' ? "Collapse" : "Expand";

            function onShowPlugin(e, from, to, msg){
                status['plugin'] = $scope.VerbVis = "flex";
                $scope.ExpandPlug = "Hide Plugin";
                $scope.verbageExpandCollapse = "Collapse";
                printStatus('Show Plug-in!');
             }

            function onHidePlugin(e, from, to, msg){
                status['plugin'] = $scope.VerbVis = "none";
                $scope.ExpandPlug = "Show Plugin";
                $scope.verbageExpandCollapse  = "Expand";
                printStatus('Hide Plug-in!');
             }

            function onShowWebSite(e, from, to, msg){
                status['website'] = $scope.SiteVis = "flex";
                $scope.mapColWidth = "inherit";
                $scope.ExpandSite = "Hide WebSite" ;
                $scope.webSiteVisible = "Collapse";
                printStatus('Show Web Site!');
             }

            function onHideWebSite(e, from, to, msg){
                status['website'] = $scope.SiteVis = "none";
                $scope.mapColWidth = "100%";
                $scope.ExpandSite = "Show WebSite";
                $scope.webSiteVisible = "Expand";
                printStatus('Hide Web Site!');
             }

            var fsm = finstatmach.create({
              'initial': 'FullWebSite',
              'events': [
                {'name': 'showplugin',  'from': 'FullWebSite',  'to': 'FullWebSiteWPlugin'},
                {'name': 'showplugin',  'from': 'NoWebSite',  'to': 'NoWebSiteWPlugin'},
                {'name': 'hideplugin', 'from': 'FullWebSiteWPlugin', 'to': 'FullWebSite'},
                {'name': 'hideplugin', 'from': 'NoWebSiteWPlugin', 'to': 'NoWebSite'},
                {'name': 'showwebsite',  'from': 'NoWebSite',  'to': 'FullWebSite'},
                {'name': 'hidewebsite',  'from': 'FullWebSiteWPlugin',  'to': 'NoWebSiteWPlugin'},
                {'name': 'showwebsite', 'from': 'NoWebSiteWPlugin', 'to': 'FullWebSiteWPlugin'},
                {'name': 'hidewebsite', 'from': 'FullWebSite', 'to': 'NoWebSite'}
              ],
              'callbacks': {
                'onshowplugin':  onShowPlugin,
                'onhideplugin':  onHidePlugin,
                'onshowwebsite': onShowWebSite,
                'onhidewebsite': onHideWebSite
              }
            })

            $scope.onExpSiteClick = function(){
                console.log("status['website'] before " + status['website']);
                if(status['website'] == 'flex'){
                    fsm.onhidewebsite();
                }else{
                    fsm.onshowwebsite();;
                }
                console.log("status['website'] after  " + status['website']);

                utils.displayHeights("####  onExpSiteClick  ###");
                utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);

                $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;
                // $scope.webSiteVisible = status['website'] == 'flex' ? "Collapse" : "Expand";
                $scope.$broadcast('WebSiteVisibilityEvent', { 'website' : status['website'],
                                                               'verbage' : status['plugin']});
                setTimeout(function(){
                    $scope.$apply(function(){
                        utils.setElementHeight('idCenterCol', colHgt - 40);
                        utils.setElementHeight('map_wrapper', colHgt - 40);
                        if(status['website'] == 'flex'){
                            utils.setElementHeight('idSiteTopRow', utils.getTopRowHeight());
                            utils.setElementHeight('idLeftCol', colHgt - 40);
                            utils.setElementHeight('idRightCol', colHgt - 40);
                        }
                        console.log("onExpSiteClick adjustments - colHgt : " + colHgt);
                        });
                    },1000);
            }

            $scope.onExpPlugClick = function(){
                if($scope.VerbVis == 'flex'){
                    fsm.onhideplugin();
                }
                else{
                    fsm.onshowplugin();
                }
                utils.displayHeights("####  onExpPlugClick  ###");
                utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);

                $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;
                $scope.$broadcast('CollapseVerbageEvent', { 'website' : status['website'],
                                                             'verbage' : status['plugin']});

                setTimeout(function(){
                    $scope.$apply(function(){
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);
                        $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;
                        utils.displayHeights("####  onExpPlugClick after timeout  ###");
                        utils.setElementHeight('idCenterCol', colHgt - 40);
                        utils.setElementHeight('map_wrapper', colHgt - 40);
                        if(status['website'] == 'flex'){
                            utils.setElementHeight('idSiteTopRow', utils.getTopRowHeight());
                            utils.setElementHeight('idLeftCol', colHgt - 40);
                            utils.setElementHeight('idRightCol', colHgt - 40);
                            utils.setElementHeight('idFooter', utils.getFooterHeight());
                        }
                        console.log("onExpPlugClick adjustments - colHgt : " + colHgt);
                        });
                    },1000);

            };

            $scope.$on('CollapseSummaryEvent', function(event, args) {
                $scope.MasterSiteVis = args.mastersitevis;
                status['navigator'] = args.navVis;
                console.log("on CollapseSummaryEvent, call adjustHeights");
                var innerScope = $scope;
                setTimeout(function(){
                    innerScope.$apply(function(){
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        utils.displayHeights("####  CollapseSummaryEvent  ###");
                        adjustHeights($scope);
                        });
                    },1000);

            });

            $scope.$on('CollapseNavigatorEvent', function(event, args) {
                $scope.MasterSiteVis = args.mastersitevis;
                status['navigator'] = args.navVis;
                setTimeout(function(){
                    $scope.$apply(function(){
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        utils.displayHeights("####  CollapseNavigatorEvent  ###");
                        adjustHeights($scope);
                        // utils.setElementHeight('idMasherCtrl', utils.getMasterSiteHeight());
                        });
                    },1000);
            });

            $scope.$on('windowResized', function() {
                utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);
                utils.displayHeights("####  windowResized Event  ###");
                $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;

                setTimeout(function(){
                    $scope.$apply(function(){
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        adjustHeights($scope);
                        // utils.setElementHeight('idMasherCtrl', utils.getMasterSiteHeight());
                        });
                    },1000);

                console.log("windowResized method in SPACtrl.js");

                // utils.calculateComponentHeights($scope.MasterSiteVis, status['website']);
                // utils.setElementHeight('idMasherCtrl', utils.getMasterSiteHeight());
                // utils.setElementHeight('idMasterSite', 90, '%');
                // adjustHeights($scope);
            });

            function adjustHeights(scope){
                /* From flexbox.js plunker  */
                var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], scope.MasterSiteVis, status['website']);
                scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;

                setTimeout(function(){
                    $scope.$apply(function(){
                        // $scope.bodyColHeight = colHgt;
                        // $scope.bodyColHeight = colHgt;
                        // utils.setElementHeight('idBody', colHgt - 20);
                        utils.setElementHeight('idCenterCol', colHgt - 40);
                        utils.setElementHeight('map_wrapper', colHgt - 40);
                        if(status['website'] == 'flex'){
                            utils.setElementHeight('idSiteTopRow', utils.getTopRowHeight());
                            utils.setElementHeight('idLeftCol', colHgt - 40);
                            utils.setElementHeight('idRightCol', colHgt - 40);
                        }
                        console.log("adjustHeights colHgt : " + colHgt);
                        });
                    },1000);
            }
        };

        function init(App) {
            console.log('SPACtrl init');
            App.controller('SPACtrl', ['$scope', SPACtrl]);
            return SPACtrl;
        }

        return { start: init };

    });

}).call(this);<commit_msg>Works fairly well with adjustments of:<commit_after>
// <<<<<<<<<<<<<<<<<   http://plnkr.co/edit/V5alqOODGmnLbKiK2YY7?p=preview  >>>>>>>>>>>>>>>>>>

(function() {
    "use strict";

    console.log('SPACtrl setup');
    define(['angular', 'lib/fsm', 'lib/utils'], function(angular, finstatmach, utils) {
        console.log('SPACtrl define');

        function SPACtrl($scope) {
            console.debug('SPACtrl - initialize collapsed bool');
            $scope.isNavigatorCollapsed = false;
            $scope.verbageExpandCollapse = "Expand";
            $scope.webSiteVisible = "Collapse";

            $scope.ExpandSite = "Hide WebSite";
            $scope.ExpandPlug = "Show Plugin";
            $scope.VerbVis = "none";
            $scope.MasterSiteVis = "inline";
            $scope.SiteVis = "flex";
            $scope.mapColWidth = "inherit";

            var status = {
                'website' : "flex",
                'plugin' : "none",
                'navigator' : 'flex'
                };

            var verbageWidth = {
                true : '70%',
                false : '0%'
                };
            var websiteVisibility = {
                true : 'true',
                false : 'false'
                };
            var innerTableAdjustment = 20;
            var colHeightAdjustment = 40;

            function printStatus(msg){
                var msgstr = String.format("{0}... site ? : {1}, plugin ? : {2}",
                         msg, status['website'], status['plugin']);
                console.log(msgstr)
                msgstr = String.format("verbage {0}, website {1}", verbageWidth[status['plugin'] == 'flex'], websiteVisibility[status['website'] == 'flex']);
                console.log(msgstr)
             }

                $scope.verbageExpandCollapse =  status['plugin'] == 'flex' ? "Collapse" : "Expand";

            function onShowPlugin(e, from, to, msg){
                status['plugin'] = $scope.VerbVis = "flex";
                $scope.ExpandPlug = "Hide Plugin";
                $scope.verbageExpandCollapse = "Collapse";
                printStatus('Show Plug-in!');
             }

            function onHidePlugin(e, from, to, msg){
                status['plugin'] = $scope.VerbVis = "none";
                $scope.ExpandPlug = "Show Plugin";
                $scope.verbageExpandCollapse  = "Expand";
                printStatus('Hide Plug-in!');
             }

            function onShowWebSite(e, from, to, msg){
                status['website'] = $scope.SiteVis = "flex";
                $scope.mapColWidth = "inherit";
                $scope.ExpandSite = "Hide WebSite" ;
                $scope.webSiteVisible = "Collapse";
                printStatus('Show Web Site!');
             }

            function onHideWebSite(e, from, to, msg){
                status['website'] = $scope.SiteVis = "none";
                $scope.mapColWidth = "100%";
                $scope.ExpandSite = "Show WebSite";
                $scope.webSiteVisible = "Expand";
                printStatus('Hide Web Site!');
             }

            var fsm = finstatmach.create({
              'initial': 'FullWebSite',
              'events': [
                {'name': 'showplugin',  'from': 'FullWebSite',  'to': 'FullWebSiteWPlugin'},
                {'name': 'showplugin',  'from': 'NoWebSite',  'to': 'NoWebSiteWPlugin'},
                {'name': 'hideplugin', 'from': 'FullWebSiteWPlugin', 'to': 'FullWebSite'},
                {'name': 'hideplugin', 'from': 'NoWebSiteWPlugin', 'to': 'NoWebSite'},
                {'name': 'showwebsite',  'from': 'NoWebSite',  'to': 'FullWebSite'},
                {'name': 'hidewebsite',  'from': 'FullWebSiteWPlugin',  'to': 'NoWebSiteWPlugin'},
                {'name': 'showwebsite', 'from': 'NoWebSiteWPlugin', 'to': 'FullWebSiteWPlugin'},
                {'name': 'hidewebsite', 'from': 'FullWebSite', 'to': 'NoWebSite'}
              ],
              'callbacks': {
                'onshowplugin':  onShowPlugin,
                'onhideplugin':  onHidePlugin,
                'onshowwebsite': onShowWebSite,
                'onhidewebsite': onHideWebSite
              }
            })

            $scope.onExpSiteClick = function(){
                console.log("status['website'] before " + status['website']);
                if(status['website'] == 'flex'){
                    fsm.onhidewebsite();
                }else{
                    fsm.onshowwebsite();;
                }
                console.log("status['website'] after  " + status['website']);

                utils.displayHeights("####  onExpSiteClick  ###");
                utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);

                $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;
                // $scope.webSiteVisible = status['website'] == 'flex' ? "Collapse" : "Expand";
                $scope.$broadcast('WebSiteVisibilityEvent', { 'website' : status['website'],
                                                               'verbage' : status['plugin']});
                setTimeout(function(){
                    $scope.$apply(function(){
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);
                        $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;
                        utils.setElementHeight('idCenterCol', colHgt - colHeightAdjustment);
                        utils.setElementHeight('map_wrapper', colHgt - colHeightAdjustment);
                        utils.setElementHeight('idFooter', utils.getFooterHeight());
                        if(status['website'] == 'flex'){
                            utils.setElementHeight('idSiteTopRow', utils.getTopRowHeight());
                            utils.setElementHeight('idLeftCol', colHgt - colHeightAdjustment);
                            utils.setElementHeight('idRightCol', colHgt - colHeightAdjustment);
                        }
                        console.log("onExpSiteClick adjustments - colHgt : " + colHgt);
                        });
                    },1000);
            }

            $scope.onExpPlugClick = function(){
                if($scope.VerbVis == 'flex'){
                    fsm.onhideplugin();
                }
                else{
                    fsm.onshowplugin();
                }
                utils.displayHeights("####  onExpPlugClick  ###");
                utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);

                $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;
                $scope.$broadcast('CollapseVerbageEvent', { 'website' : status['website'],
                                                             'verbage' : status['plugin']});

                setTimeout(function(){
                    $scope.$apply(function(){
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);
                        $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;
                        utils.displayHeights("####  onExpPlugClick after timeout  ###");
                        utils.setElementHeight('idCenterCol', colHgt - colHeightAdjustment);
                        utils.setElementHeight('map_wrapper', colHgt - colHeightAdjustment);
                        if(status['website'] == 'flex'){
                            utils.setElementHeight('idSiteTopRow', utils.getTopRowHeight());
                            utils.setElementHeight('idLeftCol', colHgt - colHeightAdjustment);
                            utils.setElementHeight('idRightCol', colHgt - colHeightAdjustment);
                            utils.setElementHeight('idFooter', utils.getFooterHeight());
                        }
                        console.log("onExpPlugClick adjustments - colHgt : " + colHgt);
                        });
                    },1000);

            };

            $scope.$on('CollapseSummaryEvent', function(event, args) {
                $scope.MasterSiteVis = args.mastersitevis;
                status['navigator'] = args.navVis;
                console.log("on CollapseSummaryEvent, call adjustHeights");
                var innerScope = $scope;
                setTimeout(function(){
                    innerScope.$apply(function(){
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        utils.displayHeights("####  CollapseSummaryEvent  ###");
                        adjustHeights($scope);
                        });
                    },1000);

            });

            $scope.$on('CollapseNavigatorEvent', function(event, args) {
                $scope.MasterSiteVis = args.mastersitevis;
                status['navigator'] = args.navVis;
                setTimeout(function(){
                    $scope.$apply(function(){
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        utils.displayHeights("####  CollapseNavigatorEvent  ###");
                        adjustHeights($scope);
                        // utils.setElementHeight('idMasherCtrl', utils.getMasterSiteHeight());
                        });
                    },1000);
            });

            $scope.$on('windowResized', function() {
                utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);
                utils.displayHeights("####  windowResized Event  ###");
                $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;

                setTimeout(function(){
                    $scope.$apply(function(){
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        adjustHeights($scope);
                        // utils.setElementHeight('idMasherCtrl', utils.getMasterSiteHeight());
                        });
                    },1000);

                console.log("windowResized method in SPACtrl.js");

                // utils.calculateComponentHeights($scope.MasterSiteVis, status['website']);
                // utils.setElementHeight('idMasherCtrl', utils.getMasterSiteHeight());
                // utils.setElementHeight('idMasterSite', 90, '%');
                // adjustHeights($scope);
            });

            function adjustHeights(scope){
                /* From flexbox.js plunker  */
                var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], scope.MasterSiteVis, status['website']);
                scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;

                setTimeout(function(){
                    $scope.$apply(function(){
                        // $scope.bodyColHeight = colHgt;
                        // $scope.bodyColHeight = colHgt;
                        // utils.setElementHeight('idBody', colHgt - 20);
                        utils.calculateComponentHeights($scope.MasterSiteVis, $scope.SiteVis);
                        var colHgt = utils.getAvailableSiteColumnHeights(status['navigator'], $scope.MasterSiteVis, status['website']);
                        $scope.innerTblHeight = colHgt + utils.getTopRowHeight() + utils.getFooterHeight() - innerTableAdjustment;
                        utils.setElementHeight('idCenterCol', colHgt - colHeightAdjustment);
                        utils.setElementHeight('map_wrapper', colHgt - colHeightAdjustment);
                        if(status['website'] == 'flex'){
                            utils.setElementHeight('idSiteTopRow', utils.getTopRowHeight());
                            utils.setElementHeight('idLeftCol', colHgt - colHeightAdjustment);
                            utils.setElementHeight('idRightCol', colHgt - colHeightAdjustment);
                        }
                        console.log("adjustHeights colHgt : " + colHgt);
                        });
                    },1000);
            }
        };

        function init(App) {
            console.log('SPACtrl init');
            App.controller('SPACtrl', ['$scope', SPACtrl]);
            return SPACtrl;
        }

        return { start: init };

    });

}).call(this);<|endoftext|>


<commit_before>mage.directive('userLocation', function(UserService, appConstants) {
  return {
    restrict: "A",
    templateUrl:  "js/app/partials/user-location.html",
    scope: {
    },
    controller: function ($scope, UserService) {
      $scope.getUser = function(userId) {
        UserService.getUser(userId)
          .success(function(user) {
            $scope.user = user;
          })
          .error(function() {
            console.log('error trying to get user');
          });
      }
    }
  };
});<commit_msg>Found a bug.  If you are an admin and went to the admin page and then came back to the map, the users would not show up in the bubble due to a different type of promise coming back.<commit_after>mage.directive('userLocation', function(UserService, appConstants) {
  return {
    restrict: "A",
    templateUrl:  "js/app/partials/user-location.html",
    scope: {
    },
    controller: function ($scope, UserService) {
      $scope.getUser = function(userId) {
        var u = UserService.getUser(userId);
        if (u.success) {
          u.success(function(user) {
            $scope.user = user;
          })
          .error(function() {
            console.log('error trying to get user');
          });
        } else if (u.then) {
          u.then(function(user) {
            $scope.user = user;
          })
        }

      }
    }
  };
});<|endoftext|>


<commit_before>/*global define*/
define([
	'jQuery-2.1.4.min',
	'underscore_1.3.3',
	'backbone_0.9.2',
  'bootstrap-table',
  '../model/FrontEndWidgetModel.js',
  'text!../../../js/app/templates/frontEndWidget.html'
], function ($, _, Backbone, BootstrapTable, FrontEndWidgetModel, FrontEndWidgetTemplate) {
	'use strict';

	var FrontEndWidgetView = Backbone.View.extend({

		tagName:  'div',

    el: '#frontEndWidgetView',

		template: _.template(FrontEndWidgetTemplate),

		// The DOM events specific to an item.
		events: {
      'click #addHTMLBtn': 'addHTML',
      'click #addImgRowBtn': 'addImgRow',
      'click #addWidget': 'addWidget'
		},

		initialize: function () {

		},

    render: function () {
      //debugger;

      this.$el.html(this.template);

      this.populateTable();

			return this;
		},

    //This function is called by render. It's purpose is to initialize and populate the bootstrap
    //table with data from the Front End Widgets Collection.
    populateTable: function() {
      //debugger;

      //Catch corner case of empty DB
      if((global.frontEndWidgetCollection.models.length == 1) &&
         (global.frontEndWidgetCollection.models[0].get('_id') == "") &&
         (global.frontEndWidgetCollection.models[0]get('title') == "") )
          return;

      //Initialize the table.
      this.$el.find('#widgetTable').bootstrapTable({
        sortName: 'entry',
        sortOrder: 'desc',
        showExport: false,
        columns: [{
          field: 'entry',
          title: 'Entry',
          sortable: true
        }, {
          field: 'title',
          title: 'Title',
          sortable: true
        }, {
          field: 'desc',
          title: 'Description',
          sortable: true
        }, {
          field: 'GUID',
          title: 'GUID',
          sortable: true
        }, {
          field: 'delete',
          title: 'Delete',
          sortable: false
        }
        ],
      });

      //Loop through the Keep Out coordinates.
      var tableData = [];
      for(var i=0; i < global.frontEndWidgetCollection.length; i++) {
        var item = global.frontEndWidgetCollection.models[i];
        var obj = new Object();

        obj.entry = i;
        obj.title = ''+item.get('title')+'';
        obj.desc = item.get('desc');
        obj.GUID = item.get('_id');
        obj.delete = '<button type="button" class="btn btn-danger btn-xs"></button>';

        tableData.push(obj);
      }
      this.$el.find('#widgetTable').bootstrapTable('load', tableData);
      this.$el.find('.fixed-table-loading').hide();

    },

    loadWidget: function(index) {
      //debugger;

      var item = global.frontEndWidgetCollection.models[index];

      //this.$el.find('#widgetEditor').slideDown(); //Show the widget editor
      this.$el.find('#widgetEditor').show(); //Show the widget editor
      this.$el.find('hr').slideDown(); //Show any hr separators

      this.$el.find('#widgetTitle').val(item.get('title'));
      this.$el.find('#widgetDesc').val(item.get('desc'));

      var htmlArray = item.get('contentArray');
      var imgArray = item.get('imgUrlArray');

      //BEGIN POPULATION OF HTML ARRAY
      if((htmlArray.length == 0) || (htmlArray.length == undefined)) {
        //Do nothing. Leave the default HTML the way it is.
      } else {

        for(var i=0; i < htmlArray.length; i++) {
          var tmpEntry = this.$el.find('#widgetHTML').find('.scaffold').clone(); //Clone the scaffolding

          tmpEntry.removeClass('scaffold'); //Remove the scaffold class
          tmpEntry.find('button').click([i],this.deleteHtml); //Assign a click handler to the delete button
          tmpEntry.find('textarea').val(htmlArray[i]); //Populate the text box
          this.$el.find('#widgetHTML').prepend(tmpEntry);
        }

        //Remove the scaffolding element
        this.$el.find('#widgetHTML').find('.scaffold').remove();
      }
      //END POPULATION OF HTML ARRAY

      //BEGIN POPULATION OF IMAGE ARRAY
      if((imgArray.length == 0) || (imgArray.length == undefined)) {
        //Do nothing. Leave the default image layout the way it is.
        debugger;
      } else {

        //Initialize
        var colIndex = 0;
        var tmpRow = this.$el.find('#widgetImages').find('.scaffold').clone();
        tmpRow.removeClass('scaffold');

        //Loop through all the images
        for(var i=0; i < imgArray.length; i++) {
          var imgSelector = '.img'+colIndex;

          var thisImg = tmpRow.find(imgSelector);
          thisImg.find('button').click([i], this.deleteImg); //Assign a click handler to the delete button.
          thisImg.find('img').attr('onclick', ''); //Remove the default click handler.
          thisImg.find('img').click([i], this.swapImg); //Assign a click handler to the image to swap out the image with a new one.
          thisImg.find('img').attr('src', imgArray[i]); //Swap out the image with the one assigned to the widget.

          //Manage the column index
          colIndex++;
          if(colIndex > 2) {
            colIndex = 0;

            this.$el.find('#widgetImages').prepend(tmpRow);
            var tmpRow = this.$el.find('#widgetImages').find('scaffold').clone();
            //tmpRow.find('.label').remove(); //Remove the label.
            tmpRow.removeClass('scaffold');
          }
        }

        this.$el.find('#widgetImages').find('.scaffold').remove();
        this.$el.find('#widgetImages').prepend(tmpRow);
      }
      //END POPULATION OF IMAGE ARRAY
    },

    //This function is called when the user clicks on the delete button assigned to an HTML array
    //element. It's purpose is to remove the array entry from the model.
    deleteHtml: function(index) {
      debugger;

      //If index is a click event object, then retrieve the data passed in.
      if(typeof(index) == "object")
        index = index.data[0];
    },

    //This function is called when the user clicks on the delete button assigned to the image.
    //It's purpose is to remove the image from the current front end widget.
    deleteImg: function(index) {
      debugger;

      //If index is a click event object, then retrieve the data passed in.
      if(typeof(index) == "object")
        index = index.data[0];
    },

    swapImg: function(index) {
      debugger;

      //If index is a click event object, then retrieve the data passed in.
      if(typeof(index) == "object")
        index = index.data[0];

      if(index == -1) {
        console.log('Empty image was clicked');
      } else {
        console.log('Existing image was clicked');
      }
    },

    //This function is called when a user clicks on the delete button for a widget.
    deleteWidget: function(index) {
      debugger;
    },

    //This function is called when the user clicks on the 'Add HTML' button.
    //This function adds a new textarea element to the DOM for additional content.
    addHTML: function() {
      debugger;
    },

    //This function is called when the suer clicks on the 'Add Image Row' button.
    addImgRow: function() {
      debugger;
    },

    addWidget: function() {
      debugger;

      //Catch corner case of empty DB
      if((global.frontEndWidgetCollection.models.length == 1) &&
         (global.frontEndWidgetCollection.models[0].get('_id') == "") ) {
        global.frontEndWidgetCollection.models[0].set('title', 'new widget');
      } else {

        var newWidget = new FrontEndWidgetModel({'title', 'new widget'});
        global.frontEndWidgetCollection.add(newWidget);
      }

      this.render();
    }

	});

  //debugger;
	return FrontEndWidgetView;
});<commit_msg>Developing front end widget view<commit_after>/*global define*/
define([
	'jQuery-2.1.4.min',
	'underscore_1.3.3',
	'backbone_0.9.2',
  'bootstrap-table',
  '../model/FrontEndWidgetModel.js',
  'text!../../../js/app/templates/frontEndWidget.html'
], function ($, _, Backbone, BootstrapTable, FrontEndWidgetModel, FrontEndWidgetTemplate) {
	'use strict';

	var FrontEndWidgetView = Backbone.View.extend({

		tagName:  'div',

    el: '#frontEndWidgetView',

		template: _.template(FrontEndWidgetTemplate),

		// The DOM events specific to an item.
		events: {
      'click #addHTMLBtn': 'addHTML',
      'click #addImgRowBtn': 'addImgRow',
      'click #addWidget': 'addWidget'
		},

		initialize: function () {

		},

    render: function () {
      //debugger;

      this.$el.html(this.template);

      this.populateTable();

			return this;
		},

    //This function is called by render. It's purpose is to initialize and populate the bootstrap
    //table with data from the Front End Widgets Collection.
    populateTable: function() {
      //debugger;

      //Catch corner case of empty DB
      if((global.frontEndWidgetCollection.models.length == 1) &&
         (global.frontEndWidgetCollection.models[0].get('_id') == "") &&
         (global.frontEndWidgetCollection.models[0].get('title') == "") )
          return;

      //Initialize the table.
      this.$el.find('#widgetTable').bootstrapTable({
        sortName: 'entry',
        sortOrder: 'desc',
        showExport: false,
        columns: [{
          field: 'entry',
          title: 'Entry',
          sortable: true
        }, {
          field: 'title',
          title: 'Title',
          sortable: true
        }, {
          field: 'desc',
          title: 'Description',
          sortable: true
        }, {
          field: 'GUID',
          title: 'GUID',
          sortable: true
        }, {
          field: 'delete',
          title: 'Delete',
          sortable: false
        }
        ],
      });

      //Loop through the Keep Out coordinates.
      var tableData = [];
      for(var i=0; i < global.frontEndWidgetCollection.length; i++) {
        var item = global.frontEndWidgetCollection.models[i];
        var obj = new Object();

        obj.entry = i;
        obj.title = ''+item.get('title')+'';
        obj.desc = item.get('desc');
        obj.GUID = item.get('_id');
        obj.delete = '<button type="button" class="btn btn-danger btn-xs"></button>';

        tableData.push(obj);
      }
      this.$el.find('#widgetTable').bootstrapTable('load', tableData);
      this.$el.find('.fixed-table-loading').hide();

    },

    loadWidget: function(index) {
      //debugger;

      var item = global.frontEndWidgetCollection.models[index];

      //this.$el.find('#widgetEditor').slideDown(); //Show the widget editor
      this.$el.find('#widgetEditor').show(); //Show the widget editor
      this.$el.find('hr').slideDown(); //Show any hr separators

      this.$el.find('#widgetTitle').val(item.get('title'));
      this.$el.find('#widgetDesc').val(item.get('desc'));

      var htmlArray = item.get('contentArray');
      var imgArray = item.get('imgUrlArray');

      //BEGIN POPULATION OF HTML ARRAY
      if((htmlArray.length == 0) || (htmlArray.length == undefined)) {
        //Do nothing. Leave the default HTML the way it is.
      } else {

        for(var i=0; i < htmlArray.length; i++) {
          var tmpEntry = this.$el.find('#widgetHTML').find('.scaffold').clone(); //Clone the scaffolding

          tmpEntry.removeClass('scaffold'); //Remove the scaffold class
          tmpEntry.find('button').click([i],this.deleteHtml); //Assign a click handler to the delete button
          tmpEntry.find('textarea').val(htmlArray[i]); //Populate the text box
          this.$el.find('#widgetHTML').prepend(tmpEntry);
        }

        //Remove the scaffolding element
        this.$el.find('#widgetHTML').find('.scaffold').remove();
      }
      //END POPULATION OF HTML ARRAY

      //BEGIN POPULATION OF IMAGE ARRAY
      if((imgArray.length == 0) || (imgArray.length == undefined)) {
        //Do nothing. Leave the default image layout the way it is.
        debugger;
      } else {

        //Initialize
        var colIndex = 0;
        var tmpRow = this.$el.find('#widgetImages').find('.scaffold').clone();
        tmpRow.removeClass('scaffold');

        //Loop through all the images
        for(var i=0; i < imgArray.length; i++) {
          var imgSelector = '.img'+colIndex;

          var thisImg = tmpRow.find(imgSelector);
          thisImg.find('button').click([i], this.deleteImg); //Assign a click handler to the delete button.
          thisImg.find('img').attr('onclick', ''); //Remove the default click handler.
          thisImg.find('img').click([i], this.swapImg); //Assign a click handler to the image to swap out the image with a new one.
          thisImg.find('img').attr('src', imgArray[i]); //Swap out the image with the one assigned to the widget.

          //Manage the column index
          colIndex++;
          if(colIndex > 2) {
            colIndex = 0;

            this.$el.find('#widgetImages').prepend(tmpRow);
            var tmpRow = this.$el.find('#widgetImages').find('scaffold').clone();
            //tmpRow.find('.label').remove(); //Remove the label.
            tmpRow.removeClass('scaffold');
          }
        }

        this.$el.find('#widgetImages').find('.scaffold').remove();
        this.$el.find('#widgetImages').prepend(tmpRow);
      }
      //END POPULATION OF IMAGE ARRAY
    },

    //This function is called when the user clicks on the delete button assigned to an HTML array
    //element. It's purpose is to remove the array entry from the model.
    deleteHtml: function(index) {
      debugger;

      //If index is a click event object, then retrieve the data passed in.
      if(typeof(index) == "object")
        index = index.data[0];
    },

    //This function is called when the user clicks on the delete button assigned to the image.
    //It's purpose is to remove the image from the current front end widget.
    deleteImg: function(index) {
      debugger;

      //If index is a click event object, then retrieve the data passed in.
      if(typeof(index) == "object")
        index = index.data[0];
    },

    swapImg: function(index) {
      debugger;

      //If index is a click event object, then retrieve the data passed in.
      if(typeof(index) == "object")
        index = index.data[0];

      if(index == -1) {
        console.log('Empty image was clicked');
      } else {
        console.log('Existing image was clicked');
      }
    },

    //This function is called when a user clicks on the delete button for a widget.
    deleteWidget: function(index) {
      debugger;
    },

    //This function is called when the user clicks on the 'Add HTML' button.
    //This function adds a new textarea element to the DOM for additional content.
    addHTML: function() {
      debugger;
    },

    //This function is called when the suer clicks on the 'Add Image Row' button.
    addImgRow: function() {
      debugger;
    },

    addWidget: function() {
      debugger;

      //Catch corner case of empty DB
      if((global.frontEndWidgetCollection.models.length == 1) &&
         (global.frontEndWidgetCollection.models[0].get('_id') == "") ) {
        global.frontEndWidgetCollection.models[0].set('title', 'new widget');
      } else {

        var newWidget = new FrontEndWidgetModel({'title', 'new widget'});
        global.frontEndWidgetCollection.add(newWidget);
      }

      this.render();
    }

	});

  //debugger;
	return FrontEndWidgetView;
});<|endoftext|>


<commit_before>/**
 * Created with JetBrains PhpStorm.
 * User: krasu
 * Date: 9/17/13
 * Time: 8:39 AM
 */
define(function (require) {
	require('backbone')
	var store = require('store').getNamespace('repo-selector')

	return Backbone.Router.extend({
		routes: {
			'type/:type/id/:id': 'switchType',
			'type/:type/id/:id/tab/:tab': 'switchType',
			'*actions': 'switchType'
		},
		switchType: function (type, id, tab) {
			if (type != store().currentType.type || id != store().currentType.id) {
				store().currentType = {
					type: type,
					id: id
				}

				store().selected.fetch()
			}

			this.selectTab(tab)
		},
		selectTab: function () {
			var tab = Array.prototype.pop.call(arguments)
			tab = tab || 'selected-repos'
			var el = store().layout.$('.nav a[href="#' + tab + '"]')
			el.tab('show')
		}
	});
})
<commit_msg>updated supporters UI<commit_after>/**
 * Created with JetBrains PhpStorm.
 * User: krasu
 * Date: 9/17/13
 * Time: 8:39 AM
 */
define(function (require) {
	require('backbone')
	var store = require('store').getNamespace('repo-selector')

	return Backbone.Router.extend({
		routes: {
			'type/:type/id/:id': 'switchType',
			'type/:type/id/:id/tab/:tab': 'switchType',
			'*actions': 'switchType'
		},
		switchType: function (type, id, tab) {
			if (type != store().currentType.type || id != store().currentType.id) {
				store().currentType = {
					type: type || 'user',
					id: id || currentUserId
				}

				store().selected.fetch()
			}

			this.selectTab(tab)
		},
		selectTab: function () {
			var tab = Array.prototype.pop.call(arguments)
			tab = tab || 'selected-repos'
			var el = store().layout.$('.nav a[href="#' + tab + '"]')
			el.tab('show')
		}
	});
})
<|endoftext|>


<commit_before>/**
 * Copyright reelyActive 2014
 * We believe in an open Internet of Things
 */

var nedb = require('nedb');

var SILO_DB = "silo.db";
var MAINTENANCE_INTERVAL_MILLISECONDS = 60000;
var TEST_JSON = { person: { firstName: "Barn",
                            lastName: "Owl",
                            companyName: "reelyActive" } };
var TEST_DOC = { "_id": "test",
                 "json": TEST_JSON,
                 "expireAfter": "2009-01-01T01:23:45.678Z",
                 "place": "test" };

/**
 * SiloManager Class
 * Manages the persistent JSON entries
 * @constructor
 */
function SiloManager() {
  var self = this;
  this.db = new nedb({filename: SILO_DB, autoload: true });
  this.db.insert(TEST_DOC);

  function periodicMaintenance() {
    removeStaleDocuments(self);
    self.db.persistence.compactDatafile();
  }

  setInterval(periodicMaintenance, MAINTENANCE_INTERVAL_MILLISECONDS);
};

/**
 * Find the JSON associated with the given identifier
 * @param {String} id Identifier to search on.
 * @param {function} callback Function to call on completion.
 */
SiloManager.prototype.find = function(id, callback) {
  var self = this;

  this.db.find({ _id: id }, function(err, docs) {
    var result = docs[0];
    var json = {};
    if(result != null) {
      json = result.json;
    }
    callback(json);
  });
}

/**
 * Find the all the JSON associated with the given place
 * @param {String} place The place name to search on.
 * @param {function} callback Function to call on completion.
 */
SiloManager.prototype.findAt = function(place, callback) {
  var self = this;

  this.db.find({ place: place }, function(err, matching) {
    var present = {};
    for(var cId = 0; cId < matching.length; cId++) {
      present[matching[cId]._id] = { };
    }
    callback(present);
  });
}

/**
 * Add a JSON to the database
 * @param {Object} doc The JSON to add.
 * @param {function} callback Function to call on completion.
 */
SiloManager.prototype.add = function(doc, callback) {
  var self = this;
  this.db.insert(doc, function(err, newDoc) {
    var id = newDoc._id;
    callback(id);
  });
}

/**
 * Remove a JSON from the database
 * @param {String} id Identifier to remove.
 */
SiloManager.prototype.remove = function(id) {
  var self = this;
  this.db.remove({ _id: id });
}

/**
 * Removes all stale tiraids from the database
 * @param {SiloManager} instance The given instance.
 */
function removeStaleDocuments(instance) {
  var cutoffTime = new Date().toISOString();
  instance.db.update({}, { $pull: { expireAfter: { $lt: cutoffTime } } },
                     { multi: true });
}

module.exports = SiloManager;
<commit_msg>Updated test JSON output<commit_after>/**
 * Copyright reelyActive 2014
 * We believe in an open Internet of Things
 */

var nedb = require('nedb');

var SILO_DB = "silo.db";
var MAINTENANCE_INTERVAL_MILLISECONDS = 60000;
var TEST_JSON = { person: { firstName: "Barn",
                            lastName: "Owl",
                            companyName: "reelyActive",
                            portraitImageUrl: "http://reelyactive.com/images/barnowl.jpg",
                            twitterPersonalScreenName: "reelyActive" },
                  device: { manufacturer: "reelyActive",
                            model: "RA-T411",
                            portraitImageUrl: "http://reelyactive.com/images/tag400x400.jpg" } };
var TEST_DOC = { "_id": "test",
                 "json": TEST_JSON,
                 "expireAfter": "2099-01-01T01:23:45.678Z",
                 "place": "test" };

/**
 * SiloManager Class
 * Manages the persistent JSON entries
 * @constructor
 */
function SiloManager() {
  var self = this;
  this.db = new nedb({filename: SILO_DB, autoload: true });
  this.db.insert(TEST_DOC);

  function periodicMaintenance() {
    removeStaleDocuments(self);
    self.db.persistence.compactDatafile();
  }

  setInterval(periodicMaintenance, MAINTENANCE_INTERVAL_MILLISECONDS);
};

/**
 * Find the JSON associated with the given identifier
 * @param {String} id Identifier to search on.
 * @param {function} callback Function to call on completion.
 */
SiloManager.prototype.find = function(id, callback) {
  var self = this;

  this.db.find({ _id: id }, function(err, docs) {
    var result = docs[0];
    var json = {};
    if(result != null) {
      json = result.json;
    }
    callback(json);
  });
}

/**
 * Find the all the JSON associated with the given place
 * @param {String} place The place name to search on.
 * @param {function} callback Function to call on completion.
 */
SiloManager.prototype.findAt = function(place, callback) {
  var self = this;

  this.db.find({ place: place }, function(err, matching) {
    var present = {};
    for(var cId = 0; cId < matching.length; cId++) {
      present[matching[cId]._id] = { };
    }
    callback(present);
  });
}

/**
 * Add a JSON to the database
 * @param {Object} doc The JSON to add.
 * @param {function} callback Function to call on completion.
 */
SiloManager.prototype.add = function(doc, callback) {
  var self = this;
  this.db.insert(doc, function(err, newDoc) {
    var id = newDoc._id;
    callback(id);
  });
}

/**
 * Remove a JSON from the database
 * @param {String} id Identifier to remove.
 */
SiloManager.prototype.remove = function(id) {
  var self = this;
  this.db.remove({ _id: id });
}

/**
 * Removes all stale tiraids from the database
 * @param {SiloManager} instance The given instance.
 */
function removeStaleDocuments(instance) {
  var cutoffTime = new Date().toISOString();
  instance.db.update({}, { $pull: { expireAfter: { $lt: cutoffTime } } },
                     { multi: true });
}

module.exports = SiloManager;
<|endoftext|>


<commit_before>(function (env) {
    "use strict";
    env.ddg_spice_<: $lia_name :> = function(api_result){

        // Validate the response (customize for your Spice)
        if (api_result.error) {
            return Spice.failed('<: $lia_name :>');
        }

        // Render the response
        Spice.add({
            id: "<: $lia_name :>",

            // Customize these properties
            name: "AnswerBar title",
            data: api_result,
            meta: {
                sourceName: "Example.com",
                sourceUrl: 'http://example.com/url/to/details/' + api_result.name
            },
            templates: {
                group: 'your-template-group',
                options: {
                    content: Spice.<: $lia_name :>.content,
                    moreAt: true
                }
            }
        });
    };
}(this));
<commit_msg>Template: Add error checking of api_result<commit_after>(function (env) {
    "use strict";
    env.ddg_spice_<: $lia_name :> = function(api_result){

        // Validate the response (customize for your Spice)
        if (!api_result || api_result.error) {
            return Spice.failed('<: $lia_name :>');
        }

        // Render the response
        Spice.add({
            id: "<: $lia_name :>",

            // Customize these properties
            name: "AnswerBar title",
            data: api_result,
            meta: {
                sourceName: "Example.com",
                sourceUrl: 'http://example.com/url/to/details/' + api_result.name
            },
            templates: {
                group: 'your-template-group',
                options: {
                    content: Spice.<: $lia_name :>.content,
                    moreAt: true
                }
            }
        });
    };
}(this));
<|endoftext|>


<commit_before>/*! Simple EU Cookies Law Compliance without dependencies by cara-tm.com, 2017. MIT license - Code: https://github.com/cara-tm/EU-Cookies-Law-Compliance/ */
function EU_cookies_law(r){'use strict';var msg="Vous refusez les cookies tiers externes : aucun, à l'initiative de ce site, n'est présent sur votre appareil.",
future='1 Month',
minutes=1,
no_alowed_cookies="Votre navigateur est configuré pour interdire tous Cookies.";

var domain=window.location.hostname,lang=(navigator.language||navigator.browserLanguage),countries=['AT','BE','BG','HR','CZ','CY','DK','EE','FI','FR','DE','EL','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','SK','SI','ES','SE','GB','UK'],affected=1,seconds=60,mins=minutes,accept_cookies=document.getElementById('ok-cookies'),refuse_cookies=document.getElementById('no-cookies');if(false!==navigator.cookieEnabled){for(var i=0;i<countries.length;i++){if(countries[i]===lang.substring(0,2).toUpperCase()){affected!==0;break;}}if(affected!==1){sanitize_msg('');jsloader(r);}else check_cookies();accept_cookies.onclick=function(evt){launch(evt);evt.preventDefault();};function launch(){future=Number(future.replace(/\D+$/, ''));var expires=new Date(new Date().setMonth(new Date().getMonth()+future));cookie_creation('Ok',expires);jsloader(r);sanitize_msg('');}refuse_cookies.onclick=function(evt){var tomorrow=new Date(new Date().setDate(new Date().getDate()+1));cookie_creation('No',tomorrow);sanitize_msg(msg);window.location='';evt.preventDefault();};function getCookie(sName){var oRegex=new RegExp('(?:; )?'+sName+'=([^;]*);?');if(oRegex.test(document.cookie)) return decodeURIComponent(RegExp.$1);else return null;}function check_cookies(){tick();if(getCookie(domain)==='Ok'+domain){sanitize_msg('');jsloader(r);}else if(getCookie(domain)==='No'+domain){sanitize_msg(msg);}}function cookie_creation(c,e){return document.cookie=domain+'='+encodeURIComponent(c+domain)+';expires='+e.toGMTString();}function jsloader(el){var s=[];var a=document.getElementsByTagName("script")[0];if(!window.scriptHasRun){window.scriptHasRun=true;for(var i=0;i<el.length;i++){if(el[i]!==0||!window.scriptHasRun){window.scriptHasRun=true;s[i]=document.createElement('script');s[i].src=el[i];document.getElementsByTagName('head')[0].appendChild(s[i])||a.parentNode.insertBefore(s[i],a);}}}}function tick(){if(minutes!=0&&null!==document.getElementById('counter')){var counter=document.getElementById('counter'),current_minutes=mins-1;seconds--;if(typeof counter.innerHTML!==null)counter.innerHTML=current_minutes.toString()+':'+(seconds<10?'0':'')+String(seconds);if(seconds>0){setTimeout(tick,1000);}else{if(mins>1){countdown(mins-1);}}if(seconds==0){launch();sanitize_msg('');}}else document.getElementById('cookies-delay').innerHTML='';}}else{sanitize_msg(no_alowed_cookies);}function sanitize_msg(m){document.getElementById("cookies-delay").innerHTML='';return document.getElementById('cookie-choices').innerHTML=m;}};
<commit_msg>Update EU_cookies_law.min.js<commit_after>/*! Simple EU Cookies Law Compliance without dependencies by cara-tm.com, 2017. MIT license - Code: https://github.com/cara-tm/EU-Cookies-Law-Compliance/ */
function EU_cookies_law(r){'use strict';var msg="You refuse external third-party cookies: none, at the initiative of this site, is present on your device.",
future='1 Month',
minutes=1,
no_alowed_cookies="Currently, your browser is set to disable cookies (check preferences).";

var domain=window.location.hostname,lang=(navigator.language||navigator.browserLanguage),countries=['AT','BE','BG','HR','CZ','CY','DK','EE','FI','FR','DE','EL','HU','IE','IT','LV','LT','LU','MT','NL','PL','PT','SK','SI','ES','SE','GB','UK'],affected=1,seconds=60,mins=minutes,accept_cookies=document.getElementById('ok-cookies'),refuse_cookies=document.getElementById('no-cookies');if(false!==navigator.cookieEnabled){for(var i=0;i<countries.length;i++){if(countries[i]===lang.substring(0,2).toUpperCase()){affected!==0;break;}}if(affected!==1){sanitize_msg('');jsloader(r);}else check_cookies();accept_cookies.onclick=function(evt){launch(evt);evt.preventDefault();};function launch(){future=Number(future.replace(/\D+$/, ''));var expires=new Date(new Date().setMonth(new Date().getMonth()+future));cookie_creation('Ok',expires);jsloader(r);sanitize_msg('');}refuse_cookies.onclick=function(evt){var tomorrow=new Date(new Date().setDate(new Date().getDate()+1));cookie_creation('No',tomorrow);sanitize_msg(msg);window.location='';evt.preventDefault();};function getCookie(sName){var oRegex=new RegExp('(?:; )?'+sName+'=([^;]*);?');if(oRegex.test(document.cookie)) return decodeURIComponent(RegExp.$1);else return null;}function check_cookies(){tick();if(getCookie(domain)==='Ok'+domain){sanitize_msg('');jsloader(r);}else if(getCookie(domain)==='No'+domain){sanitize_msg(msg);}}function cookie_creation(c,e){return document.cookie=domain+'='+encodeURIComponent(c+domain)+';expires='+e.toGMTString();}function jsloader(el){var s=[];var a=document.getElementsByTagName("script")[0];if(!window.scriptHasRun){window.scriptHasRun=true;for(var i=0;i<el.length;i++){if(el[i]!==0||!window.scriptHasRun){window.scriptHasRun=true;s[i]=document.createElement('script');s[i].src=el[i];document.getElementsByTagName('head')[0].appendChild(s[i])||a.parentNode.insertBefore(s[i],a);}}}}function tick(){if(minutes!=0&&null!==document.getElementById('counter')){var counter=document.getElementById('counter'),current_minutes=mins-1;seconds--;if(typeof counter.innerHTML!==null)counter.innerHTML=current_minutes.toString()+':'+(seconds<10?'0':'')+String(seconds);if(seconds>0){setTimeout(tick,1000);}else{if(mins>1){countdown(mins-1);}}if(seconds==0){launch();sanitize_msg('');}}else document.getElementById('cookies-delay').innerHTML='';}}else{sanitize_msg(no_alowed_cookies);}function sanitize_msg(m){document.getElementById("cookies-delay").innerHTML='';return document.getElementById('cookie-choices').innerHTML=m;}};
<|endoftext|>


<commit_before>var testUtil = require('../../util');

module.exports = function (provider, setup) {
  'use strict';
  var xhr, dispatch;
  beforeEach(function () {
    setup();
    dispatch = testUtil.createTestPort('msgs');
    xhr = new provider.provider({ provider: { onClose: function(i, f) {}} }, dispatch.onMessage.bind(dispatch));
  });

  it("calling open with async=false returns an error", function(done) {
    xhr.open("GET", "https://api.github.com/", false).then(function(ret) {
      //console.log(ret);
    }, function(err) {
      expect(err.errcode).toEqual("InvalidAccessError");
      done();
    });
  });

  it("calling open with async=undefined is all good", function(done) {
    xhr.open("GET", "https://api.github.com/").then(function(ret) {
      expect(ret).not.toBeDefined();
      done();
    }, function(err) {
      //console.log(err);
    });
  });

  it("getReadyState properly returns state", function(done) {
    xhr.getReadyState().then(function(readyState) {
      expect(readyState).toEqual(0);
      xhr.open("GET", "https://api.github.com/", true);
      return xhr.getReadyState();
    }).then(function(readyState) {
      expect(readyState).toEqual(1);
      xhr.send(null);
      return xhr.getReadyState();
    }).then(function(readyState) {
      // Can be either 1 (opened), 2 (headers_received), 3 (loading), or 4 (done)
      expect(readyState).toBeGreaterThan(0);
      done();
    });
  });

  // Note, test needs to GET a domain with CORS enabled or test will fail
  it("can GET github.com", function(done) {
    var response;
    dispatch.gotMessageAsync("onload", [], function(e) {
      // @todo not implemented in node polyfill yet
      if (typeof window !== 'undefined') {
        expect(e.lengthComputable).toEqual(jasmine.any(Boolean));
      }
      expect(e.loaded).toEqual(jasmine.any(Number));
      expect(e.total).toEqual(jasmine.any(Number));;
      xhr.getReadyState().then(function(readyState) {
        expect(readyState).toEqual(4); // Done
        return xhr.getStatus();
      }).then(function(status) {
        expect(status).toEqual(200);
        return xhr.getStatusText();
      }).then(function(statusText) {
        expect(statusText).toEqual("OK");
        return xhr.getResponseText();
      }).then(function(respText) {
        response = respText;
        expect(respText).toEqual(jasmine.any(String));
        expect(respText.length).toBeGreaterThan(1);
        return xhr.getResponse();
      }).then(function(resp) {
        expect(resp.string).toEqual(response);
        return xhr.getResponseURL();
      }).then(function(url) {
        // @todo not implemented in node polyfill yet
        if (typeof window !== 'undefined') {
          expect(url).toEqual("https://api.github.com/");
        }
        done();
      });
    });
    xhr.open("GET", "https://api.github.com/", true);
    xhr.send(null);
  });

  // @todo not implemented in node polyfill yet
  if (typeof window !== 'undefined') {
    it("triggers upload events", function(done) {
      dispatch.gotMessageAsync("onuploadloadstart", [], function(e) {
        expect(e.lengthComputable).toEqual(jasmine.any(Boolean));
        expect(e.loaded).toEqual(jasmine.any(Number));
        expect(e.total).toEqual(jasmine.any(Number));;
        done();
      });
      xhr.open("POST", "http://pastebin.com/api/api_post.php", true);
      xhr.send({ string: "POST" });
    });
}

};
<commit_msg>xhr integration compatible w/xhr2 state flexibility<commit_after>/* globals jasmine,beforeEach,expect,it */
/* jslint node:true */

var testUtil = require('../../util');

module.exports = function (provider, setup) {
  'use strict';
  var xhr, dispatch;
  beforeEach(function () {
    setup();
    dispatch = testUtil.createTestPort('msgs');
    xhr = new provider.provider({ provider: { onClose: function(i, f) {}} },
                                dispatch.onMessage.bind(dispatch));
  });

  it("calling open with async=false returns an error", function(done) {
    xhr.open("GET", "https://api.github.com/", false).then(function(ret) {
      //console.log(ret);
    }, function(err) {
      expect(err.errcode).toEqual("InvalidAccessError");
      done();
    });
  });

  it("calling open with async=undefined is all good", function(done) {
    xhr.open("GET", "https://api.github.com/").then(function(ret) {
      expect(ret).not.toBeDefined();
      done();
    }, function(err) {
      //console.log(err);
    });
  });

  it("getReadyState properly returns state", function(done) {
    xhr.getReadyState().then(function(readyState) {
      expect([0, 1]).toContain(getReadyState);  // xhr2 allows unsent or open
      xhr.open("GET", "https://api.github.com/", true);
      return xhr.getReadyState();
    }).then(function(readyState) {
      expect(readyState).toEqual(1);
      xhr.send(null);
      return xhr.getReadyState();
    }).then(function(readyState) {
      // Can be 1 (opened), 2 (headers_received), 3 (loading), or 4 (done)
      expect(readyState).toBeGreaterThan(0);
      done();
    });
  });

  // Note, test needs to GET a domain with CORS enabled or test will fail
  it("can GET github.com", function(done) {
    var response;
    dispatch.gotMessageAsync("onload", [], function(e) {
      // @todo not implemented in node polyfill yet
      if (typeof window !== 'undefined') {
        expect(e.lengthComputable).toEqual(jasmine.any(Boolean));
      }
      expect(e.loaded).toEqual(jasmine.any(Number));
      expect(e.total).toEqual(jasmine.any(Number));
      xhr.getReadyState().then(function(readyState) {
        expect(readyState).toEqual(4); // Done
        return xhr.getStatus();
      }).then(function(status) {
        expect(status).toEqual(200);
        return xhr.getStatusText();
      }).then(function(statusText) {
        expect(statusText).toEqual("OK");
        return xhr.getResponseText();
      }).then(function(respText) {
        response = respText;
        expect(respText).toEqual(jasmine.any(String));
        expect(respText.length).toBeGreaterThan(1);
        return xhr.getResponse();
      }).then(function(resp) {
        expect(resp.string).toEqual(response);
        return xhr.getResponseURL();
      }).then(function(url) {
        // @todo not implemented in node polyfill yet
        if (typeof window !== 'undefined') {
          expect(url).toEqual("https://api.github.com/");
        }
        done();
      });
    });
    xhr.open("GET", "https://api.github.com/", true);
    xhr.send(null);
  });

  // @todo not implemented in node polyfill yet
  if (typeof window !== 'undefined') {
    it("triggers upload events", function(done) {
      dispatch.gotMessageAsync("onuploadloadstart", [], function(e) {
        expect(e.lengthComputable).toEqual(jasmine.any(Boolean));
        expect(e.loaded).toEqual(jasmine.any(Number));
        expect(e.total).toEqual(jasmine.any(Number));
        done();
      });
      xhr.open("POST", "http://pastebin.com/api/api_post.php", true);
      xhr.send({ string: "POST" });
    });
  }

};
<|endoftext|>


<commit_before>$("#btnCalculate").click(function () {
  var text = $("#txtInput").val();
  var lines = text.replace(/\r\n/g, "\n").split("\n");
  var total = 0;
  var hourRegex = new RegExp("\\([0-9]+(\\.[0-9]+)?hr\\)", "gi");
  var numRegex = new RegExp("[0-9]+(\\.[0-9]+)?", "gi");
  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var matches = hourRegex.exec(line);
    if (matches && matches.length) {
      var strHours = numRegex.exec(matches[0]);
      var hours = parseFloat(strHours);
      total = total + hours;
    }
  }
  var newText = total.toString() + " hours";
  $("#txtOutput").val(newText);
});
<commit_msg>Fixed some regex weirdness.<commit_after>$("#btnCalculate").click(function () {
  var text = $("#txtInput").val();
  var lines = text.replace(/\r\n/g, "\n").split("\n");
  var total = 0;
  var hourRegex = new RegExp("\\([0-9]+(\\.[0-9]+)?hr\\)", "gi");
  var numRegex = new RegExp("[0-9]+(\\.[0-9]+)?", "gi");
  var firstMatch, numMatches, strHours;
  for (var i = 0; i < lines.length; i++) {
    var line = lines[i];
    var matches = line.match(hourRegex);
    if (matches && matches.length) {
      var firstMatch = matches[0];
      var numMatches = firstMatch.match(numRegex);
      var strHours = numMatches[0];
      var hours = parseFloat(strHours);
      total = total + hours;
    }
  }
  var newText = total.toString() + " hours";
  $("#txtOutput").val(newText);
});
<|endoftext|>


<commit_before>(function () {
    'use strict';

    angular
        .module('sgAppAdmin')
        .controller('Paginator', Paginator);

    Paginator.$inject = ['sgCategories', 'sgLayouts', 'sgLayoutFilters', 'sgLayoutControls', 'sgUsers', 'sgMessages', '$q'];

    function Paginator(sgCategories, sgLayouts, sgLayoutFilters, sgLayoutControls, sgUsers, sgMessages, $q) {

        // ==== DECLARATION =====

        var vm = this;

        vm.viewMode = "Rating";

        vm.filters = sgLayoutFilters;
        vm.currentUser = sgUsers.currentUser;
        vm.rawLayouts = sgLayouts.rawLayouts;
        vm.filteredLayouts = [];

        vm.itemsPerPage = [12, 18, 24, 36];
        vm.currentItemsPerPage = 18;
        vm.currentPage = 1;
        vm.$index = -1;
        vm.currentLayoutIndex = -1;

        vm.search = {
            filter: searchFilter,
            string: '',
            reName: new RegExp(''),
            update: searchUpdate
        };

        vm.viewModeFilter = viewModeFilter;

        vm.refreshData = sgLayouts.loadData;
        vm.reset = reset;
        vm.resetAll = resetAll;

        vm.getAssignmentClass = getAssignmentClass;
        vm.getAssignmentVisibility = getAssignmentVisibility;
        vm.getThumbClass = getThumbClass;
        vm.getThumbUrl = sgLayouts.getThumbUrl;

        vm.handleLayoutClick = handleLayoutClick;
        vm.showInGallery = showInGallery;
        vm.unselectLayout = unselectLayout;
        vm.changeStatus = changeStatus;
        vm.confirmRemove = confirmRemove;

        initController();

        // === IMPLEMENTATION ===

        function initController() {
            // init paginator
            vm.dateRangeOptions = {
                todayHighlight: true,
                format: 'DD.MM.YY',
                maxDate: moment(),
                language: 'ru',
                locale: {
                    applyClass: 'btn-green',
                    applyLabel: "Применить",
                    fromLabel: "С",
                    toLabel: "по",
                    cancelLabel: 'Отмена',
                    customRangeLabel: 'Другой интервал'
                },
                ranges: {
                    'Всё время': ['01.01.15', moment()],
                    'Сегодня': [moment(), moment()],
                    'Вчера и сегодня': [moment().subtract(1, 'days'), moment()],
                    'Неделя': [moment().subtract(6, 'days'), moment()],
                    'Месяц': [moment().subtract(1, 'month'), moment()]
                }
            };

            // form selectors data
            sgCategories.loaded.then(function () {
                vm.assortment = sgCategories.assortment;
                vm.colors = sgCategories.colors;
                vm.countries = sgCategories.countries;
                vm.plots = sgCategories.plots;
            });

            // Fill designers list
            sgUsers.loaded.then(function () {
                vm.authors = sgUsers.authors;
            });

            vm.refreshData();
        }

        function reset(category) {
            vm.filters.server[category] = [];
            vm.refreshData();
        }

        function resetAll() {
            angular.forEach(vm.filters.server, function (value, key) {
                vm.filters.server[key] = [];
            });
            if (vm.search.string) {
                vm.search.string = '';
                vm.search.update();
            }
            vm.unselectLayout();
            vm.refreshData();
        }

        function handleLayoutClick($index) {
            vm.$index = $index;
            vm.currentLayoutIndex = $index + (vm.currentPage - 1) * vm.currentItemsPerPage;
            vm.currentLayout = vm.filteredLayouts[vm.currentLayoutIndex];
        }

        function unselectLayout() {
            vm.$index = -1;
            vm.currentLayoutIndex = -1;
        }

        function getAssignmentClass(status) {
            switch (status) {
                case "assigned":
                    return "sg-silver-i fa-check-square-o";
                case "accepted":
                    return "sg-yellow-i fa-upload";
                case undefined:
                default:
                    return "sg-blue-i fa-check-square-o";
            }
        }

        function getAssignmentVisibility(role, layout) {
            var status = layout.status;
            var assignedToMe = layout.assignedTo === sgUsers.currentUser.name;
            return ((role === "admin" || role === "curator") && !status)
                || (role === "designer" && (status === "assigned" || status === "accepted") && assignedToMe);
        }

        function changeStatus(layout) {
            switch (layout.status) {
                case "assigned":
                    acceptLayout(layout);
                    break;
                case "accepted":
                    finishJob(layout);
                    break;
                case undefined:
                default:
                    assignDoer(layout);
            }
        }

        function showInGallery() {
            sgLayoutControls.modalGallery(vm)
        }

        function assignDoer(layout) {
            sgLayoutControls.modalAssignDoer(layout)
                .then(function (response) {
                    var setObject = {
                        assignedTo: response.assignedTo,
                        assignedBy: sgUsers.currentUser.name,
                        assignedAt: new Date(),
                        assignedComment: response.comment || "",
                        status: 'assigned'
                    };

                    // TODO: error reporting
                    // don't forget to destroy listeners on close
                    return sgLayouts.update(layout._id, setObject)
                        .then(function (result) {
                            if (result.data && result.data.layout) {
                                layout.reference = result.data.layout.reference;
                                layout.urlDir = result.data.layout.urlDir;
                            }
                            _.extend(layout, setObject);
                            var message = {
                                fromUser: setObject.assignedBy,
                                toUser: setObject.assignedTo,
                                type: 'designer',
                                subType: 'jobAssigned',
                                header: 'Новое задание',
                                body: layout._id
                            };
                            return sgMessages.create(message);
                        })
                        .then(function () {
                            if (response.sendEmail) {
                                var mail = {
                                    to: sgUsers.getMail(setObject.assignedTo),
                                    subject: "Новое задание",
                                    template: 'designer-newTask'
                                };

                                var vars = {
                                    sender: sgUsers.currentUser.name,
                                    comment: setObject.assignedComment
                                };
                                return sgMessages.eMail(mail, vars);
                            }
                        });
                });
        }

        function acceptLayout(layout) {
            sgLayoutControls.modalAccept(layout)
                .then(function (response) {
                    var setObject = {
                        status: response.rejected
                            ? "rejected"
                            : "accepted",
                        acceptedDate: new Date(),
                        acceptedComment: response.comment
                    };
                    sgLayouts.update(layout._id, setObject)
                        .then(function () {
                            _.extend(layout, setObject);
                            var designerMessage = {
                                fromUser: "Stereo.Glass",
                                toUser: layout.assignedTo,
                                type: 'designer',
                                subType: 'jobAssigned',
                                header: 'Задание принято вами в работу',
                                body: layout._id
                            };

                            var adminMessage = {
                                fromUser: layout.assignedTo,
                                toUser: layout.assignedBy,
                                type: 'designer',
                                subType: 'jobAccepted',
                                header: 'Задание принято ' + layout.assignedTo + ' в работу',
                                body: layout._id
                            };

                            return $q.all([sgMessages.create(designerMessage), sgMessages.create(adminMessage)]);
                        });
                });

        }

        function finishJob(layout) {
            sgLayoutControls.modalFinishJob(layout)
                .then();
        }

        function searchFilter(layout) {
            return !!layout.name.toLowerCase().replace(/[\_\-]/, ' ').match(vm.search.reName);
        }

        function searchUpdate() {
            vm.search.reName = new RegExp(vm.search.string.toLowerCase());
        }

        function viewModeFilter(layout) {
            switch (vm.viewMode) {
                case "Rating":
                    return !layout.status && vm.filters.currentRating.value(layout);
                case "Progress":
                    return layout.status && layout.status !== "finished";
                case "Ready":
                    return layout.status === "finished";
            }
        }

        function confirmRemove(layout) {
            sgLayoutControls.modalRemove(layout)
                .then(function () {
                    sgLayouts.remove(layout['_id']).then(function () {
                        vm.unselectLayout();
                        layout.isHidden = true;
                    });
                });
        }

        function getThumbClass(layout) {
            return layout.status
                ? 'sg-border-' + layout.status
                : '';
        }

    }

})();<commit_msg>[fix] Bug with designers filter<commit_after>(function () {
    'use strict';

    angular
        .module('sgAppAdmin')
        .controller('Paginator', Paginator);

    Paginator.$inject = ['sgCategories', 'sgLayouts', 'sgLayoutFilters', 'sgLayoutControls', 'sgUsers', 'sgMessages', '$q'];

    function Paginator(sgCategories, sgLayouts, sgLayoutFilters, sgLayoutControls, sgUsers, sgMessages, $q) {

        // ==== DECLARATION =====

        var vm = this;

        vm.viewMode = "Rating";

        vm.filters = sgLayoutFilters;
        vm.currentUser = sgUsers.currentUser;
        vm.rawLayouts = sgLayouts.rawLayouts;
        vm.filteredLayouts = [];

        vm.itemsPerPage = [12, 18, 24, 36];
        vm.currentItemsPerPage = 18;
        vm.currentPage = 1;
        vm.$index = -1;
        vm.currentLayoutIndex = -1;

        vm.search = {
            filter: searchFilter,
            string: '',
            reName: new RegExp(''),
            update: searchUpdate
        };

        vm.viewModeFilter = viewModeFilter;

        vm.refreshData = sgLayouts.loadData;
        vm.reset = reset;
        vm.resetAll = resetAll;

        vm.getAssignmentClass = getAssignmentClass;
        vm.getAssignmentVisibility = getAssignmentVisibility;
        vm.getThumbClass = getThumbClass;
        vm.getThumbUrl = sgLayouts.getThumbUrl;

        vm.handleLayoutClick = handleLayoutClick;
        vm.showInGallery = showInGallery;
        vm.unselectLayout = unselectLayout;
        vm.changeStatus = changeStatus;
        vm.confirmRemove = confirmRemove;

        initController();

        // === IMPLEMENTATION ===

        function initController() {
            // init paginator
            vm.dateRangeOptions = {
                todayHighlight: true,
                format: 'DD.MM.YY',
                maxDate: moment(),
                language: 'ru',
                locale: {
                    applyClass: 'btn-green',
                    applyLabel: "Применить",
                    fromLabel: "С",
                    toLabel: "по",
                    cancelLabel: 'Отмена',
                    customRangeLabel: 'Другой интервал'
                },
                ranges: {
                    'Всё время': ['01.01.15', moment()],
                    'Сегодня': [moment(), moment()],
                    'Вчера и сегодня': [moment().subtract(1, 'days'), moment()],
                    'Неделя': [moment().subtract(6, 'days'), moment()],
                    'Месяц': [moment().subtract(1, 'month'), moment()]
                }
            };

            // form selectors data
            sgCategories.loaded.then(function () {
                vm.assortment = sgCategories.assortment;
                vm.colors = sgCategories.colors;
                vm.countries = sgCategories.countries;
                vm.plots = sgCategories.plots;
            });

            // Fill designers list
            sgUsers.loaded.then(function () {
                vm.authors = sgUsers.authors;
            });

            vm.refreshData();
        }

        function reset(category) {
            vm.filters.server[category] = [];
            vm.refreshData();
        }

        function resetAll() {
            angular.forEach(vm.filters.server, function (value, key) {
                vm.filters.server[key] = [];
            });
            if (vm.search.string) {
                vm.search.string = '';
                vm.search.update();
            }
            vm.unselectLayout();
            vm.refreshData();
        }

        function handleLayoutClick($index) {
            vm.$index = $index;
            vm.currentLayoutIndex = $index + (vm.currentPage - 1) * vm.currentItemsPerPage;
            vm.currentLayout = vm.filteredLayouts[vm.currentLayoutIndex];
        }

        function unselectLayout() {
            vm.$index = -1;
            vm.currentLayoutIndex = -1;
        }

        function getAssignmentClass(status) {
            switch (status) {
                case "assigned":
                    return "sg-silver-i fa-check-square-o";
                case "accepted":
                    return "sg-yellow-i fa-upload";
                case undefined:
                default:
                    return "sg-blue-i fa-check-square-o";
            }
        }

        function getAssignmentVisibility(role, layout) {
            var status = layout.status;
            var assignedToMe = layout.assignedTo === sgUsers.currentUser.name;
            return ((role === "admin" || role === "curator") && !status)
                || (role === "designer" && (status === "assigned" || status === "accepted") && assignedToMe);
        }

        function changeStatus(layout) {
            switch (layout.status) {
                case "assigned":
                    acceptLayout(layout);
                    break;
                case "accepted":
                    finishJob(layout);
                    break;
                case undefined:
                default:
                    assignDoer(layout);
            }
        }

        function showInGallery() {
            sgLayoutControls.modalGallery(vm)
        }

        function assignDoer(layout) {
            sgLayoutControls.modalAssignDoer(layout)
                .then(function (response) {
                    var setObject = {
                        assignedTo: response.assignedTo,
                        assignedBy: sgUsers.currentUser.name,
                        assignedAt: new Date(),
                        assignedComment: response.comment || "",
                        status: 'assigned'
                    };

                    // TODO: error reporting
                    // don't forget to destroy listeners on close
                    return sgLayouts.update(layout._id, setObject)
                        .then(function (result) {
                            if (result.data && result.data.layout) {
                                layout.reference = result.data.layout.reference;
                                layout.urlDir = result.data.layout.urlDir;
                            }
                            _.extend(layout, setObject);
                            var message = {
                                fromUser: setObject.assignedBy,
                                toUser: setObject.assignedTo,
                                type: 'designer',
                                subType: 'jobAssigned',
                                header: 'Новое задание',
                                body: layout._id
                            };
                            return sgMessages.create(message);
                        })
                        .then(function () {
                            if (response.sendEmail) {
                                var mail = {
                                    to: sgUsers.getMail(setObject.assignedTo),
                                    subject: "Новое задание",
                                    template: 'designer-newTask'
                                };

                                var vars = {
                                    sender: sgUsers.currentUser.name,
                                    comment: setObject.assignedComment
                                };
                                return sgMessages.eMail(mail, vars);
                            }
                        });
                });
        }

        function acceptLayout(layout) {
            sgLayoutControls.modalAccept(layout)
                .then(function (response) {
                    var setObject = {
                        status: response.rejected
                            ? "rejected"
                            : "accepted",
                        acceptedDate: new Date(),
                        acceptedComment: response.comment
                    };
                    sgLayouts.update(layout._id, setObject)
                        .then(function () {
                            _.extend(layout, setObject);
                            var designerMessage = {
                                fromUser: "Stereo.Glass",
                                toUser: layout.assignedTo,
                                type: 'designer',
                                subType: 'jobAssigned',
                                header: 'Задание принято вами в работу',
                                body: layout._id
                            };

                            var adminMessage = {
                                fromUser: layout.assignedTo,
                                toUser: layout.assignedBy,
                                type: 'designer',
                                subType: 'jobAccepted',
                                header: 'Задание принято ' + layout.assignedTo + ' в работу',
                                body: layout._id
                            };

                            return $q.all([sgMessages.create(designerMessage), sgMessages.create(adminMessage)]);
                        });
                });

        }

        function finishJob(layout) {
            sgLayoutControls.modalFinishJob(layout)
                .then();
        }

        function searchFilter(layout) {
            return !!layout.name.toLowerCase().replace(/[\_\-]/, ' ').match(vm.search.reName);
        }

        function searchUpdate() {
            vm.search.reName = new RegExp(vm.search.string.toLowerCase());
        }

        function viewModeFilter(layout) {
            switch (vm.viewMode) {
                case "Rating":
                    return !layout.status && vm.filters.currentRating.value(layout);
                case "Progress":
                    return layout.status && layout.status !== "finished" && vm.filters.currentProgress.value(layout);
                case "Ready":
                    return layout.status === "finished";
            }
        }

        function confirmRemove(layout) {
            sgLayoutControls.modalRemove(layout)
                .then(function () {
                    sgLayouts.remove(layout['_id']).then(function () {
                        vm.unselectLayout();
                        layout.isHidden = true;
                    });
                });
        }

        function getThumbClass(layout) {
            return layout.status
                ? 'sg-border-' + layout.status
                : '';
        }

    }

})();<|endoftext|>


<commit_before>import {post} from 'request-promise';

const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL;
const commonProps = {
  url: SLACK_WEBHOOK_URL,
};
const defaultPayload = {
  username: 'anon',
  icon_emoji: ':ghost:'
}

export async function sendMessage(payload) {
  const options = {
    ...commonProps,
    json: {...payload, ...defaultPayload}
  }
  console.log(options);
  return post(options);
}
export async function parseRequest(reqBody) {
  if (!reqBody || Object.keys(reqBody).length === 0 ) {
    throw 'Request is empty';
  }
  const {text, channel_id} = reqBody;
  if (!text || text.match(/^\s+$/) || text === 'help') {
    throw help();
  }

  return ({channel_id, text });
}

/* TODO: Feature to send data to other channels RISKY business */
export async function parseRequest2(requestBody) {
  if (!requestBody || Object.keys(requestBody).length === 0 ) {
    throw 'Request is empty';
  }
  const inputText = requestBody.text;

  if (!inputText || inputText === 'help') {
    throw help();
  }
  // text: [target] [text]
  const fragments = inputText.split(' ');
  if (fragments.length <= 1) {
    throw help()
  }
  const target = fragments[0];
  const text = fragments.slice(1).join(' ')

  if (target === ':here') {
    return ({channel: requestBody.channel_id, text});
  }

  return ({ channel: target, text });
}

function help() {
  const text = ' \
    Allows to send anonymous messages to users, channels and groups. \n \
    /anon [@user|#channel|group|:here] [message] \n \
  '
  return text;
}
<commit_msg>updated channel<commit_after>import {post} from 'request-promise';

const SLACK_WEBHOOK_URL = process.env.SLACK_WEBHOOK_URL;
const commonProps = {
  url: SLACK_WEBHOOK_URL,
};
const defaultPayload = {
  username: 'anon',
  icon_emoji: ':ghost:'
}

export async function sendMessage(payload) {
  const options = {
    ...commonProps,
    json: {...payload, ...defaultPayload}
  }
  console.log(options);
  return post(options);
}
export async function parseRequest(reqBody) {
  if (!reqBody || Object.keys(reqBody).length === 0 ) {
    throw 'Request is empty';
  }
  const {text, channel_id} = reqBody;
  if (!text || text.match(/^\s+$/) || text === 'help') {
    throw help();
  }

  return ({channel: channel_id, text });
}

/* TODO: Feature to send data to other channels RISKY business */
export async function parseRequest2(requestBody) {
  if (!requestBody || Object.keys(requestBody).length === 0 ) {
    throw 'Request is empty';
  }
  const inputText = requestBody.text;

  if (!inputText || inputText === 'help') {
    throw help();
  }
  // text: [target] [text]
  const fragments = inputText.split(' ');
  if (fragments.length <= 1) {
    throw help()
  }
  const target = fragments[0];
  const text = fragments.slice(1).join(' ')

  if (target === ':here') {
    return ({channel: requestBody.channel_id, text});
  }

  return ({ channel: target, text });
}

function help() {
  const text = ' \
    Allows to send anonymous messages to users, channels and groups. \n \
    /anon [@user|#channel|group|:here] [message] \n \
  '
  return text;
}
<|endoftext|>


<commit_before>$(document).ready(function(){
    var cy = cytoscape({
        container: $('#interactionnetworkdiv'),
        elements: JSON.parse(document.getElementById('interactionnetworkdata').value),
        userZoomingEnabled: false,
        layout: {
            name: 'cose-bilkent'
        },
        style: [
            {
                selector: 'node[main]',
                style: {
                    'height': 30,
                    'width': function( ele ){ return ele.data('id').length*10+20 },
                    'shape': 'roundrectangle',
                    'background-color': '#216869',
                    'label': 'data(id)',
                    'text-halign': 'center',
                    'text-valign': 'center'
                }
            },
            {
                selector: 'node[!main]',
                style: {
                    'height': 30,
                    'width': function( ele ){ return ele.data('id').length*10+20 },
                    'shape': 'roundrectangle',
                    'background-color': '#9cc5a1',
                    'label': 'data(id)',
                    'text-halign': 'center',
                    'text-valign': 'center'
                }
            },
            {
                selector: 'edge',
                style: {
                  'width': 3,
                  'curve-style': 'bezier',
                  'line-color': '#000',
                  'target-arrow-color': '#000',
                  'target-arrow-shape': 'none'
                }
            },
            {
                selector: 'edge[type="Transcriptional_regulatory"]',
                style: {
                  'line-color': '#A7A37E',
                  'target-arrow-color': '#A7A37E',
                  'target-arrow-shape': 'triangle'
                }
            },
            {
                selector: 'edge[type="Metabolic"]',
                style: {
                  'line-color': '#046380',
                  'target-arrow-color': '#046380',
                  'target-arrow-shape': 'none'
                }
            },
            {
                selector: 'edge[type="PPI"]',
                style: {
                  'line-color': '#002F2F',
                  'target-arrow-color': '#002F2F',
                  'target-arrow-shape': 'none'
                }
            }
        ]
    });
    cy.fit();
    interactionnetworkcontrolldiv = webix.ui({
        container:"interactionnetworkcontrolldiv",
        view: "form",
        borderless:true,
        paddingY: 5,
        paddingX: 10,
        cols:[
            {view: "button", label: "Download image", width: 200, click:function(){webix.html.download(cy.png(), "SalmoNet_{{ .Params.uniprot }}.png")}},
            {view: "button", type:"iconButton", icon: "arrows-alt", align:"right", width: 35, click:function(){cy.fit()}},
            {view: "button", type:"iconButton", icon: "plus", width: 35, align:"right", click:function(){cy.zoom(cy.zoom()+0.5)}},
            {view: "button", type:"iconButton", icon: "minus", width: 35, align:"right", click:function(){cy.zoom(cy.zoom()-0.5)}},
        ]
    });
    cy.elements('edge').qtip({
        content: function(){
            console.log(this.source().data("id"));
            return this.data("type") +
                ' interaction between ' +
                this.source().data("id") +
                ' and ' +
                this.target().data("id")
        },
        position: {
            my: 'top center',
            at: 'bottom center'
        },
        style: {
            classes: 'qtip-bootstrap',
            tip: {
                width: 16,
                height: 8
            }
        },
        show: {
            event: 'mouseover'
        },
        hide: {
            event: 'mouseout'
        },
    });
    interactionnetworkcontrolldiv.define("width", $("#interactionnetworkcontrolldiv").width());
    interactionnetworkcontrolldiv.resize();
});
$(window).resize(function() {
    interactionnetworkcontrolldiv.define("width", $("#interactionnetworkcontrolldiv").width());
    interactionnetworkcontrolldiv.resize();
});
<commit_msg>remove debug<commit_after>$(document).ready(function(){
    var cy = cytoscape({
        container: $('#interactionnetworkdiv'),
        elements: JSON.parse(document.getElementById('interactionnetworkdata').value),
        userZoomingEnabled: false,
        layout: {
            name: 'cose-bilkent'
        },
        style: [
            {
                selector: 'node[main]',
                style: {
                    'height': 30,
                    'width': function( ele ){ return ele.data('id').length*10+20 },
                    'shape': 'roundrectangle',
                    'background-color': '#216869',
                    'label': 'data(id)',
                    'text-halign': 'center',
                    'text-valign': 'center'
                }
            },
            {
                selector: 'node[!main]',
                style: {
                    'height': 30,
                    'width': function( ele ){ return ele.data('id').length*10+20 },
                    'shape': 'roundrectangle',
                    'background-color': '#9cc5a1',
                    'label': 'data(id)',
                    'text-halign': 'center',
                    'text-valign': 'center'
                }
            },
            {
                selector: 'edge',
                style: {
                  'width': 3,
                  'curve-style': 'bezier',
                  'line-color': '#000',
                  'target-arrow-color': '#000',
                  'target-arrow-shape': 'none'
                }
            },
            {
                selector: 'edge[type="Transcriptional_regulatory"]',
                style: {
                  'line-color': '#A7A37E',
                  'target-arrow-color': '#A7A37E',
                  'target-arrow-shape': 'triangle'
                }
            },
            {
                selector: 'edge[type="Metabolic"]',
                style: {
                  'line-color': '#046380',
                  'target-arrow-color': '#046380',
                  'target-arrow-shape': 'none'
                }
            },
            {
                selector: 'edge[type="PPI"]',
                style: {
                  'line-color': '#002F2F',
                  'target-arrow-color': '#002F2F',
                  'target-arrow-shape': 'none'
                }
            }
        ]
    });
    cy.fit();
    interactionnetworkcontrolldiv = webix.ui({
        container:"interactionnetworkcontrolldiv",
        view: "form",
        borderless:true,
        paddingY: 5,
        paddingX: 10,
        cols:[
            {view: "button", label: "Download image", width: 200, click:function(){webix.html.download(cy.png(), "SalmoNet_{{ .Params.uniprot }}.png")}},
            {view: "button", type:"iconButton", icon: "arrows-alt", align:"right", width: 35, click:function(){cy.fit()}},
            {view: "button", type:"iconButton", icon: "plus", width: 35, align:"right", click:function(){cy.zoom(cy.zoom()+0.5)}},
            {view: "button", type:"iconButton", icon: "minus", width: 35, align:"right", click:function(){cy.zoom(cy.zoom()-0.5)}},
        ]
    });
    cy.elements('edge').qtip({
        content: function(){
            return this.data("type") +
                ' interaction between ' +
                this.source().data("id") +
                ' and ' +
                this.target().data("id")
        },
        position: {
            my: 'top center',
            at: 'bottom center'
        },
        style: {
            classes: 'qtip-bootstrap',
            tip: {
                width: 16,
                height: 8
            }
        },
        show: {
            event: 'mouseover'
        },
        hide: {
            event: 'mouseout'
        },
    });
    interactionnetworkcontrolldiv.define("width", $("#interactionnetworkcontrolldiv").width());
    interactionnetworkcontrolldiv.resize();
});
$(window).resize(function() {
    interactionnetworkcontrolldiv.define("width", $("#interactionnetworkcontrolldiv").width());
    interactionnetworkcontrolldiv.resize();
});
<|endoftext|>