<commit_before>'use strict';

formsAngular.controller('NavCtrl', ['$scope', '$data', '$location', '$filter', '$locationParse', '$controller', function ($scope, $data, $location, $filter, $locationParse, $controller) {

    $scope.items = [];

    function loadControllerAndMenu(controllerName, level) {
        var locals = {}, addThis;

        controllerName += 'Ctrl';
        locals.$scope = $scope.scopes[level] = $scope.$new();
        try {
            $controller(controllerName, locals);
            if ($scope.routing.newRecord) {
                addThis = "creating";
            } else if ($scope.routing.id) {
                addThis = "editing";
            } else {
                addThis = "listing";
            }
            if (angular.isObject(locals.$scope.contextMenu)) {
                angular.forEach(locals.$scope.contextMenu, function (value) {
                    if (value[addThis]) {
                        $scope.items.push(value);
                    }
                })
            }
        }
        catch (error) {
            if (/is not a function, got undefined/.test(error.message)) {
                // No such controller - don't care
            } else {
                console.log("Unable to instantiate " + controllerName + " - " + error.message);
            }
        }
    }

    $scope.$on('$locationChangeSuccess', function (event, newUrl, oldUrl) {

        $scope.routing = $locationParse($location.$$path);

        $scope.items = [];

        if ($scope.routing.analyse) {
            $scope.contextMenu = 'Report';
            $scope.items = [
                {
                    broadcast: 'exportToPDF',
                    text: "PDF"
                },
                {
                    broadcast: 'exportToCSV',
                    text: "CSV"
                }
            ]
        } else if ($scope.routing.modelName) {

            angular.forEach($scope.scopes, function (value, key) {
                value.$destroy();
            });
            $scope.scopes = [];
            $data.record = {};
            $data.disableFunctions = {};
            $data.dataEventFunctions = {};
            delete $data.dropDownDisplay;
            delete $data.modelNameDisplay;
            // Now load context menu.  For /person/client/:id/edit we need
            // to load PersonCtrl and PersonClientCtrl
            var modelName = $filter('titleCase')($scope.routing.modelName, false);
            loadControllerAndMenu(modelName, 0);
            if ($scope.routing.formName) {
                loadControllerAndMenu(modelName + $filter('titleCase')($scope.routing.formName, true), 1);
            }
            $scope.contextMenu = $data.dropDownDisplay || $data.modelNameDisplay || modelName;
        }
    });

    $scope.doClick = function (index) {
        if ($scope.items[index].broadcast) {
            $scope.$broadcast($scope.items[index].broadcast)
        } else {
            // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
            var args = $scope.items[index].args || [],
                fn = $scope.items[index].fn;
            switch (args.length) {
                case  0:
                    fn();
                    break;
                case  1:
                    fn(args[0]);
                    break;
                case  2:
                    fn(args[0], args[1]);
                    break;
                case  3:
                    fn(args[0], args[1], args[2]);
                    break;
                case  4:
                    fn(args[0], args[1], args[2], args[3]);
                    break;
            }
        }
    }
}]);
<commit_msg>Don't strip spaces from model name when generating menu text - fix regression<commit_after>'use strict';

formsAngular.controller('NavCtrl', ['$scope', '$data', '$location', '$filter', '$locationParse', '$controller', function ($scope, $data, $location, $filter, $locationParse, $controller) {

    $scope.items = [];

    function loadControllerAndMenu(controllerName, level) {
        var locals = {}, addThis;

        controllerName += 'Ctrl';
        locals.$scope = $scope.scopes[level] = $scope.$new();
        try {
            $controller(controllerName, locals);
            if ($scope.routing.newRecord) {
                addThis = "creating";
            } else if ($scope.routing.id) {
                addThis = "editing";
            } else {
                addThis = "listing";
            }
            if (angular.isObject(locals.$scope.contextMenu)) {
                angular.forEach(locals.$scope.contextMenu, function (value) {
                    if (value[addThis]) {
                        $scope.items.push(value);
                    }
                })
            }
        }
        catch (error) {
            if (/is not a function, got undefined/.test(error.message)) {
                // No such controller - don't care
            } else {
                console.log("Unable to instantiate " + controllerName + " - " + error.message);
            }
        }
    }

    $scope.$on('$locationChangeSuccess', function (event, newUrl, oldUrl) {

        $scope.routing = $locationParse($location.$$path);

        $scope.items = [];

        if ($scope.routing.analyse) {
            $scope.contextMenu = 'Report';
            $scope.items = [
                {
                    broadcast: 'exportToPDF',
                    text: "PDF"
                },
                {
                    broadcast: 'exportToCSV',
                    text: "CSV"
                }
            ]
        } else if ($scope.routing.modelName) {

            angular.forEach($scope.scopes, function (value, key) {
                value.$destroy();
            });
            $scope.scopes = [];
            $data.record = {};
            $data.disableFunctions = {};
            $data.dataEventFunctions = {};
            delete $data.dropDownDisplay;
            delete $data.modelNameDisplay;
            // Now load context menu.  For /person/client/:id/edit we need
            // to load PersonCtrl and PersonClientCtrl
            var modelName = $filter('titleCase')($scope.routing.modelName, true);
            loadControllerAndMenu(modelName, 0);
            if ($scope.routing.formName) {
                loadControllerAndMenu(modelName + $filter('titleCase')($scope.routing.formName, true), 1);
            }
            $scope.contextMenu = $data.dropDownDisplay || $data.modelNameDisplay || $filter('titleCase')($scope.routing.modelName, false);
        }
    });

    $scope.doClick = function (index) {
        if ($scope.items[index].broadcast) {
            $scope.$broadcast($scope.items[index].broadcast)
        } else {
            // Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
            var args = $scope.items[index].args || [],
                fn = $scope.items[index].fn;
            switch (args.length) {
                case  0:
                    fn();
                    break;
                case  1:
                    fn(args[0]);
                    break;
                case  2:
                    fn(args[0], args[1]);
                    break;
                case  3:
                    fn(args[0], args[1], args[2]);
                    break;
                case  4:
                    fn(args[0], args[1], args[2], args[3]);
                    break;
            }
        }
    }
}]);
<|endoftext|>


<commit_before>define([
  'jquery',
  'underscore',
  'backbone',
  'collections/topic',
  'helpers/conf',
  'helpers/nav'
], function($, _, Backbone, TopicCollection, ConfHelper, NavHelper) {
  return {

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    hidePopover: function () {
      if (this.currentPopover) {
        $(this.currentPopover).popover ('hide');
        this.currentPopover = 0;
      }
    },

    // FIXME: this is a complete mess. needs serious refactoring
    popover: function (ev) {

      var that = this;
      var link = $(ev.currentTarget).attr ('href');

      if (this.isLoading) {
        return false;
      }

      if (this.currentPopover == ev.currentTarget) {
        if ($(ev.currentTarget).attr ('data-content-url')) {
          location.href = $(ev.currentTarget).attr ('href');
          return true;
        } else {
          return false;
        }
      }

      this.hidePopover ();

      // TODO: expand this
      var position = function (context, source) {
        var position = $(source).position ();
        var main_position = $(that.el).width ();

        if ($(window).width () < 767) {
          return "auto";
        }

        if (position.top < 100)
          return "bottom";

        if (position.left < 300)
          return "auto left";

        return "auto top";
      };

      // external link

      // FIXME: this is shitty code I've ever written
      //        code repeats, hard to read etc.
      //        need to refactor ASAP

      if (link.match (/^http(s)*:\/\//)) {

        // do nothing if content is already loaded
        if ($(ev.currentTarget).attr ('data-loaded')) {
          return false;
        }

        if ((youtube_id = this.parseYoutubeUrl (link)) != false) {
          if (ConfHelper.getOption ('youtube')) {
            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }
          return false;
        }

        // check if its image
        // FIXME: 80+
        if (link.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?/i)) {

          if (ConfHelper.getOption ('images')) {

            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }

          return false;

        }

        if (!ConfHelper.getOption ('readability')) {
          window.open (link);
          return false;
        }

        // get content from readability if external url is not an image
        $.ajax ('https://readability.com/api/content/v1/parser?url=' +
                escape (link) + '&token=' +
                // token supposed to be secret but who cares
                'd83f7c87d05f46dcff11e87cbe4b278268f30132'
               ).done (function (data) {

                  $(ev.currentTarget).after ('

' +
                                             data.content +
                                             '

');
                  $(ev.currentTarget).attr ('data-loaded', 'true');

               }).error (function () {
                 window.open (link);
               });

        return false;
      }

      if ($(ev.currentTarget).attr ('data-content')) {
        that.currentPopover = ev.currentTarget;
        $(ev.currentTarget).popover ('show');
        return false;
      }

      NavHelper.loader(this.isLoading = true);

      var topicCollection = new TopicCollection ();
      topicCollection.external_url = link;
      topicCollection.order = 0;
      topicCollection.fetch ({
        success: function (entries) {

          NavHelper.loader(that.isLoading = false);

          if (!ConfHelper.getOption ('popover')) {
            location.href = '#t/0/' + topicCollection.external_url;
            return;
          }

          $(ev.currentTarget).attr ('data-content',
                   $('
' + entries.at (0).get ('content') + '
').text ());
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          $(ev.currentTarget).attr ('data-content-url', 'true');
          $(ev.currentTarget).attr ('href', "#t/0/" + topicCollection.external_url);

          that.currentPopover = ev.currentTarget;
        },

        error: function () {
          $(ev.currentTarget).attr ('data-content',
            '404 böyle bir başlık/entry yok')
          $(ev.currentTarget).popover ({ placement: position,
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          NavHelper.loader(that.isLoading = false);

          that.currentPopover = ev.currentTarget;
        }
      });

      return false;

    },

    trigger: function (ev) {

      if (this.currentPopover) {
        this.hidePopover ();
      }

      return false;
    },

    reset: function () {
      this.currentPopover = false;
    }

  };
});
<commit_msg>Remove position function<commit_after>define([
  'jquery',
  'underscore',
  'backbone',
  'collections/topic',
  'helpers/conf',
  'helpers/nav'
], function($, _, Backbone, TopicCollection, ConfHelper, NavHelper) {
  return {

    parseYoutubeUrl: function (url) {
      // FIXME: 80+
      var regExp = /^.*((youtu.be\/)|(v\/)|(\/u\/\w\/)|(embed\/)|(watch\?))\??v?=?([^#\&\?]*).*/;
      var match = url.match (regExp);
      if (match && match[7].length == 11){
        return match[7];
      } else {
        return false;
      }
    },

    hidePopover: function () {
      if (this.currentPopover) {
        $(this.currentPopover).popover ('hide');
        this.currentPopover = 0;
      }
    },

    // FIXME: this is a complete mess. needs serious refactoring
    popover: function (ev) {

      var that = this;
      var link = $(ev.currentTarget).attr ('href');

      if (this.isLoading) {
        return false;
      }

      if (this.currentPopover == ev.currentTarget) {
        if ($(ev.currentTarget).attr ('data-content-url')) {
          location.href = $(ev.currentTarget).attr ('href');
          return true;
        } else {
          return false;
        }
      }

      this.hidePopover ();

      // external link

      // FIXME: this is shitty code I've ever written
      //        code repeats, hard to read etc.
      //        need to refactor ASAP

      if (link.match (/^http(s)*:\/\//)) {

        // do nothing if content is already loaded
        if ($(ev.currentTarget).attr ('data-loaded')) {
          return false;
        }

        if ((youtube_id = this.parseYoutubeUrl (link)) != false) {
          if (ConfHelper.getOption ('youtube')) {
            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }
          return false;
        }

        // check if its image
        // FIXME: 80+
        if (link.match(/(?:([^:\/?#]+):)?(?:\/\/([^\/?#]*))?([^?#]*\.(?:jpg|gif|png))(?:\?([^#]*))?(?:#(.*))?/i)) {

          if (ConfHelper.getOption ('images')) {

            $(ev.currentTarget).after ('

');
            $(ev.currentTarget).attr ('data-loaded', 'true');
          } else {
            window.open (link);
          }

          return false;

        }

        if (!ConfHelper.getOption ('readability')) {
          window.open (link);
          return false;
        }

        // get content from readability if external url is not an image
        $.ajax ('https://readability.com/api/content/v1/parser?url=' +
                escape (link) + '&token=' +
                // token supposed to be secret but who cares
                'd83f7c87d05f46dcff11e87cbe4b278268f30132'
               ).done (function (data) {

                  $(ev.currentTarget).after ('

' +
                                             data.content +
                                             '

');
                  $(ev.currentTarget).attr ('data-loaded', 'true');

               }).error (function () {
                 window.open (link);
               });

        return false;
      }

      if ($(ev.currentTarget).attr ('data-content')) {
        that.currentPopover = ev.currentTarget;
        $(ev.currentTarget).popover ('show');
        return false;
      }

      NavHelper.loader(this.isLoading = true);

      var topicCollection = new TopicCollection ();
      topicCollection.external_url = link;
      topicCollection.order = 0;
      topicCollection.fetch ({
        success: function (entries) {

          NavHelper.loader(that.isLoading = false);

          if (!ConfHelper.getOption ('popover')) {
            location.href = '#t/0/' + topicCollection.external_url;
            return;
          }

          $(ev.currentTarget).attr ('data-content',
                   $('
' + entries.at (0).get ('content') + '
').text ());
          $(ev.currentTarget).popover ({ placement: 'auto right',
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          $(ev.currentTarget).attr ('data-content-url', 'true');
          $(ev.currentTarget).attr ('href', "#t/0/" + topicCollection.external_url);

          that.currentPopover = ev.currentTarget;
        },

        error: function () {
          $(ev.currentTarget).attr ('data-content',
            '404 böyle bir başlık/entry yok')
          $(ev.currentTarget).popover ({ placement: 'auto right',
                                         trigger: 'manual' });
          $(ev.currentTarget).popover ('show');

          NavHelper.loader(that.isLoading = false);

          that.currentPopover = ev.currentTarget;
        }
      });

      return false;

    },

    trigger: function (ev) {

      if (this.currentPopover) {
        this.hidePopover ();
      }

      return false;
    },

    reset: function () {
      this.currentPopover = false;
    }

  };
});
<|endoftext|>


<commit_before>/* global Cervus */

const game = new Cervus.core.Game({
  width: window.innerWidth,
  height: window.innerHeight,
  light_intensity: 0.4,
  // clear_color: 'ff00ff'
  // fps: 10
});

game.camera.position = [0, 1, 2];
game.camera.rotate_rl(Math.PI);
game.camera.keyboard_controlled = true;
// game.camera.mouse_controlled = true;

Cervus.core.model_loader('models/birdd.json').then((models) => {
  for(let i=0; i< 5000; i++) {
    setTimeout(() => {
      create_bird(
        50 - Math.random() * 100,
        50 - Math.random() * 100,
        50 - Math.random() * 100,
        models[0].scale,
        models
      );
    }, 0);
    // create_bird();
  }
}).catch(console.log);

const create_bird = (x = 0, y = 0, z = 0, scale, frames) => {
  let animated_model;
  animated_model = new Cervus.core.AnimatedEntity({
    material: Cervus.materials.basic,
    color:  '#ff00ff',
    frame_time: 16,
    position: [x, y, z],
    scale: scale
  });
  animated_model.frames = frames;
  animated_model.rotate_ud(Math.PI * 1.5);
  animated_model.create_buffers();
  // animated_model.current_tick = ~~(Math.random()*100);
  // animated_model.current_frame = ~~(Math.random()*frames.length);
  // animated_model.next_frame = animated_model.get_next_frame();
  game.add(animated_model);
};

game.add_frame_action(() => {
  game.light_position = game.camera.position;
});
<commit_msg>:running: typo fix<commit_after>/* global Cervus */

const game = new Cervus.core.Game({
  width: window.innerWidth,
  height: window.innerHeight,
  light_intensity: 0.4,
  // clear_color: 'ff00ff'
  // fps: 10
});

game.camera.position = [0, 1, 2];
game.camera.rotate_rl(Math.PI);
game.camera.keyboard_controlled = true;
// game.camera.mouse_controlled = true;

Cervus.core.model_loader('models/bird.json').then((models) => {
  for(let i=0; i< 5000; i++) {
    setTimeout(() => {
      create_bird(
        50 - Math.random() * 100,
        50 - Math.random() * 100,
        50 - Math.random() * 100,
        models[0].scale,
        models
      );
    }, 0);
    // create_bird();
  }
}).catch(console.log);

const create_bird = (x = 0, y = 0, z = 0, scale, frames) => {
  let animated_model;
  animated_model = new Cervus.core.AnimatedEntity({
    material: Cervus.materials.basic,
    color:  '#ff00ff',
    frame_time: 16,
    position: [x, y, z],
    scale: scale
  });
  animated_model.frames = frames;
  animated_model.rotate_ud(Math.PI * 1.5);
  animated_model.create_buffers();
  // animated_model.current_tick = ~~(Math.random()*100);
  // animated_model.current_frame = ~~(Math.random()*frames.length);
  // animated_model.next_frame = animated_model.get_next_frame();
  game.add(animated_model);
};

game.add_frame_action(() => {
  game.light_position = game.camera.position;
});
<|endoftext|>


<commit_before>
var KSUtils = Class.create({

    /**
     *  @param int verboseLevel (0=Silenced,1=Console,2=BrowserAlert)
     *
     */
    initialize: function () {

        this._vl = 0;
    },
    setVerboseLevel: function (verboseLevel) {

        this._vl = verboseLevel;
    },
    log: function (msg) {

        switch (this._vl) {

            case 2:
                alert(msg);
            case 1:
                console.log(msg);
                break;
            case 0:
            default:
                // Silence
        }
    }
});

var ManagementPanel = Class.create(KS, {

    initialize: function () {

        this._page = "managementPanel.html";
    },
    openPage: function ($super) {

        $super(this._page);
    },
    close: function ($super) {

        //$super();
    },
    openSettings: function (id) {

        //ks.scriptSettingsPanel.openPage(id);
    },
    disable: function (id) {

        //db.disableScript(id);

        //$('#user-script-'+id).addClass('disabled');
        //$('button','#us-list tbody tr td').attr('disabled','disabled');
    },
    remove: function (id) {

        //db.remove(id);

        //$('#user-script-'+id).remove();
    }
});

var NewUserScriptPanel = Class.create(KS, {

    initialize: function () {

        this._page = "newUserScriptPanel.html";
    },
    openPage: function ($super) {

        $super(this._page);
    },
    close: function ($super) {

        //$super();
    },
    save: function (newUserScriptForm) {
        /*
        code = newUserScriptForm.us-code;

        us = new UserScript(code);

        name = us.getName();
        desc = us.getDescription();
        includes = us.getIncludes().join(",");
        excludes = us.getExcludes().join(",");
        disabled = 0;

        db.create(name, desc, includes, excludes, code, disabled);
        */
    },
    autoSave: function () {

    }
});

var ScriptSettingsPanel = Class.create(KS, {

    initialize: function () {

        this._page = "scriptSettingsPanel.html";
    },
    openPage: function ($super, scriptId) {

        this._scriptId = scriptId;

        $super(this._page);

        //this.showUserSettings();
    },
    close: function ($super) {

        //$super();
    },
    showUserSettings: function () {

    },
    showScriptSettings: function () {

    },
    showScriptEdition: function () {

    },
    saveUserSettings: function () {

    },
    saveScriptSettings: function () {

    },
    saveScriptEdition: function (userScriptForm) {
        /*
        id = userScriptForm.us-id;

        code = userScriptForm.us-code;

        us = new UserScript(code);

        name = us.getName();
        desc = us.getDescription();
        includes = us.getIncludes().join(",");
        excludes = us.getExcludes().join(",");
        disabled = userScriptForm.isDisabled;

        db.update(name, desc, includes, excludes, code, disabled, id);
        */
    }
});

var KS = Class.create({

    initialize: function () {

        this._isTabOpen = false;

        this.defaultPage = 'main.html';

        this._previousPage = null;
        this._currentPage = this.defaultPage;

        this._tbItems = safari.extension.toolbarItems;

        this._tab = null;
        this._url = null;
    },
    openPage: function (page) {

        if (this._tab === null)
            this.openTab();

        this.setTabPage(page);
    },
    closePage: function () {

        this.setTabPage(this.defaultPage);
        this.closeTab();
    },
    setTabPage: function (page) {

        this._previousPage = this.currentPage;
        this._currentPage = page;

        this._tab.url = location.href.replace(this.previousPage, 'markups/'+this.currentPage);
        this._url = this._tab.url;
    },
    openTab: function () {

        this._tab = safari.application.activeBrowserWindow.openTab('foreground',-1);
        this._isTabOpen = true;
    },
    closeTab: function () {

        this._tab.close();

        this._isTabOpen = false;
    },
    isTabOpen: function () {

        return this._isTabOpen;
    }
});

var ks = Class.create(KSUtils, {

    initialize: function () {

        this.setVerboseLevel(1);
    },
    db: new KSStorage(),
    panels: {
        manageUserScripts: new ManagementPanel(),
        newUserScript: new NewUserScriptPanel(),
        UserScriptSettings: new ScriptSettingsPanel()
    }
});

function _ksCommandHandler(event) {

    switch (event.command)
    {
        case "open_main":

            ks.panels.manageUserScripts.openPage();
            break;
        case "close":

            ks.log("Something closed.");
            //ks.panels.manageUserScripts.close();
            break;
        case "toggle_enable":

            break;
        case "open_manage":

            break;
        case "open_new":

            break;
    }
}

function _ksValidateHandler(event) {

    switch (event.command)
    {
        case "open_main":

            if (ks.panels.manageUserScripts.isTabOpen() === true) {

                ks.panels.manageUserScripts.openPage(ks.panels.manageUserScripts.defaultPage);
            }
            break;
        case "close":

            break;
        case "toggle_enable":

            break;
        case "open_manage":

            break;
        case "open_new":

            break;
    }
}

safari.application.addEventListener("command", _ksCommandHandler, false);

safari.application.addEventListener("validate", _ksValidateHandler, false);

<commit_msg>Comments added<commit_after>/**
 *  KitScript - A User Script Safari Extension
 */

/**
 *  KSUtils (KitScript Utilitary Class)
 */
var KSUtils = Class.create({

    initialize: function () {

        this._vl = 0;
    },
    /**
     *  @param int verboseLevel (0=Silenced,1=Console,2=BrowserAlert)
     */
    setVerboseLevel: function (verboseLevel) {

        this._vl = verboseLevel;
    },
    log: function (msg) {

        switch (this._vl) {

            case 2:
                alert(msg);
            case 1:
                console.log(msg);
                break;
            case 0:
            default:
                // Silence
        }
    }
});

/**
 *  KSManagementPanel (KitScript User Scripts Management Panel Class)
 */
var KSManagementPanel = Class.create(KSBase, {

    initialize: function () {

        this._pageName = "managementPanel.html";
    },
    openPanel: function () {

        this.openPage(this._pageName);
    },
    openSettings: function (id) {

        //ks.scriptSettingsPanel.openPage(id);
    },
    disable: function (id) {

        //db.disableScript(id);

        //$('#user-script-'+id).addClass('disabled');
        //$('button','#us-list tbody tr td').attr('disabled','disabled');
    },
    remove: function (id) {

        //db.remove(id);

        //$('#user-script-'+id).remove();
    }
});

/**
 *  KSNewPanel (KitScript New User Script Panel Class)
 */
/*
var KSNewPanel = Class.create(KSBase, {

    initialize: function () {

        this._page = "newUserScriptPanel.html";
    },
    openPage: function ($super) {

        $super(this._page);
    },
    close: function ($super) {

        //$super();
    },
    save: function (newUserScriptForm) {
        /*
        code = newUserScriptForm.us-code;

        us = new UserScript(code);

        name = us.getName();
        desc = us.getDescription();
        includes = us.getIncludes().join(",");
        excludes = us.getExcludes().join(",");
        disabled = 0;

        db.create(name, desc, includes, excludes, code, disabled);
        */
        /*
    },
    autoSave: function () {

    }
});

/**
 *  KSSettingsPanel (KitScript User Script Settings Panel Class)
 */
/*
var KSSettingsPanel = Class.create(KSBase, {

    initialize: function () {

        this._page = "scriptSettingsPanel.html";
    },
    openPage: function ($super, scriptId) {

        this._scriptId = scriptId;

        $super(this._page);

        //this.showUserSettings();
    },
    close: function ($super) {

        //$super();
    },
    showUserSettings: function () {

    },
    showScriptSettings: function () {

    },
    showScriptEdition: function () {

    },
    saveUserSettings: function () {

    },
    saveScriptSettings: function () {

    },
    saveScriptEdition: function (userScriptForm) {
        /*
        id = userScriptForm.us-id;

        code = userScriptForm.us-code;

        us = new UserScript(code);

        name = us.getName();
        desc = us.getDescription();
        includes = us.getIncludes().join(",");
        excludes = us.getExcludes().join(",");
        disabled = userScriptForm.isDisabled;

        db.update(name, desc, includes, excludes, code, disabled, id);
        */
        /*
    }
});
*/

/**
 *  KSBase (KitScript Base Object Class)
 */
var KSBase = Class.create({

    initialize: function () {

        this._isTabOpen = false;

        this.defaultPage = 'main.html';

        this._previousPage = null;
        this._currentPage = this.defaultPage;

        this._tab = null;
        this._url = null;
    },
    openPage: function (page) {

        if (this._tab === null)
            this.openTab();

        this.setTabPage(page);
    },
    closePage: function () {

        this.setTabPage(this.defaultPage);
        this.closeTab();
    },
    setTabPage: function (page) {

        this._previousPage = this._currentPage;
        this._currentPage = page;

        this._tab.url = location.href.replace(this._previousPage, 'markups/'+this._currentPage);
        this._url = this._tab.url;
    },
    openTab: function () {

        this._tab = safari.application.activeBrowserWindow.openTab('foreground',-1);
        this._isTabOpen = true;
    },
    closeTab: function () {

        if (this._tab !== null) {

            this._tab.close();
            this._tab = null;
            this._isTabOpen = false;
        }
    },
    isTabOpen: function () {

        return this._isTabOpen;
    }
});

/**
 *  KSStorage (KitScript Storage Class)
 *
var KSStorage = Class.create(Storage, {

    initialize: function ($super) {

        this._dbName = 'KitScript';
        this._dbVersion = '1.0';
        this._dbDisplayName = 'KitScript';
        this._dbSize = 10 * 1024 * 1024; // 10 MB in bytes

        $super(this._dbName, this._dbVersion, this._dbDisplayName, this._dbSize);
    },
    connect: function ($super) {

        return $super();
    },
    createTable: function (isDropAllowed) {

        if (isDropAllowed) {

            _fH = function () { console.log("Table dropped."); };

            sqlArray = new SQLStatementsArray();

            sqlArray.push('DROP TABLE UserScripts;', [], _fH, _errorHandler);

            this.transact(sqlArray);
        }

        _fH = function () { console.log("Table created."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push('CREATE TABLE IF NOT EXISTS UserScripts (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, description TEXT NOT NULL, whitelist TEXT NOT NULL, blacklist TEXT NOT NULL, script TEXT NOT NULL, disabled INT NOT NULL DEFAULT 0);', [], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    insert: function (name, desc, includes, excludes, code, disabled) {

        _fH = function () { console.log("Data inserted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push("INSERT INTO UserScripts (name, description, whitelist, blacklist, script, disabled) VALUES (?, ?, ?, ?, ?, ?);", [name, desc, includes, excludes, code, disabled], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    update: function (id, name, desc, includes, excludes, code, disabled) {

        _fH = function () { console.log("Data updated."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push("UPDATE UserScripts SET name = ?, description = ?, whitelist = ?, blacklist = ?, script = ?, disabled = ? WHERE id = ?;", [name, desc, includes, excludes, code, disabled, id], _fH, _errorHandler);

        this.transact(sqlArray);
    },
    fetch: function (id, fetchCallback) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push("SELECT * FROM UserScripts WHERE id = ?;", [id], fetchCallback, _errorHandler);

        this.transact(sqlArray);
    },
    fetchAll: function (offset, limit, fetchCallback) {

        sqlArray = new SQLStatementsArray();

        sqlArray.push("SELECT * FROM UserScripts LIMIT ?, ?;", [offset, limit], fetchCallback, _errorHandler);

        this.transact(sqlArray);
    },
    remove: function (id) {

        _fH = function () { console.log("Data deleted."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push("DELETE FROM UserScripts WHERE id = ?;", [id], _fH, _killTransaction);

        this.transact(sqlArray);
    },
    disableScript: function (id) {

        _fH = function () { console.log("Script disabled."); };

        sqlArray = new SQLStatementsArray();

        sqlArray.push("UPDATE UserScripts SET disabled = 1 WHERE id = ?;", [id], _fH, _errorHandler);

        this.transact(sqlArray);
    }
});
*/

var ks = Class.create(KSUtils, {

    initialize: function () {

        this.setVerboseLevel(1);
    },
    //db: new KSStorage(),
    manageUserScripts: new KSManagementPanel()//,
    //newUserScript: new KSNewPanel(),
    //UserScriptSettings: new KSSettingsPanel()
});

function _ksCommandHandler(event) {

    switch (event.command)
    {
        case "open_main":

            //ks.panels.manageUserScripts.openPage();
            //ks.manageUserScripts.openPage();
            break;
        case "close":

            ks.log("Something closed.");
            //ks.panels.manageUserScripts.close();
            break;
        case "toggle_enable":

            break;
        case "open_manage":

            break;
        case "open_new":

            break;
    }
}

function _ksValidateHandler(event) {

    switch (event.command)
    {
        case "open_main":

            //if (ks.manageUserScripts.isTabOpen() === true) {

            //    ks.manageUserScripts.openPage(ks.panels.manageUserScripts.defaultPage);
            //}
            break;
        case "close":

            break;
        case "toggle_enable":

            break;
        case "open_manage":

            break;
        case "open_new":

            break;
    }
}

safari.application.addEventListener("command", _ksCommandHandler, false);
safari.application.addEventListener("validate", _ksValidateHandler, false);

<|endoftext|>


<commit_before>/*
 * Node.js
 */

class SpriteNodeOperation extends Operation
{
        constructor(){
                super() ;
        }

        // action: SpriteNodeAction
        get action() {
                let action  = super.parameter("action") ;
                let speed   = action.speed ;
                let angle   = action.angle ;
                checkVariables("SpriteNodeOperation.action (get)", action, speed, action) ;
                return new SpriteNodeAction(speed, angle) ;
        }
        set action(newact){ // SpriteNodeAction
                if(checkVariables("SpriteNodeOperation.action (set)", newact, newact.speed, newact.angle)){
                        let action = {
                                speed:   newact.speed,
                                angle:   newact.angle
                        } ;
                        super.setParameter("action", action) ;
                }
        }

        // result: SpriteNodeAction
        get result() {
                let action  = super.parameter("result") ;
                let speed   = action.speed ;
                let angle   = action.angle ;
                checkVariables("SpriteNodeOperation.result (get)", action, speed, action) ;
                return new SpriteNodeAction(speed, angle) ;
        }
        set result(newact){ // SpriteNodeAction
                if(checkVariables("SpriteNodeOperation.result (set)", newact, newact.speed, newact.angle)){
                        let action = {
                                speed:   newact.speed,
                                angle:   newact.angle
                        } ;
                        super.setParameter("result", action) ;
                }
        }

        // status: SpriteNodeStatus
        get status() {
                let status   = super.parameter("status") ;
		let name     = status.name ;
		let teamid   = status.teamId ;
                let position = status.position ;
                let size     = status.size ;
		let bounds   = status.bounds ;
                let energy   = status.energy ;
                checkVariables("SpriteNodeOperation.status (get)", name, teamid, status, position, size, bounds, energy) ;
                return new SpriteNodeStatus(name, teamid, position, size, bounds, energy) ;
        }
        set status(newstat){ // SpriteNodeStatus
                if(checkVariables("SpriteNodeOperation.status (set)", newstat, newstat.name, newstat.teamId, newstat.position, newstat.size, newstat.bounds, newstat.energy)){
                        let status = {
			        name:     newstat.name,
				teamId:   newstat.teamId,
                                position: newstat.position,
                                size:     newstat.size,
				bounds:	  newstat.bounds,
                                energy:   newstat.energy
                        } ;
                        super.setParameter("status", status) ;
                }
        }

	// condition: SpriteCondition
	get conditions() {
		let cond    = super.parameter("conditions") ;
		let cdamage = cond.collisionDamage ;
		checkVariables("SpriteNodeOperation.conditions (get)", cond, cdamage) ;
		return new SpriteCondition(cdamage) ;
	}
	set conditions(newcond) {
		 if(checkVariables("SpriteNodeOperation.conditions (set)", newcond, newcond.collisionDamage)){
			 let cond = {
			 	collisionDamage: newcond.collisionDamage
			 } ;
			 super.setParameter("conditions", cond) ;
		 }
	}

	execute(){
                let status  = this.status ;
                let action  = this.action ;
                let newact  = this.decideAction(status, action) ;
                this.result = newact ;
        }

        // decideAction(status: Status, action: Action)
        decideAction(status, action){
                console.log("[Error] SpriteNodeOperation.decideAction\n") ;
                return action ;
        }
}
<commit_msg>SpriteOperation.js: Update built-in script for operation<commit_after>/*
 * Node.js
 */

class SpriteNodeOperation extends Operation
{
        constructor(){
                super() ;
        }

	get interval(){
		let interval = super.parameter("interval") ;
		checkVariables("SpriteNodeOperation.interval (get)", interval) ;
		return interval ;
	}

        // action: SpriteNodeAction
        get action() {
                let action  = super.parameter("action") ;
                let speed   = action.speed ;
                let angle   = action.angle ;
                checkVariables("SpriteNodeOperation.action (get)", action, speed, action) ;
                return new SpriteNodeAction(speed, angle) ;
        }
        set action(newact){ // SpriteNodeAction
                if(checkVariables("SpriteNodeOperation.action (set)", newact, newact.speed, newact.angle)){
                        let action = {
                                speed:   newact.speed,
                                angle:   newact.angle
                        } ;
                        super.setParameter("action", action) ;
                }
        }

        // result: SpriteNodeAction
        get result() {
                let action  = super.parameter("result") ;
                let speed   = action.speed ;
                let angle   = action.angle ;
                checkVariables("SpriteNodeOperation.result (get)", action, speed, action) ;
                return new SpriteNodeAction(speed, angle) ;
        }
        set result(newact){ // SpriteNodeAction
                if(checkVariables("SpriteNodeOperation.result (set)", newact, newact.speed, newact.angle)){
                        let action = {
                                speed:   newact.speed,
                                angle:   newact.angle
                        } ;
                        super.setParameter("result", action) ;
                }
        }

        // status: SpriteNodeStatus
        get status() {
                let status   = super.parameter("status") ;
		let name     = status.name ;
		let teamid   = status.teamId ;
                let position = status.position ;
                let size     = status.size ;
		let bounds   = status.bounds ;
                let energy   = status.energy ;
                checkVariables("SpriteNodeOperation.status (get)", name, teamid, status, position, size, bounds, energy) ;
                return new SpriteNodeStatus(name, teamid, position, size, bounds, energy) ;
        }
        set status(newstat){ // SpriteNodeStatus
                if(checkVariables("SpriteNodeOperation.status (set)", newstat, newstat.name, newstat.teamId, newstat.position, newstat.size, newstat.bounds, newstat.energy)){
                        let status = {
			        name:     newstat.name,
				teamId:   newstat.teamId,
                                position: newstat.position,
                                size:     newstat.size,
				bounds:	  newstat.bounds,
                                energy:   newstat.energy
                        } ;
                        super.setParameter("status", status) ;
                }
        }

	// condition: SpriteCondition
	get conditions() {
		let cond    = super.parameter("conditions") ;
		let cdamage = cond.collisionDamage ;
		checkVariables("SpriteNodeOperation.conditions (get)", cond, cdamage) ;
		return new SpriteCondition(cdamage) ;
	}
	set conditions(newcond) {
		 if(checkVariables("SpriteNodeOperation.conditions (set)", newcond, newcond.collisionDamage)){
			 let cond = {
			 	collisionDamage: newcond.collisionDamage
			 } ;
			 super.setParameter("conditions", cond) ;
		 }
	}

	execute(){
                let status   = this.status ;
		let interval = this.interval ;
                let action   = this.action ;
                let newact   = this.decideAction(interval, status, action) ;
                this.result  = newact ;
        }

	// decideAction(interval:TimeInterval, status: Status, action: Action)
        decideAction(interval, status, action){
                console.log("[Error] SpriteNodeOperation.decideAction\n") ;
                return action ;
        }
}
<|endoftext|>


<commit_before>// ==UserScript==
// @name        LCA reviewer hiding
// @namespace   http://mary.gardiner.id.au/
// @description Hide existing reviewers and their reviews in Zookeeper
// @include     https://lca2013.linux.org.au/*
// @version     1
// ==/UserScript==

/*
Copyright (c) 2012 Mary Gardiner

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

function LCA_checkTable(table) {
/* This is horrible: if Zookeepr made more liberal (any) use of id
   attributes, we could find them directly by use of
   getElementById */

	var th = table.getElementsByTagName("th");
	var firstTh  = th[0];
	return firstTh.textContent == "# - Reviewer";
}

function LCA_findTable() {
	var tables = document.getElementsByTagName("table");

	for (i = 0; i < tables.length; i++) {
		var tab = tables[i];
		if (LCA_checkTable(tab)) {
			return tab;
		}
	}
}

function LCA_createUnhide() {
        var unhideTableElem = document.createElement("div");
	unhideTableElem.style.border = "thin solid #ff0";
	unhideTableElem.style.backgroundColor = "#ffc";
	unhideTableElem.style.padding = "1ex";
	unhideTableElem.style.fontWeight = "bold";
	unhideTableElem.style.textDecoration = "underline";
	unhideTableElem.id = "unhidetable";
	table = LCA_findTable();
	table.parentNode.insertBefore(unhideTableElem, table);
	return unhideTableElem;
}

function LCA_hideTable() {
	table = LCA_findTable();
	table.style.visibility = "hidden";
	var unhide = document.getElementById("unhidetable");
	unhide.textContent = "Existing reviews hidden, click to see.";
	unhide.onclick = LCA_showTable;
	return false;
}

function LCA_showTable() {
	table = LCA_findTable();
	table.style.visibility = "visible";
	var unhideTableElem = document.getElementById("unhidetable");
	unhideTableElem.textContent = "Showing existing reviews, click to hide.";
	unhideTableElem.onclick = LCA_hideTable;
	return false;
}

LCA_createUnhide();
LCA_hideTable();
<commit_msg>Use display: none to collapse reviews rather than simply hide them<commit_after>// ==UserScript==
// @name        LCA reviewer hiding
// @namespace   http://mary.gardiner.id.au/
// @description Hide existing reviewers and their reviews in Zookeeper
// @include     https://lca2013.linux.org.au/*
// @version     1
// ==/UserScript==

/*
Copyright (c) 2012 Mary Gardiner

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

function LCA_checkTable(table) {
/* This is horrible: if Zookeepr made more liberal (any) use of id
   attributes, we could find them directly by use of
   getElementById */

	var th = table.getElementsByTagName("th");
	var firstTh  = th[0];
	return firstTh.textContent == "# - Reviewer";
}

function LCA_findTable() {
	var tables = document.getElementsByTagName("table");

	for (i = 0; i < tables.length; i++) {
		var tab = tables[i];
		if (LCA_checkTable(tab)) {
			return tab;
		}
	}
}

function LCA_createUnhide() {
        var unhideTableElem = document.createElement("div");
	unhideTableElem.style.border = "thin solid #ff0";
	unhideTableElem.style.backgroundColor = "#ffc";
	unhideTableElem.style.padding = "1ex";
	unhideTableElem.style.fontWeight = "bold";
	unhideTableElem.style.textDecoration = "underline";
	unhideTableElem.id = "unhidetable";
	table = LCA_findTable();
	table.parentNode.insertBefore(unhideTableElem, table);
	return unhideTableElem;
}

function LCA_hideTable() {
	table = LCA_findTable();
	table.style.display = "none";
	var unhide = document.getElementById("unhidetable");
	unhide.textContent = "Existing reviews hidden, click to see.";
	unhide.onclick = LCA_showTable;
	return false;
}

function LCA_showTable() {
	table = LCA_findTable();
	table.style.display = "block";
	var unhideTableElem = document.getElementById("unhidetable");
	unhideTableElem.textContent = "Showing existing reviews, click to hide.";
	unhideTableElem.onclick = LCA_hideTable;
	return false;
}

LCA_createUnhide();
LCA_hideTable();
<|endoftext|>


<commit_before>$(function () {
    $("div#loadpkg").slideDown();
    var container = $("div#pkglist");
    $.get(container.data("url"), function (result) {
        $("div#loadpkg").slideUp();
        $(container).html(result);
        $(container).slideDown();
        initRemoteAlerts(container);
        $(container).find(".tablesorter").DataTable({
            language: {
                url: $("body").data("datatables-translation")
            },
            columnDefs: [{targets: "no-sort", orderable: false}]
        });
        $(container).find(".btn-install").click(function (event) {
            event.preventDefault();
            const url = $(event.target).attr("href");
            const name = $(event.target).data("name");
            const message = AvailablePackageTranslation.AskForInstallPackage.replace
            ("%pkg%", name);
            bootbox.confirm(message, function (confirmed) {
                if (confirmed) {
                    location.replace(url);
                }
            });
        });
    });
});
<commit_msg>const<commit_after>$(function () {
    $("div#loadpkg").slideDown();
    const container = $("div#pkglist");
    $.get(container.data("url"), function (result) {
        $("div#loadpkg").slideUp();
        $(container).html(result);
        $(container).slideDown();
        initRemoteAlerts(container);
        $(container).find(".tablesorter").DataTable({
            language: {
                url: $("body").data("datatables-translation")
            },
            columnDefs: [{targets: "no-sort", orderable: false}]
        });
        $(container).find(".btn-install").click(function (event) {
            event.preventDefault();
            const url = $(event.target).attr("href");
            const name = $(event.target).data("name");
            const message = AvailablePackageTranslation.AskForInstallPackage.replace
            ("%pkg%", name);
            bootbox.confirm(message, function (confirmed) {
                if (confirmed) {
                    location.replace(url);
                }
            });
        });
    });
});
<|endoftext|>


<commit_before>const config = require('config')
const uuid = require('uuid')
const Twitter = require('twitter')
const User = require('../../models/user.js')
const { ERRORS } = require('../../../lib/util')
const logger = require('../../../lib/logger.js')()

exports.post = function (req, res) {
  let loginToken = null
  const handleCreateUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not create user.')
      return
    }
    const userJson = { id: user.id, loginToken: loginToken }
    logger.info({ user: userJson }, 'New user created.')
    res.header('Location', config.restapi.baseuri + '/v1/users/' + user.id)
    res.status(201).send(userJson)
  } // END function - handleCreateUser

  const handleUpdateUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not update user.')
      return
    }

    const userJson = { id: user.id, loginToken: loginToken }
    logger.info({ user: userJson }, 'Existing user issued new login token.')

    res.header('Location', config.restapi.baseuri + '/v1/users/' + user.id)
    res.status(200).send(userJson)
  } // END function - handleUpdateUser

  const handleAuth0TwitterSignIn = function (credentials) {
    const handleFindUser = function (err, user) {
      if (err) {
        logger.error(err)
        res.status(500).send('Error finding user with Auth0 ID.')
        return
      }

      loginToken = uuid.v1()
      if (!user) {
        const u = new User({
          id: credentials.screenName,
          auth0_id: credentials.auth0_id,
          login_tokens: [ loginToken ],
          profile_image_url: credentials.profile_image_url
        })
        u.save(handleCreateUser)
      } else {
        user.id = credentials.screenName
        user.auth0_id = credentials.auth0_id
        user.profile_image_url = credentials.profile_image_url
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } // END function - handleFindUser

    User.findOne({ id: credentials.screenName }, handleFindUser)
  } // END function - handleAuth0TwitterSignIn

  const handleTwitterSignIn = function (twitterCredentials) {
    // TODO: Call Twitter API with OAuth access credentials to make sure they are valid
    const handleFindUser = function (err, user) {
      if (err) {
        logger.error(err)
        res.status(500).send('Error finding user with Twitter ID.')
        return
      }
      loginToken = uuid.v1()
      if (!user) {
        const u = new User({
          id: twitterCredentials.screenName,
          twitter_id: twitterCredentials.userId,
          twitter_credentials: {
            access_token_key: twitterCredentials.oauthAccessTokenKey,
            access_token_secret: twitterCredentials.oauthAccessTokenSecret
          },
          login_tokens: [ loginToken ]
        })
        u.save(handleCreateUser)
      } else {
        user.id = twitterCredentials.screenName
        user.twitter_id = twitterCredentials.userId
        user.twitter_credentials = {
          access_token_key: twitterCredentials.oauthAccessTokenKey,
          access_token_secret: twitterCredentials.oauthAccessTokenSecret
        }
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } // END function - handleFindUser
    // Try to find user with twitter ID
    User.findOne({ twitter_id: twitterCredentials.userId }, handleFindUser)
  } // END function - handleTwitterSignIn

  /**
   * Returns a randomly-generated 4-digit string of a number between 0000 and 9999
   *
   * @returns {string}
   */
  const generateRandomId = () => Math.floor(Math.random() * 10000).toString().padStart(4, '0')

  const generateId = function (nickname) {
    // TODO - Check if the Id generated is not existing
    const id = generateRandomId()
    return nickname + '-' + id
  }

  const handleAuth0SignIn = async function (credentials) {
    try {
      const user = await User.findOne({ auth0_id: credentials.auth0_id })
      loginToken = uuid.v1()
      if (!user) {
        const numOfUser = await User.count({ id: credentials.nickname })
        // Ensure there is no existing user with id same this nickname
        if (numOfUser === 0) {
          const u = new User({
            id: credentials.nickname,
            auth0_id: credentials.auth0_id,
            email: credentials.email,
            login_tokens: [ loginToken ],
            profile_image_url: credentials.profile_image_url
          })
          u.save(handleCreateUser)
        } else {
          const id = generateId(credentials.nickname)
          const u = new User({
            id: id,
            auth0_id: credentials.auth0_id,
            email: credentials.email,
            login_tokens: [ loginToken ],
            profile_image_url: credentials.profile_image_url
          })
          u.save(handleCreateUser)
        }
      } else {
        user.auth0_id = credentials.auth0_id
        user.profile_image_url = credentials.profile_image_url
        user.email = credentials.email
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } catch (err) {
      logger.error(err)
      console.log(err)
      res.status(500).send('Error finding user with Auth0 ID.')
    }
  } // END function - handleAuth0SignIn

  let body
  try {
    body = req.body
  } catch (e) {
    res.status(400).send('Could not parse body as JSON.')
    return
  }

  if (body.hasOwnProperty('twitter')) {
    handleTwitterSignIn(body.twitter)
  } else if (body.hasOwnProperty('auth0_twitter')) {
    handleAuth0TwitterSignIn(body.auth0_twitter)
  } else if (body.hasOwnProperty('auth0')) {
    handleAuth0SignIn(body.auth0)
  } else {
    res.status(400).send('Unknown sign-in method used.')
  }
} // END function - exports.post

exports.get = async function (req, res) {
  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const userId = req.params.user_id

  const findUserById = async function (userId) {
    let user

    try {
      user = await User.findOne({ id: userId })
    } catch (err) {
      logger.error(err)
      throw new Error(ERRORS.CANNOT_GET_USER)
    }

    if (!user) {
      throw new Error(ERRORS.USER_NOT_FOUND)
    }

    return user
  }

  const findUserByLoginToken = async function (loginToken) {
    let user

    try {
      user = await User.findOne({ login_tokens: { $in: [ loginToken ] } })
    } catch (err) {
      logger.error(err)
      throw new Error(ERRORS.CANNOT_GET_USER)
    }

    if (!user) {
      throw new Error(ERRORS.UNAUTHORISED_ACCESS)
    }

    return user
  }

  const handleFindUser = function (user) {
    let twitterApiClient

    try {
      twitterApiClient = new Twitter({
        consumer_key: config.twitter.oauth_consumer_key,
        consumer_secret: config.twitter.oauth_consumer_secret,
        access_token_key: user.twitter_credentials.access_token_key,
        access_token_secret: user.twitter_credentials.access_token_secret
      })
    } catch (error) {
      logger.error('Could not initialize Twitter API client: ' + error)
    }

    const sendUserJson = function (data) {
      const auth = (user.login_tokens.indexOf(req.loginToken) !== -1)

      user.asJson({ auth: auth }, function (err, userJson) {
        if (err) {
          logger.error(err)
          res.status(500).send('Could not render user JSON.')
          return
        }

        if (data) {
          userJson.profileImageUrl = data.twitter_profile_image_url
        } else {
          userJson.profileImageUrl = user.profile_image_url
        }

        res.status(200).send(userJson)
      })
    } // END function - sendUserJson

    let responseAlreadySent = false

    const handleFetchUserProfileFromTwitter = function (err, res) {
      if (err) {
        logger.error('Twitter API call users/show returned error.')
        logger.error(err)
      }

      if (responseAlreadySent) {
        logger.debug({ profile_image_url: res.profile_image_url }, 'Twitter API users/show call returned but response already sent!')
      } else {
        logger.debug({ profile_image_url: res.profile_image_url }, 'Twitter API users/show call returned. Sending response with Twitter data.')
        responseAlreadySent = true

        if (!res) {
          logger.error('Twitter API call users/show did not return any data.')
        }

        sendUserJson({
          twitter_profile_image_url: res.picture
        })
      }
    } // END function - handleFetchUserProfileFromTwitter

    if (twitterApiClient && !user.profile_image_url) {
      logger.debug('About to call Twitter API: /users/show.json?user_id=' + user.twitter_id)
      twitterApiClient.get('/users/show.json', { user_id: user.twitter_id }, handleFetchUserProfileFromTwitter)
      setTimeout(function () {
        if (!responseAlreadySent) {
          logger.debug(`Timing out Twitter API call after %d milliseconds and sending partial response.`, config.twitter.timeout_ms)
          responseAlreadySent = true
          sendUserJson()
        }
      }, config.twitter.timeout_ms)
    } else {
      sendUserJson()
    }
  } // END function - handleFindUser

  const handleError = function (error) {
    switch (error) {
      case ERRORS.USER_NOT_FOUND:
        res.status(404).send('User not found.')
        return
      case ERRORS.CANNOT_GET_USER:
        res.status(500).send('Error finding user.')
        return
      case ERRORS.UNAUTHORISED_ACCESS:
        res.status(401).send('User with that login token not found.')
        return
      default:
        res.status(500).end()
    }
  }

  if (req.loginToken) {
    findUserByLoginToken(req.loginToken)
      .then(handleFindUser)
      .catch(handleError)
  } else {
    findUserById(userId)
      .then(handleFindUser)
      .catch(handleError)
  }
}

exports.delete = async function (req, res) {
  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const userId = req.params.user_id

  let user

  try {
    user = await User.findOne({ id: userId })
  } catch (err) {
    logger.error(err)
    res.status(500).send('Error finding user.')
  }

  if (!user) {
    res.status(404).send('User not found.')
    return
  }

  const idx = user.login_tokens.indexOf(req.loginToken)
  if (idx === -1) {
    res.status(401).end()
    return
  }
  user.login_tokens.splice(idx, 1)

  user.save().then(user => {
    res.status(204).end()
  }).catch(err => {
    logger.error(err)
    res.status(500).send('Could not sign-out user.')
  })
} // END function - exports.delete

exports.put = async function (req, res) {
  let body
  try {
    body = req.body
  } catch (e) {
    res.status(400).send('Could not parse body as JSON.')
    return
  }

  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  // 1. on auth header, check userId matches their login token
  // 2a. if auth.userId = params.userId => permission granted
  // 2b. if auth.userId != params.userId, auth.userId IS admin => permission granted

  // Find requesting user
  const userId = req.userId
  let user

  try {
    user = await User.findOne({ id: userId })
  } catch (err) {
    logger.error(err)
    res.status(500).send('Error finding user.')
  }

  if (!user) {
    res.status(404).send('User not found.')
    return
  }

  // Is requesting user logged in?
  if (user.login_tokens.indexOf(req.loginToken) === -1) {
    res.status(401).end()
    return
  }

  // Find target user
  const targetUserId = req.params.user_id
  let targetUser
  if (userId !== targetUserId) {
    try {
      targetUser = await User.findOne({ id: targetUserId })
    } catch (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
    }

    if (!targetUser) {
      res.status(404).send('User not found.')
      return
    }
  } else {
    targetUser = user
  }

  if (userId === targetUserId || user.roles.includes('ADMIN')) {
    targetUser.data = body.data || targetUser.data
    targetUser.save().then(user => {
      res.status(204).end()
    }).catch(err => {
      logger.error(err)
      res.status(500).send('Could not update user information.')
    })
  } else {
    res.status(401).end()
  }
} // END function - exports.put
<commit_msg>users api/get: allow admin to  get other users data<commit_after>const config = require('config')
const uuid = require('uuid')
const Twitter = require('twitter')
const User = require('../../models/user.js')
const { ERRORS } = require('../../../lib/util')
const logger = require('../../../lib/logger.js')()

exports.post = function (req, res) {
  let loginToken = null
  const handleCreateUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not create user.')
      return
    }
    const userJson = { id: user.id, loginToken: loginToken }
    logger.info({ user: userJson }, 'New user created.')
    res.header('Location', config.restapi.baseuri + '/v1/users/' + user.id)
    res.status(201).send(userJson)
  } // END function - handleCreateUser

  const handleUpdateUser = function (err, user) {
    if (err) {
      logger.error(err)
      res.status(500).send('Could not update user.')
      return
    }

    const userJson = { id: user.id, loginToken: loginToken }
    logger.info({ user: userJson }, 'Existing user issued new login token.')

    res.header('Location', config.restapi.baseuri + '/v1/users/' + user.id)
    res.status(200).send(userJson)
  } // END function - handleUpdateUser

  const handleAuth0TwitterSignIn = function (credentials) {
    const handleFindUser = function (err, user) {
      if (err) {
        logger.error(err)
        res.status(500).send('Error finding user with Auth0 ID.')
        return
      }

      loginToken = uuid.v1()
      if (!user) {
        const u = new User({
          id: credentials.screenName,
          auth0_id: credentials.auth0_id,
          login_tokens: [ loginToken ],
          profile_image_url: credentials.profile_image_url
        })
        u.save(handleCreateUser)
      } else {
        user.id = credentials.screenName
        user.auth0_id = credentials.auth0_id
        user.profile_image_url = credentials.profile_image_url
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } // END function - handleFindUser

    User.findOne({ id: credentials.screenName }, handleFindUser)
  } // END function - handleAuth0TwitterSignIn

  const handleTwitterSignIn = function (twitterCredentials) {
    // TODO: Call Twitter API with OAuth access credentials to make sure they are valid
    const handleFindUser = function (err, user) {
      if (err) {
        logger.error(err)
        res.status(500).send('Error finding user with Twitter ID.')
        return
      }
      loginToken = uuid.v1()
      if (!user) {
        const u = new User({
          id: twitterCredentials.screenName,
          twitter_id: twitterCredentials.userId,
          twitter_credentials: {
            access_token_key: twitterCredentials.oauthAccessTokenKey,
            access_token_secret: twitterCredentials.oauthAccessTokenSecret
          },
          login_tokens: [ loginToken ]
        })
        u.save(handleCreateUser)
      } else {
        user.id = twitterCredentials.screenName
        user.twitter_id = twitterCredentials.userId
        user.twitter_credentials = {
          access_token_key: twitterCredentials.oauthAccessTokenKey,
          access_token_secret: twitterCredentials.oauthAccessTokenSecret
        }
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } // END function - handleFindUser
    // Try to find user with twitter ID
    User.findOne({ twitter_id: twitterCredentials.userId }, handleFindUser)
  } // END function - handleTwitterSignIn

  /**
   * Returns a randomly-generated 4-digit string of a number between 0000 and 9999
   *
   * @returns {string}
   */
  const generateRandomId = () => Math.floor(Math.random() * 10000).toString().padStart(4, '0')

  const generateId = function (nickname) {
    // TODO - Check if the Id generated is not existing
    const id = generateRandomId()
    return nickname + '-' + id
  }

  const handleAuth0SignIn = async function (credentials) {
    try {
      const user = await User.findOne({ auth0_id: credentials.auth0_id })
      loginToken = uuid.v1()
      if (!user) {
        const numOfUser = await User.count({ id: credentials.nickname })
        // Ensure there is no existing user with id same this nickname
        if (numOfUser === 0) {
          const u = new User({
            id: credentials.nickname,
            auth0_id: credentials.auth0_id,
            email: credentials.email,
            login_tokens: [ loginToken ],
            profile_image_url: credentials.profile_image_url
          })
          u.save(handleCreateUser)
        } else {
          const id = generateId(credentials.nickname)
          const u = new User({
            id: id,
            auth0_id: credentials.auth0_id,
            email: credentials.email,
            login_tokens: [ loginToken ],
            profile_image_url: credentials.profile_image_url
          })
          u.save(handleCreateUser)
        }
      } else {
        user.auth0_id = credentials.auth0_id
        user.profile_image_url = credentials.profile_image_url
        user.email = credentials.email
        user.login_tokens.push(loginToken)
        user.save(handleUpdateUser)
      }
    } catch (err) {
      logger.error(err)
      console.log(err)
      res.status(500).send('Error finding user with Auth0 ID.')
    }
  } // END function - handleAuth0SignIn

  let body
  try {
    body = req.body
  } catch (e) {
    res.status(400).send('Could not parse body as JSON.')
    return
  }

  if (body.hasOwnProperty('twitter')) {
    handleTwitterSignIn(body.twitter)
  } else if (body.hasOwnProperty('auth0_twitter')) {
    handleAuth0TwitterSignIn(body.auth0_twitter)
  } else if (body.hasOwnProperty('auth0')) {
    handleAuth0SignIn(body.auth0)
  } else {
    res.status(400).send('Unknown sign-in method used.')
  }
} // END function - exports.post

exports.get = async function (req, res) {
  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const targetUserId = req.params.user_id
  let targetUser

  const findUserById = async function (userId) {
    try {
      targetUser = await User.findOne({ id: userId })
    } catch (err) {
      logger.error(err)
      throw new Error(ERRORS.CANNOT_GET_USER)
    }

    if (!targetUser) {
      throw new Error(ERRORS.USER_NOT_FOUND)
    }

    return targetUser
  }

  let requestUser

  const findUserByLoginToken = async function (loginToken) {
    try {
      requestUser = await User.findOne({ login_tokens: { $in: [ loginToken ] } })
    } catch (err) {
      logger.error(err)
      throw new Error(ERRORS.CANNOT_GET_USER)
    }

    if (!requestUser) {
      throw new Error(ERRORS.UNAUTHORISED_ACCESS)
    }

    // Finding target user
    if (req.user_id !== targetUserId) {
      try {
        targetUser = await findUserById(targetUserId)
      } catch (error) {
        logger.error(err)
        throw new Error(ERRORS.CANNOT_GET_USER)
      }

      if (!targetUser) {
        throw new Error(ERRORS.UNAUTHORISED_ACCESS)
      }

    } else {
      targetUser = requestUser
    }

    return targetUser
  }

  const handleFindUser = function (user) {
    let twitterApiClient

    try {
      twitterApiClient = new Twitter({
        consumer_key: config.twitter.oauth_consumer_key,
        consumer_secret: config.twitter.oauth_consumer_secret,
        access_token_key: user.twitter_credentials.access_token_key,
        access_token_secret: user.twitter_credentials.access_token_secret
      })
    } catch (error) {
      logger.error('Could not initialize Twitter API client: ' + error)
    }

    const sendUserJson = function (data) {
      // If requestUser = targetUser => permission granted
      // If requestUser != targetUser and requestUser is admin => permission granted
      const auth = (user.login_tokens.indexOf(req.loginToken) !== -1) || requestUser.roles.includes('ADMIN')

      user.asJson({ auth: auth }, function (err, userJson) {
        if (err) {
          logger.error(err)
          res.status(500).send('Could not render user JSON.')
          return
        }

        if (data) {
          userJson.profileImageUrl = data.twitter_profile_image_url
        } else {
          userJson.profileImageUrl = user.profile_image_url
        }

        res.status(200).send(userJson)
      })
    } // END function - sendUserJson

    let responseAlreadySent = false

    const handleFetchUserProfileFromTwitter = function (err, res) {
      if (err) {
        logger.error('Twitter API call users/show returned error.')
        logger.error(err)
      }

      if (responseAlreadySent) {
        logger.debug({ profile_image_url: res.profile_image_url }, 'Twitter API users/show call returned but response already sent!')
      } else {
        logger.debug({ profile_image_url: res.profile_image_url }, 'Twitter API users/show call returned. Sending response with Twitter data.')
        responseAlreadySent = true

        if (!res) {
          logger.error('Twitter API call users/show did not return any data.')
        }

        sendUserJson({
          twitter_profile_image_url: res.picture
        })
      }
    } // END function - handleFetchUserProfileFromTwitter

    if (twitterApiClient && !user.profile_image_url) {
      logger.debug('About to call Twitter API: /users/show.json?user_id=' + user.twitter_id)
      twitterApiClient.get('/users/show.json', { user_id: user.twitter_id }, handleFetchUserProfileFromTwitter)
      setTimeout(function () {
        if (!responseAlreadySent) {
          logger.debug(`Timing out Twitter API call after %d milliseconds and sending partial response.`, config.twitter.timeout_ms)
          responseAlreadySent = true
          sendUserJson()
        }
      }, config.twitter.timeout_ms)
    } else {
      sendUserJson()
    }
  } // END function - handleFindUser

  const handleError = function (error) {
    switch (error) {
      case ERRORS.USER_NOT_FOUND:
        res.status(404).send('User not found.')
        return
      case ERRORS.CANNOT_GET_USER:
        res.status(500).send('Error finding user.')
        return
      case ERRORS.UNAUTHORISED_ACCESS:
        res.status(401).send('User with that login token not found.')
        return
      default:
        res.status(500).end()
    }
  }

  if (req.loginToken) {
    findUserByLoginToken(req.loginToken)
      .then(handleFindUser)
      .catch(handleError)
  } else {
    findUserById(targetUserId)
      .then(handleFindUser)
      .catch(handleError)
  }
}

exports.delete = async function (req, res) {
  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  const userId = req.params.user_id

  let user

  try {
    user = await User.findOne({ id: userId })
  } catch (err) {
    logger.error(err)
    res.status(500).send('Error finding user.')
  }

  if (!user) {
    res.status(404).send('User not found.')
    return
  }

  const idx = user.login_tokens.indexOf(req.loginToken)
  if (idx === -1) {
    res.status(401).end()
    return
  }
  user.login_tokens.splice(idx, 1)

  user.save().then(user => {
    res.status(204).end()
  }).catch(err => {
    logger.error(err)
    res.status(500).send('Could not sign-out user.')
  })
} // END function - exports.delete

exports.put = async function (req, res) {
  let body
  try {
    body = req.body
  } catch (e) {
    res.status(400).send('Could not parse body as JSON.')
    return
  }

  // Flag error if user ID is not provided
  if (!req.params.user_id) {
    res.status(400).send('Please provide user ID.')
    return
  }

  // 1. on auth header, check userId matches their login token
  // 2a. if auth.userId = params.userId => permission granted
  // 2b. if auth.userId != params.userId, auth.userId IS admin => permission granted

  // Find requesting user
  const userId = req.userId
  let user

  try {
    user = await User.findOne({ id: userId })
  } catch (err) {
    logger.error(err)
    res.status(500).send('Error finding user.')
  }

  if (!user) {
    res.status(404).send('User not found.')
    return
  }

  // Is requesting user logged in?
  if (user.login_tokens.indexOf(req.loginToken) === -1) {
    res.status(401).end()
    return
  }

  // Find target user
  const targetUserId = req.params.user_id
  let targetUser
  if (userId !== targetUserId) {
    try {
      targetUser = await User.findOne({ id: targetUserId })
    } catch (err) {
      logger.error(err)
      res.status(500).send('Error finding user.')
    }

    if (!targetUser) {
      res.status(404).send('User not found.')
      return
    }
  } else {
    targetUser = user
  }

  if (userId === targetUserId || user.roles.includes('ADMIN')) {
    targetUser.data = body.data || targetUser.data
    targetUser.save().then(user => {
      res.status(204).end()
    }).catch(err => {
      logger.error(err)
      res.status(500).send('Could not update user information.')
    })
  } else {
    res.status(401).end()
  }
} // END function - exports.put
<|endoftext|>


<commit_before>'use strict';

chrome.runtime.onInstalled.addListener(function (details) {
    console.log('Github Pro\nVersion: ', details.previousVersion);
});

chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {

    if (changeInfo.status === 'complete') {
        var url = new URL(tab.url);

        if ( url.origin === 'https://github.com') {

            // The current open tab will be listening to this message if it is
            // running contentscript.js. Which, only runs on github.com
            chrome.tabs.query({ active: true, currentWindow: true }, function(tabs) {
                chrome.tabs.sendMessage(tabs[0].id, {msg: 'msg'}, function(msg) {
                    console.log(msg);
                });
            });
        }
    }
});<commit_msg>Features are fun in background tabs as well<commit_after>'use strict';

chrome.runtime.onInstalled.addListener(function (details) {
    console.log('Github Pro\nVersion: ', details.previousVersion);
});

// Every time a tab has been updated (first load or dom change via ajax)
chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {

    // And has completed loading
    if (changeInfo.status === 'complete') {

        // And if the tab is a Github tab
        var url = new URL(tab.url);
        if ( url.origin === 'https://github.com') {

            // Send a message to that page's contentscript!
            // Basically, the message listener will run all the features
            chrome.tabs.sendMessage(tab.id, {msg: 'page has been loaded'}, function(msg) {
                console.log(msg);
            });
        }
    }
});<|endoftext|>


<commit_before>/*jshint camelcase: false */
(function () {
    'use strict';

    var query  = window.location.search.substring(1);
    var restaurant_id = getParameterByName('id');

    // function to get the search parameters
    function getParameterByName(name) {
      name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
      var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
          results = regex.exec(location.search);
      return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }

    var source = $('#restaurant-template').html();
    var template = Handlebars.compile(source);

    var menu_items;
    var menuIndex;
    var menu_source = $('#menu-template').html();
    var menu_template = Handlebars.compile(menu_source);

    var deals_items;
    var dealsIndex;
    var deals_source = $('#deals-template').html();
    var deals_template = Handlebars.compile(deals_source);

    var scrolling = false;

    // call a function everytime the user scrolls
    $('.main-div').scroll(function() {
      var scrollAmt = -$('.main-photo').offset().top - $('.main-div').offset().top;
      if (scrollAmt > 5) {
        $('.sub-nav').removeClass('hidden');
      } else {
        $('.sub-nav').addClass('hidden');
        return;
      }
      if (scrollAmt > 100) {
        scrollAmt = 100;
      }
      $('.sub-nav').css({
        opacity: scrollAmt/100
      });

      if (scrolling) {
        return; // user has clicked on a menu item
      }

      // underline as the user scrolls
      $('.sub-nav').children().each(function(){
        var anchor = $(this).data('anchor');
        var offset = $('.' + anchor).offset().top - $('.main-div').offset().top - $('.sub-nav').offset().top;

        if (offset < 0) {
          $('.sub-nav-item').removeClass('selected');
          $(this).addClass('selected');
        }
      });
    });

    $('.sub-nav-item').click(function() {
      // set the underline at the right place
      $('.sub-nav-item').removeClass('selected');
      $(this).addClass('selected');

      var anchor = $(this).data('anchor');
      scrolling = true;
      $('.main-div').animate({
        'scrollTop':   $('.' + anchor).offset().top - $('.main-photo').offset().top - $('.sub-nav').height()
      }, 1000, function() {
        scrolling = false;
      });
    });

    Handlebars.registerHelper('rating_stars', function(rating_num, num_reviews) {
      var i;
      var rating = '';
      for (i=0; i<rating_num; i++) {
        rating += '';
      }
      for (i=0; i<5-rating_num; i++) {
        rating += '';
      }

      return rating + ' ' + num_reviews;

    });

    function getDetails() {

      $.getJSON( window.apiUrl + '/restaurant/' + restaurant_id + '/' + window.username + '/', function( data ) {

        menu_items = data.foods;
        deals_items = data.deals;

        console.log(data);

        $('.sub-name').text(data.name);

        $('.main-div').html(template(data));

      }).done(function() {

        // scroll to reviews if the user landed here from reviews
        if (getParameterByName('nav') === 'reviews') {
          setTimeout(function() {
            $('.infopage').eq(2).click()
          }, 1000);
        }

        $('.follow-button').click(function(event) {

          var restaurant_id = $(this).data('id');

          $.getJSON (window.apiUrl + '/restaurant/follow/' + restaurant_id + '/' + window.username + '/', function(data) {
            getDetails();
          });

          $(this).toggleClass('following');
          event.stopPropagation();
        });

        $('.menu-items .modal-button').click(function() {
          menuIndex = $(this).data('index');

          displayMenuItem(menuIndex);

          var id = $(this).attr('id');
          // show the vignette
          $('#modal-' + id).addClass('open');
          // slide the modal in
          $('#modal-' + id + ' .modal').animate({
            'marginTop': $(window).height()/9
          });

        });

        $('.deal-items .modal-button').click(function(){
          dealsIndex = $(this).data('index');

          displayDeals(dealsIndex);

          var id = $(this).attr('id');

          // show the vignette
          $('#modal-' + id).addClass('open');
          // slide the modal in
          $('#modal-' + id + ' .modal').animate({
            'marginTop': $(window).height()/11
          });

          //close modal
          $('.close-deals-button').click(function(){
            $('#modal-' + id + ' .modal').animate({
              'marginTop': 900
            }, 300, function() {
              $('#modal-' + id).removeClass('open');
            });
          });
        });
      });
    }

    function displayMenuItem(index) {
      var not_first = (index !== 0);
      var not_last = (index !== menu_items.length-1);

      $('#modal-menu-item .modal').html(menu_template({'not_first':not_first, 'not_last':not_last, 'item':menu_items[index]}));

      // set the height of the menu item so its fixed
      var width = $('#modal-menu-item .photo img').width();
      $('#modal-menu-item .photo img').height(width);

      $('.controls .right').click(function(event) {
        if (menuIndex === menu_items.length - 1) {
          return;
        }
        displayMenuItem(++menuIndex);
        event.stopPropagation();
      });

      $('.controls .left').click(function(event) {
        if (menuIndex === 0) {
          return;
        }
        displayMenuItem(--menuIndex);
        event.stopPropagation();
      });
    }

    function displayDeals(index) {
      var not_first = (index !== 0);
      var not_last = (index !== deals_items.length-1);

      $('#modal-restaurant-deals .modal').html(deals_template({'not_first':not_first, 'not_last':not_last, 'deals':deals_items[index]}));

      // set the height of the menu item so its fixed
      var width = $('#modal-restaurant-deals .photo img').width();
      $('#modal-restaurant-deals .photo img').height(width);

      $('.controls .right').click(function(event) {
        if (dealsIndex === deals_items.length - 1) {
          return;
        }
        displayDeals(++dealsIndex);
        event.stopPropagation();
      });

      $('.controls .left').click(function(event) {
        if (dealsIndex === 0) {
          return;
        }
        displayDeals(--dealsIndex);
        event.stopPropagation();
      });
    }

    getDetails();
})();<commit_msg>fixed deals modal close button<commit_after>/*jshint camelcase: false */
(function () {
    'use strict';

    var query  = window.location.search.substring(1);
    var restaurant_id = getParameterByName('id');

    // function to get the search parameters
    function getParameterByName(name) {
      name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
      var regex = new RegExp('[\\?&]' + name + '=([^&#]*)'),
          results = regex.exec(location.search);
      return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
    }

    var source = $('#restaurant-template').html();
    var template = Handlebars.compile(source);

    var menu_items;
    var menuIndex;
    var menu_source = $('#menu-template').html();
    var menu_template = Handlebars.compile(menu_source);

    var deals_items;
    var dealsIndex;
    var deals_source = $('#deals-template').html();
    var deals_template = Handlebars.compile(deals_source);

    var scrolling = false;

    // call a function everytime the user scrolls
    $('.main-div').scroll(function() {
      var scrollAmt = -$('.main-photo').offset().top - $('.main-div').offset().top;
      if (scrollAmt > 5) {
        $('.sub-nav').removeClass('hidden');
      } else {
        $('.sub-nav').addClass('hidden');
        return;
      }
      if (scrollAmt > 100) {
        scrollAmt = 100;
      }
      $('.sub-nav').css({
        opacity: scrollAmt/100
      });

      if (scrolling) {
        return; // user has clicked on a menu item
      }

      // underline as the user scrolls
      $('.sub-nav').children().each(function(){
        var anchor = $(this).data('anchor');
        var offset = $('.' + anchor).offset().top - $('.main-div').offset().top - $('.sub-nav').offset().top;

        if (offset < 0) {
          $('.sub-nav-item').removeClass('selected');
          $(this).addClass('selected');
        }
      });
    });

    $('.sub-nav-item').click(function() {
      // set the underline at the right place
      $('.sub-nav-item').removeClass('selected');
      $(this).addClass('selected');

      var anchor = $(this).data('anchor');
      scrolling = true;
      $('.main-div').animate({
        'scrollTop':   $('.' + anchor).offset().top - $('.main-photo').offset().top - $('.sub-nav').height()
      }, 1000, function() {
        scrolling = false;
      });
    });

    Handlebars.registerHelper('rating_stars', function(rating_num, num_reviews) {
      var i;
      var rating = '';
      for (i=0; i<rating_num; i++) {
        rating += '';
      }
      for (i=0; i<5-rating_num; i++) {
        rating += '';
      }

      return rating + ' ' + num_reviews;

    });

    function getDetails() {

      $.getJSON( window.apiUrl + '/restaurant/' + restaurant_id + '/' + window.username + '/', function( data ) {

        menu_items = data.foods;
        deals_items = data.deals;

        console.log(data);

        $('.sub-name').text(data.name);

        $('.main-div').html(template(data));

      }).done(function() {

        // scroll to reviews if the user landed here from reviews
        if (getParameterByName('nav') === 'reviews') {
          setTimeout(function() {
            $('.infopage').eq(2).click()
          }, 1000);
        }

        $('.follow-button').click(function(event) {

          var restaurant_id = $(this).data('id');

          $.getJSON (window.apiUrl + '/restaurant/follow/' + restaurant_id + '/' + window.username + '/', function(data) {
            getDetails();
          });

          $(this).toggleClass('following');
          event.stopPropagation();
        });

        $('.menu-items .modal-button').click(function() {
          menuIndex = $(this).data('index');

          displayMenuItem(menuIndex);

          var id = $(this).attr('id');
          // show the vignette
          $('#modal-' + id).addClass('open');
          // slide the modal in
          $('#modal-' + id + ' .modal').animate({
            'marginTop': $(window).height()/9
          });

        });

        $('.deal-items .modal-button').click(function(){
          dealsIndex = $(this).data('index');

          displayDeals(dealsIndex);

          var id = $(this).attr('id');

          // show the vignette
          $('#modal-' + id).addClass('open');
          // slide the modal in
          $('#modal-' + id + ' .modal').animate({
            'marginTop': $(window).height()/11
          });

        });
      });
    }

    function displayMenuItem(index) {
      var not_first = (index !== 0);
      var not_last = (index !== menu_items.length-1);

      $('#modal-menu-item .modal').html(menu_template({'not_first':not_first, 'not_last':not_last, 'item':menu_items[index]}));

      // set the height of the menu item so its fixed
      var width = $('#modal-menu-item .photo img').width();
      $('#modal-menu-item .photo img').height(width);

      $('.controls .right').click(function(event) {
        if (menuIndex === menu_items.length - 1) {
          return;
        }
        displayMenuItem(++menuIndex);
        event.stopPropagation();
      });

      $('.controls .left').click(function(event) {
        if (menuIndex === 0) {
          return;
        }
        displayMenuItem(--menuIndex);
        event.stopPropagation();
      });
    }

    function displayDeals(index) {
      var not_first = (index !== 0);
      var not_last = (index !== deals_items.length-1);

      $('#modal-restaurant-deals .modal').html(deals_template({'not_first':not_first, 'not_last':not_last, 'deals':deals_items[index]}));

      // set the height of the menu item so its fixed
      var width = $('#modal-restaurant-deals .photo img').width();
      $('#modal-restaurant-deals .photo img').height(width);

      $('.controls .right').click(function(event) {
        if (dealsIndex === deals_items.length - 1) {
          return;
        }
        displayDeals(++dealsIndex);
        event.stopPropagation();
      });

      $('.controls .left').click(function(event) {
        if (dealsIndex === 0) {
          return;
        }
        displayDeals(--dealsIndex);
        event.stopPropagation();
      });

      //close modal
      $('.main-buttons .close-deals-button').click(function(){
        $('#modal-restaurant-deals .modal').animate({
          'marginTop': 900
        }, 300, function() {
          $('#modal-restaurant-deals').removeClass('open');
        });
      });

    }

    getDetails();
})();<|endoftext|>