<commit_before>import express from 'express';
import request from 'supertest';
import createRouteMiddleware from '../../create-route-middleware';
import createFeatures from '../fixtures/createFeatures';
import { describe } from 'riteway';

describe('createRouteMiddleware()', async should => {

  const { assert } = should();

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature: 'posts',
        get: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .get(path)
      .end(function(err, res) {
        assert({
          given: 'a feature that is enabled',
          should: 'set the correct response status code',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature : 'help',
        get: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .get(path)
      .end(function(err, res) {
        assert({
          given: 'a feature that is disabled',
          should: 'set the correct response status code',
          actual: res.statusCode,
          expected: 404
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature : 'help',
        get: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .get(`${path}?ft=posts`)
      .end(function(err, res) {
        assert({
          given: 'the path has param override that is not relevant to the given disabled feature',
          should: 'set the correct response status code',
          actual: res.statusCode,
          expected: 404
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature : 'help',
        get: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .get(`${path}?ft=help`)
      .end(function(err, res) {
        assert({
          given: 'the path has param override that enables a disabled feature',
          should: 'set the correct response status code',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const path = '/posts';
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature: 'posts',
        get: (req, res) => {
          // Simulate template rendering time
          // This allows following express methods to be called, possibly causing errors or changing the status.
          setTimeout(() => res.send(), 3000);
        }
      }
    );
    app.use(path, handler);
    app.get('*', (req, res) => { res.status(404); res.send(); });

    request(app)
      .get(path)
      .end(function(err, res) {
        if (err) throw(err);
        assert({
          given: 'given more than one handler',
          should: 'handler should not effect each other',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature: 'posts',
        post: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .post(path)
      .end(function(err, res) {
        assert({
          given: 'a post method',
          should: 'should use the post method',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature: 'posts',
        put: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .put(path)
      .end(function(err, res) {
        assert({
          given: 'a put method',
          should: 'should use the put method',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

});
<commit_msg>change comment so it makes more sense.<commit_after>import express from 'express';
import request from 'supertest';
import createRouteMiddleware from '../../create-route-middleware';
import createFeatures from '../fixtures/createFeatures';
import { describe } from 'riteway';

describe('createRouteMiddleware()', async should => {

  const { assert } = should();

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature: 'posts',
        get: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .get(path)
      .end(function(err, res) {
        assert({
          given: 'a feature that is enabled',
          should: 'set the correct response status code',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature : 'help',
        get: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .get(path)
      .end(function(err, res) {
        assert({
          given: 'a feature that is disabled',
          should: 'set the correct response status code',
          actual: res.statusCode,
          expected: 404
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature : 'help',
        get: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .get(`${path}?ft=posts`)
      .end(function(err, res) {
        assert({
          given: 'the path has param override that is not relevant to the given disabled feature',
          should: 'set the correct response status code',
          actual: res.statusCode,
          expected: 404
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature : 'help',
        get: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .get(`${path}?ft=help`)
      .end(function(err, res) {
        assert({
          given: 'the path has param override that enables a disabled feature',
          should: 'set the correct response status code',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const path = '/posts';
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature: 'posts',
        get: (req, res) => {
          // Simulate template rendering time
          // This allows subsequent express methods to be called that could possibly
          // cause errors or change the response status if the `next` callback is not
          // used correctly.
          setTimeout(() => res.send(), 3000);
        }
      }
    );
    app.use(path, handler);
    app.get('*', (req, res) => { res.status(404); res.send(); });

    request(app)
      .get(path)
      .end(function(err, res) {
        if (err) throw(err);
        assert({
          given: 'given more than one handler',
          should: 'handler should not effect each other',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature: 'posts',
        post: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .post(path)
      .end(function(err, res) {
        assert({
          given: 'a post method',
          should: 'should use the post method',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

  {
    const app = express();
    const features = createFeatures();
    const handler = createRouteMiddleware(
      features,
      {
        requiredFeature: 'posts',
        put: (req, res) => {
          res.send();
        }
      }
    );
    const path = '/posts';
    app.use(path, handler);

    request(app)
      .put(path)
      .end(function(err, res) {
        assert({
          given: 'a put method',
          should: 'should use the put method',
          actual: res.statusCode,
          expected: 200
        });
      });
  }

});
<|endoftext|>


<commit_before>Application.Controllers.controller("FilesEditController",
    ["$scope", "$stateParams", "projectFiles", "User", "mcfile", "pubsub", "tags", "mcapi", "$modal", "toastr", "project",
        FilesEditController]);
function FilesEditController($scope, $stateParams, projectFiles, User, mcfile, pubsub, tags, mcapi, $modal, toastr, project) {
    var ctrl = this;

    ctrl.editNote = false;

    pubsub.waitOn($scope, 'datafile-note.change', function () {
        ctrl.editNote = !ctrl.editNote;
    });

    pubsub.waitOn($scope, 'display-directory', function () {
        ctrl.active = projectFiles.getActiveDirectory();
        ctrl.type = 'dir';
    });

    ctrl.addTag = addTag;
    ctrl.removeTag = removeTag;
    ctrl.downloadSrc = downloadSrc;
    ctrl.fileSrc = fileSrc;
    ctrl.closeFile = closeFile;
    ctrl.rename = rename;
    ctrl.createFolder = createFolder;

    init();

    //////////////////////

    function addTag(tag) {
        var tag_obj = {
            tag_id: tag.tag_id,
            owner: User.u(),
            item_type: 'datafile'
        };
        tags.createTag(tag_obj, ctrl.active.df_id);
    }

    function removeTag(tag) {
        tags.removeTag(tag.tag_id, ctrl.active.df_id);
    }

    function downloadSrc(file) {
        return mcfile.downloadSrc(file.df_id);
    }

    function fileSrc(file) {
        if (file) {
            var id = getID(file);
            return mcfile.src(id);
        }
    }

    function closeFile() {
        ctrl.active = null;
    }

    function rename() {
        var modalInstance = $modal.open({
            size: 'sm',
            templateUrl: 'application/core/projects/project/files/rename-file.html',
            controller: 'FileModalController',
            controllerAs: 'file',
            resolve: {
                active: function () {
                    return ctrl.active;
                }
            }
        });
        modalInstance.result.then(function (name) {
            mcapi("/datafile/%", $stateParams.file_id)
                .success(function () {
                    ctrl.active.name = name;
                    pubsub.send('files.refresh');
                })
                .error(function (err) {
                    toastr.error("Rename failed: " + err.error, "Error");
                })
                .put({name: name});
        });
    }

    function createFolder() {
        var modalInstance = $modal.open({
            size: 'sm',
            templateUrl: 'application/core/projects/project/files/create-folder.html',
            controller: 'FileModalController',
            controllerAs: 'folder',
            resolve: {
                active: function () {
                    return ctrl.active;
                }
            }
        });
        modalInstance.result.then(function (name) {
            mcapi('/datadirs')
                .success(function (datadir) {
                    datadir.parent = ctrl.active;
                    datadir.group = true;
                    ctrl.active.addFolder = false;
                    ctrl.active.children.push(datadir);
                    pubsub.send('files.refresh');
                })
                .post({
                    project_id: project.id,
                    parent: ctrl.active.df_id,
                    name: ctrl.active.name + '/' + name,
                    level: ctrl.active.level+1
                });
        });
    }

    // TODO: Clean this up so we don't have to search for different id keys
    // returns the file id depending on which key it is under.
    function getID(file) {
        if ('df_id' in file) {
            return file.df_id;
        } else if ('datafile_id' in file) {
            return file.datafile_id;
        } else if ('id' in file) {
            return file.id;
        } else {
            return ""
        }
    }

    function getActiveFile() {
        ctrl.active = projectFiles.getActiveFile();
        if (!ctrl.active) {
            // A refresh on page has happened. That means we have lost
            // our state in the directory tree. We have the file but
            // tree isn't open on that file. In this case we show the
            // top level directory.
            ctrl.active = ctrl.active = projectFiles.getActiveDirectory();
            //ctrl.type = 'dir';
        } else {
            if (_.isObject(ctrl.active.mediatype)) {
                // TODO: Fix this hack
                // This exists because search sends back the full mediatype, while
                // the tree doesn't.
                ctrl.active.mediatype = ctrl.active.mediatype.mime;
            }
            //ctrl.type = 'file';
            if (isImage(ctrl.active.mediatype)) {
                ctrl.fileType = "image";
            } else if (ctrl.active.mediatype === "application/pdf") {
                ctrl.fileType = "pdf";
            } else if (ctrl.active.mediatype === "application/vnd.ms-excel") {
                ctrl.fileType = "xls";
            } else {
                ctrl.fileType = ctrl.active.mediatype;
            }
        }
    }

    function init() {
        ctrl.active = {};
        ctrl.type = $stateParams.file_type;
        if (ctrl.type == 'datafile') {
            getActiveFile();
        } else {
            ctrl.active = projectFiles.getActiveDirectory();
        }
    }
}

////////////////////////////////

Application.Controllers.controller("FileModalController",
    ["$modalInstance", "active", FileModalController]);
function FileModalController($modalInstance, active) {
    var ctrl = this;
    ctrl.name = "";
    ctrl.useName = useName;
    ctrl.cancel = cancel;

    ///////////

    function useName() {
        if (ctrl.name != "" && ctrl.name != active.name) {
            $modalInstance.close(ctrl.name);
        }
    }

    function cancel() {
        $modalInstance.dismiss('cancel');
    }
}<commit_msg>Show error if create folder fails.<commit_after>Application.Controllers.controller("FilesEditController",
    ["$scope", "$stateParams", "projectFiles", "User", "mcfile", "pubsub", "tags", "mcapi", "$modal", "toastr", "project",
        FilesEditController]);
function FilesEditController($scope, $stateParams, projectFiles, User, mcfile, pubsub, tags, mcapi, $modal, toastr, project) {
    var ctrl = this;

    ctrl.editNote = false;

    pubsub.waitOn($scope, 'datafile-note.change', function () {
        ctrl.editNote = !ctrl.editNote;
    });

    pubsub.waitOn($scope, 'display-directory', function () {
        ctrl.active = projectFiles.getActiveDirectory();
        ctrl.type = 'dir';
    });

    ctrl.addTag = addTag;
    ctrl.removeTag = removeTag;
    ctrl.downloadSrc = downloadSrc;
    ctrl.fileSrc = fileSrc;
    ctrl.closeFile = closeFile;
    ctrl.rename = rename;
    ctrl.createFolder = createFolder;

    init();

    //////////////////////

    function addTag(tag) {
        var tag_obj = {
            tag_id: tag.tag_id,
            owner: User.u(),
            item_type: 'datafile'
        };
        tags.createTag(tag_obj, ctrl.active.df_id);
    }

    function removeTag(tag) {
        tags.removeTag(tag.tag_id, ctrl.active.df_id);
    }

    function downloadSrc(file) {
        return mcfile.downloadSrc(file.df_id);
    }

    function fileSrc(file) {
        if (file) {
            var id = getID(file);
            return mcfile.src(id);
        }
    }

    function closeFile() {
        ctrl.active = null;
    }

    function rename() {
        var modalInstance = $modal.open({
            size: 'sm',
            templateUrl: 'application/core/projects/project/files/rename-file.html',
            controller: 'FileModalController',
            controllerAs: 'file',
            resolve: {
                active: function () {
                    return ctrl.active;
                }
            }
        });
        modalInstance.result.then(function (name) {
            mcapi("/datafile/%", $stateParams.file_id)
                .success(function () {
                    ctrl.active.name = name;
                    pubsub.send('files.refresh');
                })
                .error(function (err) {
                    toastr.error("Rename failed: " + err.error, "Error");
                })
                .put({name: name});
        });
    }

    function createFolder() {
        var modalInstance = $modal.open({
            size: 'sm',
            templateUrl: 'application/core/projects/project/files/create-folder.html',
            controller: 'FileModalController',
            controllerAs: 'folder',
            resolve: {
                active: function () {
                    return ctrl.active;
                }
            }
        });
        modalInstance.result.then(function (name) {
            mcapi('/datadirs')
                .success(function (datadir) {
                    datadir.parent = ctrl.active;
                    datadir.group = true;
                    ctrl.active.addFolder = false;
                    ctrl.active.children.push(datadir);
                    pubsub.send('files.refresh');
                })
                .error(function (err) {
                    toastr.error("Create folder failed: " + err.error, "Error");
                })
                .post({
                    project_id: project.id,
                    parent: ctrl.active.df_id,
                    name: ctrl.active.name + '/' + name,
                    level: ctrl.active.level+1
                });
        });
    }

    // TODO: Clean this up so we don't have to search for different id keys
    // returns the file id depending on which key it is under.
    function getID(file) {
        if ('df_id' in file) {
            return file.df_id;
        } else if ('datafile_id' in file) {
            return file.datafile_id;
        } else if ('id' in file) {
            return file.id;
        } else {
            return ""
        }
    }

    function getActiveFile() {
        ctrl.active = projectFiles.getActiveFile();
        if (!ctrl.active) {
            // A refresh on page has happened. That means we have lost
            // our state in the directory tree. We have the file but
            // tree isn't open on that file. In this case we show the
            // top level directory.
            ctrl.active = ctrl.active = projectFiles.getActiveDirectory();
            //ctrl.type = 'dir';
        } else {
            if (_.isObject(ctrl.active.mediatype)) {
                // TODO: Fix this hack
                // This exists because search sends back the full mediatype, while
                // the tree doesn't.
                ctrl.active.mediatype = ctrl.active.mediatype.mime;
            }
            //ctrl.type = 'file';
            if (isImage(ctrl.active.mediatype)) {
                ctrl.fileType = "image";
            } else if (ctrl.active.mediatype === "application/pdf") {
                ctrl.fileType = "pdf";
            } else if (ctrl.active.mediatype === "application/vnd.ms-excel") {
                ctrl.fileType = "xls";
            } else {
                ctrl.fileType = ctrl.active.mediatype;
            }
        }
    }

    function init() {
        ctrl.active = {};
        ctrl.type = $stateParams.file_type;
        if (ctrl.type == 'datafile') {
            getActiveFile();
        } else {
            ctrl.active = projectFiles.getActiveDirectory();
        }
    }
}

////////////////////////////////

Application.Controllers.controller("FileModalController",
    ["$modalInstance", "active", FileModalController]);
function FileModalController($modalInstance, active) {
    var ctrl = this;
    ctrl.name = "";
    ctrl.useName = useName;
    ctrl.cancel = cancel;

    ///////////

    function useName() {
        if (ctrl.name != "" && ctrl.name != active.name) {
            $modalInstance.close(ctrl.name);
        }
    }

    function cancel() {
        $modalInstance.dismiss('cancel');
    }
}<|endoftext|>


<commit_before>function createProjectsPanel(renderer, scale){

   var STANDARD_DIMENSIONS = {width: 460, height:287};

   var width = STANDARD_DIMENSIONS.width * scale,
       height = STANDARD_DIMENSIONS.height * scale;

   var panel = createPanel(renderer, width, height, {foregroundGlow: true});

   var encomGlobe,
       encomBoardroom,
       hexasphere,
       githubWargames,
       mousePos = null,
       currentSelection = -1;

   var menu = [
               {title: "ENCOM BOARDROOM", pic: "images/projects-boardroom.png", url: "http://www.robscanlon.com/encom-boardroom"},
               {title: "ENCOM GLOBE", pic: "images/projects-globe.png", url: "http://www.robscanlon.com/encom-globe"},
               {title: "GITHUB WARGAMES", pic: "images/projects-wargames.png", url: "http://www.robscanlon.com/github-wargames"},
               {title: "PLEASEROTATE.JS", pic: "images/projects-rotate.png", url: "http://www.robscanlon.com/pleaserotate"}
              ];

    var choices = [];

    function createTextPlane(text, header){
       var titleCanvas =  panel.renderToCanvas(512, 160, function(ctx){
           ctx.strokeStyle="#eac7df";

           ctx.fillStyle = '#eac7df';
           ctx.font = "18pt Roboto";
           if(header){
               ctx.font = "26pt Roboto";

               if(orange){
                   ctx.fillStyle = '#f15a24';
               } else {
                   ctx.fillStyle = '#12b7a7';
               }
           }

           ctx.fillText(text.toUpperCase(), 50, 35);

       });

        var titleTexture = new THREE.Texture(titleCanvas)
        titleTexture.needsUpdate = true;

        var titleMaterial = new THREE.MeshBasicMaterial({map: titleTexture, transparent: true});
        var titleGeometry = new THREE.PlaneBufferGeometry( 256 * scale, 80 * scale);

        var plane = new THREE.Mesh( titleGeometry, titleMaterial );
        return plane;

    }
    function buildMenu(){
        for(var i = 0; i< menu.length; i++){
            var leftPlane = createTextPlane(menu[i].title);
            leftPlane.position.set(170 * scale, height - 110*scale - 20*scale*i, 0);
            panel.addToScene(leftPlane);
            leftPlane._index = i;
            choices.push(leftPlane);

            var menuTexture = THREE.ImageUtils.loadTexture(menu[i].pic, undefined, LOADSYNC.register() );
            var menuMaterial = new THREE.MeshBasicMaterial({map: menuTexture, depthTest: false, transparent: true, blending: THREE.AdditiveBlending, opacity: 0.0});
            var menuGeometry = new THREE.PlaneBufferGeometry( 281 * scale, 281 * scale);
            var menuPlane = new THREE.Mesh(menuGeometry, menuMaterial );
            menuPlane.scale.set(.5,.5,.5);
            // headerPlane.position.set(108 * scale, height - 90 * scale,5);
            menuPlane.position.set(306 * scale, 140 * scale, 0);
            panel.addToScene(menuPlane);

            menu[i].rightPlane = createTextPlane(menu[i].title);
            menu[i].rightPlane.position.set(-100, 30*scale, 0);
            menu[i].picPlane = menuPlane;
            panel.addToScene(menu[i].rightPlane);

        }
    }

    function init(){

        var backgroundTexture = THREE.ImageUtils.loadTexture("images/projects-background.png", undefined, LOADSYNC.register() );
        var backgroundMaterial = new THREE.MeshBasicMaterial({map: backgroundTexture, depthTest: false, transparent: true});
        var backgroundGeometry = new THREE.PlaneBufferGeometry( 776 * scale, 494 * scale);
        var backgroundPlane = new THREE.Mesh(backgroundGeometry, backgroundMaterial );
        backgroundPlane.scale.set(.5,.5,.5);
        // headerPlane.position.set(108 * scale, height - 90 * scale,5);
        backgroundPlane.position.set(width/2, height/2, 0);
        panel.addToScene(backgroundPlane);

        buildMenu();

    }

    function render(time){

        panel.render(time);
    }

    function setMenu(index){
        if(index >= 0 && index < menu.length){
            for(var i = 0; i< menu.length; i++){
                menu[i].rightPlane.position.x = 450 * scale * (i == index) - 100 * scale;
                menu[i].picPlane.material.opacity = (i == index);

            }

        }
        currentSelection = index;
    }

    function clearMenu(){
        if(currentSelection > -1){
            menu[currentSelection].rightPlane.position.x = 450 * scale *  - 100 * scale;
            menu[currentSelection].picPlane.material.opacity = 0;
        }

        currentSelection = -1;

    }

    function checkBounds(x,y){
        if(!panel.checkBounds(x,y)){
            mousePos = null;
            return false;
        }
        var pos = panel.positionWithinPanel(x,y);

        if(pos.x > 60 * scale && pos.x < 200 * scale){
            var index = Math.floor(((height-pos.y) - 72 * scale) / (20 * scale));
            if(index >= 0 && index < choices.length){
                setMenu(index);
                return menu[index].url;
            }
        }

        clearMenu();

        return false;
    }

    init();

    return Object.freeze({
        toString: function(){return "ProjectsPanel"},
        render: render,
        renderTarget: panel.renderTarget,
        width: width,
        height: height,
        quad: panel.quad,
        checkBounds: checkBounds,
        setBlur: panel.setBlur,
        setPosition: panel.setPosition
    });
}

<commit_msg>Add cycling to the projects tab<commit_after>function createProjectsPanel(renderer, scale){

   var STANDARD_DIMENSIONS = {width: 460, height:287};

   var width = STANDARD_DIMENSIONS.width * scale,
       height = STANDARD_DIMENSIONS.height * scale;

   var panel = createPanel(renderer, width, height, {foregroundGlow: true});

   var encomGlobe,
       encomBoardroom,
       hexasphere,
       githubWargames,
       mousePos = null,
       currentSelection = -1,
       currentTween = null,
       currentTimeout = null;

   var menu = [
               {title: "ENCOM BOARDROOM", pic: "images/projects-boardroom.png", url: "http://www.robscanlon.com/encom-boardroom"},
               {title: "ENCOM GLOBE", pic: "images/projects-globe.png", url: "http://www.robscanlon.com/encom-globe"},
               {title: "GITHUB WARGAMES", pic: "images/projects-wargames.png", url: "http://www.robscanlon.com/github-wargames"},
               {title: "PLEASEROTATE.JS", pic: "images/projects-rotate.png", url: "http://www.robscanlon.com/pleaserotate"}
              ];

    var choices = [];

    function createTextPlane(text, header){
       var titleCanvas =  panel.renderToCanvas(512, 160, function(ctx){
           ctx.strokeStyle="#eac7df";

           ctx.fillStyle = '#eac7df';
           ctx.font = "18pt Roboto";
           if(header){
               ctx.font = "26pt Roboto";

               if(orange){
                   ctx.fillStyle = '#f15a24';
               } else {
                   ctx.fillStyle = '#12b7a7';
               }
           }

           ctx.fillText(text.toUpperCase(), 50, 35);

       });

        var titleTexture = new THREE.Texture(titleCanvas)
        titleTexture.needsUpdate = true;

        var titleMaterial = new THREE.MeshBasicMaterial({map: titleTexture, transparent: true});
        var titleGeometry = new THREE.PlaneBufferGeometry( 256 * scale, 80 * scale);

        var plane = new THREE.Mesh( titleGeometry, titleMaterial );
        return plane;

    }
    function buildMenu(){
        for(var i = 0; i< menu.length; i++){
            var leftPlane = createTextPlane(menu[i].title);
            leftPlane.position.set(170 * scale, height - 110*scale - 20*scale*i, 0);
            panel.addToScene(leftPlane);
            leftPlane._index = i;
            choices.push(leftPlane);

            var menuTexture = THREE.ImageUtils.loadTexture(menu[i].pic, undefined, LOADSYNC.register() );
            var menuMaterial = new THREE.MeshBasicMaterial({map: menuTexture, depthTest: false, transparent: true, blending: THREE.AdditiveBlending, opacity: 0.0});
            var menuGeometry = new THREE.PlaneBufferGeometry( 281 * scale, 281 * scale);
            var menuPlane = new THREE.Mesh(menuGeometry, menuMaterial );
            menuPlane.scale.set(.5,.5,.5);
            // headerPlane.position.set(108 * scale, height - 90 * scale,5);
            menuPlane.position.set(306 * scale, 140 * scale, 0);
            panel.addToScene(menuPlane);

            menu[i].rightPlane = createTextPlane(menu[i].title);
            menu[i].rightPlane.position.set(-100, 30*scale, 0);
            menu[i].picPlane = menuPlane;
            menu[i].leftPlane = leftPlane;
            panel.addToScene(menu[i].rightPlane);

        }
    }

    function init(){

        var backgroundTexture = THREE.ImageUtils.loadTexture("images/projects-background.png", undefined, LOADSYNC.register() );
        var backgroundMaterial = new THREE.MeshBasicMaterial({map: backgroundTexture, depthTest: false, transparent: true});
        var backgroundGeometry = new THREE.PlaneBufferGeometry( 776 * scale, 494 * scale);
        var backgroundPlane = new THREE.Mesh(backgroundGeometry, backgroundMaterial );
        backgroundPlane.scale.set(.5,.5,.5);
        // headerPlane.position.set(108 * scale, height - 90 * scale,5);
        backgroundPlane.position.set(width/2, height/2, 0);
        panel.addToScene(backgroundPlane);

        buildMenu();

        setMenu(0);

    }

    function render(time){

        panel.render(time);
    }

    function setMenu(index){
        clearTimeout(currentTimeout);

        if(currentTween != null){
            currentTween.stop();
        }

        menu[index].leftPlane.scale.set(1.05, 1.05, 1.05);
        currentTween = new TWEEN.Tween({val: 0}, 1000)
            .to({val: 1})
            .onUpdate(function(val){
                // menu[currentSelection].picPlane.material.opacity = 1 - val;
                menu[index].picPlane.material.opacity = val;
            }).start();

        if(currentSelection >= 0){
            menu[currentSelection].leftPlane.scale.set(1, 1, 1);
            menu[currentSelection].picPlane.material.opacity = 0;
        }

        currentSelection = index;

        currentTimeout = setTimeout(function(){
            setMenu((index + 1) % menu.length);
        }, 5000);
    }

    function clearMenu(){
        if(currentSelection > -1){
            menu[currentSelection].rightPlane.position.x = 450 * scale *  - 100 * scale;
            menu[currentSelection].picPlane.material.opacity = 0;
        }

        currentSelection = -1;

    }

    function checkBounds(x,y){
        if(!panel.checkBounds(x,y)){
            mousePos = null;
            return false;
        }
        var pos = panel.positionWithinPanel(x,y);

        if(pos.x > 60 * scale && pos.x < 200 * scale){
            var index = Math.floor(((height-pos.y) - 72 * scale) / (20 * scale));
            if(index >= 0 && index < choices.length){
                if(currentSelection != index){
                    setMenu(index);
                }
                return menu[index].url;
            }
        }

        clearMenu();

        return false;
    }

    init();

    return Object.freeze({
        toString: function(){return "ProjectsPanel"},
        render: render,
        renderTarget: panel.renderTarget,
        width: width,
        height: height,
        quad: panel.quad,
        checkBounds: checkBounds,
        setBlur: panel.setBlur,
        setPosition: panel.setPosition
    });
}

<|endoftext|>


<commit_before>Application.Controllers.controller("FilesAllController",
    ["$scope", "projectFiles", "mcfile", "$state", "pubsub","$filter",  FilesAllController]);
function FilesAllController($scope, projectFiles, mcfile, $state, pubsub, $filter) {
    var f = projectFiles.model.projects[$scope.project.id].dir;

    // Root is name of project. Have it opened by default.
    $scope.files = [f];
    $scope.files[0].children = $filter('orderBy')($scope.files[0].children, 'displayname');

    pubsub.waitOn($scope, 'files.refresh', function() {
        $scope.gridOptions.api.refreshView();
    });

    $scope.fileSrc = function (file) {
        return mcfile.src(file.id);
    };

    var columnDefs = [
        {
            displayName: "",
            field: "name",
            width: 350,
            cellRenderer: function (params) {
                return '' +
                    '' +
                    params.node.name + '';
            }
        }];

    $scope.gridOptions = {
        columnDefs: columnDefs,
        rowData: $scope.files,
        rowSelection: 'multiple',
        rowsAlreadyGrouped: true,
        rowClicked: rowClicked,
        enableColResize: true,
        enableSorting: false,
        rowHeight: 30,
        angularCompileRows: true,
        icons: {
            groupExpanded: '',
            groupContracted: ''
        },
        groupInnerCellRenderer: groupInnerCellRenderer
    };

    function groupInnerCellRenderer(params) {
        var eCell = document.createElement('span');
        eCell.innerHTML = params.node.displayname;
        return eCell;
    }

    function rowClicked(params) {
        if (params.node.type == 'datadir') {
            projectFiles.setActiveDirectory(params.node)
            if (!params.node.sorted) {
                var file = projectFiles.findFileByID($scope.project.id, params.node.df_id);
                file.children = $filter('orderBy')(file.children, 'displayname');
                file.sorted = true;
                $scope.gridOptions.api.onNewRows();
            }
        } else {
            projectFiles.setActiveFile(params.node);
        }
        $state.go('projects.project.files.all.edit', {file_id: params.node.df_id, file_type: params.node.type});
    }

    function init() {
        projectFiles.setActiveDirectory($scope.files[0]);
        $state.go('projects.project.files.all.edit', {file_id: $scope.files[0].df_id, file_type: 'datadir'});
    }

    init();
}

<commit_msg>Save open state of tree so it displays in the proper state. Show different icons for different file types.<commit_after>Application.Controllers.controller("FilesAllController",
    ["$scope", "projectFiles", "mcfile", "$state", "pubsub", "$filter", FilesAllController]);
function FilesAllController($scope, projectFiles, mcfile, $state, pubsub, $filter) {
    var f = projectFiles.model.projects[$scope.project.id].dir;

    // Root is name of project. Have it opened by default.
    $scope.files = [f];
    $scope.files[0].children = $filter('orderBy')($scope.files[0].children, 'displayname');

    pubsub.waitOn($scope, 'files.refresh', function () {
        $scope.gridOptions.api.refreshView();
    });

    $scope.fileSrc = function (file) {
        return mcfile.src(file.id);
    };

    var columnDefs = [
        {
            displayName: "",
            field: "name",
            width: 350,
            cellRenderer: function (params) {
                var icon = "fa-file";
                switch (params.node.mediatype) {
                case "application/pdf":
                    icon = "fa-file-pdf-o";
                    break;
                case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":
                    icon = "fa-file-excel-o";
                    break;
                case "application/vnd.ms-excel":
                    icon = "fa-file-excel-o";
                    break;
                case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
                    icon = "fa-file-word-o";
                    break;
                case "application/ms-word":
                    icon = "fa-file-word-o";
                    break;
                case "application/vnd.ms-powerpoint.presentation.macroEnabled.12":
                    icon = "fa-file-powerpoint-o";
                    break;
                case "application/vnd.ms-powerpoint":
                    icon = "fa-file-powerpoint-o";
                    break;
                default:
                    if (isImage(params.node.mediatype)) {
                        icon = "fa-file-image-o";
                    }
                    break;
                }
                return '' +
                    '' +
                    params.node.name + '';
            }
        }];

    $scope.gridOptions = {
        columnDefs: columnDefs,
        rowData: $scope.files,
        //rowSelection: 'multiple',
        rowsAlreadyGrouped: true,
        rowClicked: rowClicked,
        enableColResize: false,
        enableSorting: false,
        rowHeight: 30,
        angularCompileRows: false,
        icons: {
            groupExpanded: '',
            groupContracted: ''
        },
        groupInnerCellRenderer: groupInnerCellRenderer
    };

    function groupInnerCellRenderer(params) {
        var eCell = document.createElement('span');
        eCell.innerHTML = params.node.displayname;
        return eCell;
    }

    function rowClicked(params) {
        if (params.node.type == 'datadir') {
            projectFiles.setActiveDirectory(params.node);
            var file = projectFiles.findFileByID($scope.project.id, params.node.df_id);
            file.expanded = params.node.expanded;
            if (!params.node.sorted) {
                file.children = $filter('orderBy')(file.children, 'displayname');
                file.sorted = true;
                $scope.gridOptions.api.onNewRows();
            }
        } else {
            projectFiles.setActiveFile(params.node);
        }
        $state.go('projects.project.files.all.edit', {file_id: params.node.df_id, file_type: params.node.type});
    }

    function init() {
        projectFiles.setActiveDirectory($scope.files[0]);
        $state.go('projects.project.files.all.edit', {file_id: $scope.files[0].df_id, file_type: 'datadir'});
    }

    init();
}

<|endoftext|>


<commit_before>var MisPars = MisPars || {};
MisPars.Parser = MisPars.Parser || {};
MisPars.AstFunctions = MisPars.AstFunctions || {};

(function(AstFunctions, Parser, undefined) {

    // Triggers are in Missions.Sensors
    AstFunctions.exportTriggers = function(ast) {

    };

    AstFunctions.select = function(ast, query) {
        var fields = query.split(".");
        var node = ast;
        var result = [];
        for (var i = 0; i < fields.length; i++) {
            var result = findFieldInNode(node, fields[i]);
            if (result.length == 1) {
                node = result[0];
            } else if (i !== fields.length - 1) {
                return [];
            }
        }
        return result;
    };

    var findFieldInNode = function(node, fieldName) {
        var result = [];
        if (node.type === Parser.NodeType.ClassField || node.type === Parser.NodeType.Root) {
            result = findFieldInArray(node.fields, fieldName);
        }
        return result;
    };

    var findFieldInArray = function(fields, fieldName) {
        var result = [];
        for(var i = 0; i < fields.length; i++) {
            if (fields[i].value === fieldName || fieldNameStarMatch(fields[i].value, fieldName)) {
                result.push(fields[i]);
            }
        }
        return result;
    };

    var fieldNameStarMatch = function(value, fieldName) {
        return fieldName.indexOf("*") === fieldName.length - 1 &&
            value.indexOf(fieldName.substring(0, fieldName.length - 1)) === 0;
    };

}(MisPars.AstFunctions, MisPars.Parser));
<commit_msg>Added trigger removal function.<commit_after>var MisPars = MisPars || {};
MisPars.Parser = MisPars.Parser || {};
MisPars.AstFunctions = MisPars.AstFunctions || {};

(function(AstFunctions, Parser, undefined) {

    // Triggers are in Missions.Sensors
    AstFunctions.removeTriggers = function(ast) {
        var missions = AstFunctions.select(ast, "Mission");
        if (missions.length === 1) {
            var sensorIndex = missions[0].fields.first(function(node) { return node.value === "Sensors" });
            if (sensorIndex >= 0) {
                missions[0].fields.splice(sensorIndex, 1);
            };
        }
    };

    AstFunctions.select = function(ast, query) {
        var fields = query.split(".");
        var node = ast;
        var result = [];
        for (var i = 0; i < fields.length; i++) {
            var result = findFieldInNode(node, fields[i]);
            if (result.length == 1) {
                node = result[0];
            } else if (i !== fields.length - 1) {
                return [];
            }
        }
        return result;
    };

    var findFieldInNode = function(node, fieldName) {
        var result = [];
        if (node.type === Parser.NodeType.ClassField || node.type === Parser.NodeType.Root) {
            result = findFieldInArray(node.fields, fieldName);
        }
        return result;
    };

    var findFieldInArray = function(fields, fieldName) {
        var result = [];
        for(var i = 0; i < fields.length; i++) {
            if (fields[i].value === fieldName || fieldNameStarMatch(fields[i].value, fieldName)) {
                result.push(fields[i]);
            }
        }
        return result;
    };

    var fieldNameStarMatch = function(value, fieldName) {
        return fieldName.indexOf("*") === fieldName.length - 1 &&
            value.indexOf(fieldName.substring(0, fieldName.length - 1)) === 0;
    };

}(MisPars.AstFunctions, MisPars.Parser));
<|endoftext|>


<commit_before>function createStacked(data, endDate, startDate) {
    d3.select(' #stacked-svg ').remove();

    let dateFormat  = "%Y-%m-%_d";
    let padding     = { top: 15, right: 15, bottom: 15, left: 15 };
    let width       = $(' #stacked-chart ').outerWidth(true) - padding.right - padding.left;
    let height      = ($(' #stacked-chart ').outerWidth(true) / 4) - padding.top - padding.bottom;
    let legendHgt   = 30;

    $(' #stacked-chart ').width(width);
    $(' #stacked-chart ').height(height + legendHgt);
    $(' #stacked-chart ').css('padding', padding.top + 'px ' + padding.right + 'px ' + padding.bottom + 'px ' + padding.left + 'px');

    let d3DateParse = d3.timeParse(dateFormat);

    let maxData     = _.chain(data).find(['state', 'daily']).get('data').maxBy('y1').value().y1;
    let keys        = _.map(data, 'state');

    let x           = d3.scaleTime().domain([d3DateParse(startDate), d3DateParse(endDate)]).range([0, width]);
    let y           = d3.scaleLinear().domain([-maxData, maxData]).range([height, 0]);

    let positiveArea    = d3.area().x((o) => (x(d3DateParse(o.date)))).y0((o) => (y(o.y0))).y1((o) => (y(o.y1)));
    let negativeArea    = d3.area().x((o) => (x(d3DateParse(o.date)))).y0((o) => (y(-o.y0))).y1((o) => (y(-o.y1)));

    var svg = d3.select(' #stacked-chart ').append('svg')
        .attr('id', 'stacked-svg')
        .attr('width', width)
        .attr('height', height + legendHgt);

    svg.append('g')
        .selectAll('.positive-layer')
        .data(data)
        .enter().append('path')
            .attr('class', (d) => ('positive-layer stacked-layers layer-' + d.state ))
            .attr('d', (d) => (positiveArea(d.data)));

    svg.append('g')
        .selectAll('.negative-layer')
        .data(data)
        .enter().append('path')
            .attr('class', (d) => ('negative-layer stacked-layers layer-' + d.state ))
            .attr('d', (d) => (negativeArea(d.data)));

    // centerLine
    svg.append('g')
        .attr('class', 'center-line')
        .attr('transform', 'translate(0,' + y(0) + ')')
        .attr('width', width)
        .call(d3.axisTop(x).tickSize(12).tickFormat(d3.timeFormat('%b %Y')))
        .selectAll('text')
            .attr('dx', 23)
            .attr('dy', 12)
            .attr('class', 'noselect cursor-default');;

    var legend  = svg.append('g')
        .attr('id', 'legend-group')
        .attr('transform', 'translate(' + (width * 3 / 4) + ', ' + (height + legendHgt - 20) + ')')
        .selectAll('.legend')
            .data(keys)
            .enter().append('g')
                .attr('class', 'legend noselect')
                .attr('transform', (o, i) => ('translate(' + (i * (width / 16))  + ', 0)'));

    legend.append('rect')
        .attr('class', (o) => ('rect-' + o));

    legend.append('text')
        .attr('y', 14)
        .attr('x', 23)
        .style('font-size', '12px')
        .attr('class', (o) => ('text-' + o))
        .text((o) => (_.upperFirst(o)));
}
<commit_msg>zoom and pan<commit_after>function createStacked(data, endDate, startDate) {
    d3.select(' #stacked-svg ').remove();

    let dateFormat  = "%Y-%m-%_d";
    let padding     = { top: 15, right: 15, bottom: 15, left: 15 };
    let width       = $(' #stacked-chart ').outerWidth(true) - padding.right - padding.left;
    let height      = ($(' #stacked-chart ').outerWidth(true) / 4) - padding.top - padding.bottom;
    let legendHgt   = 30;

    $(' #stacked-chart ').width(width);
    $(' #stacked-chart ').height(height + legendHgt);
    $(' #stacked-chart ').css('padding', padding.top + 'px ' + padding.right + 'px ' + padding.bottom + 'px ' + padding.left + 'px');

    let d3DateParse = d3.timeParse(dateFormat);

    let maxData     = _.chain(data).find(['state', 'daily']).get('data').maxBy('y1').value().y1;
    let keys        = _.map(data, 'state');

    let x           = d3.scaleTime().domain([d3DateParse(startDate), d3DateParse(endDate)]).range([0, width]);
    let defaultx    = d3.scaleTime().domain([d3DateParse(startDate), d3DateParse(endDate)]).range([0, width]);
    let y           = d3.scaleLinear().domain([-maxData, maxData]).range([height, 0]);

    // let xAxis       = d3.axisTop(x).tickSize(12).tickFormat(d3.timeFormat('%b %Y'));
    let xAxis       = d3.axisTop(x).tickSize(12);

    let positiveArea    = d3.area().x((o) => (x(d3DateParse(o.date)))).y0((o) => (y(o.y0))).y1((o) => (y(o.y1)));
    let negativeArea    = d3.area().x((o) => (x(d3DateParse(o.date)))).y0((o) => (y(-o.y0))).y1((o) => (y(-o.y1)));

    var zoom = d3.zoom()
        .scaleExtent([1, 10])
        .translateExtent([[0, 0], [width, height]])
        .on("zoom", () => {
            var transform = d3.event.transform;
            x.domain(transform.rescaleX(defaultx).domain());
            d3.select(' .center-line ').call(xAxis);
            d3.selectAll(' path.positive-layer ').attr('d', (d) => (positiveArea(d.data)));
            d3.selectAll(' path.negative-layer ').attr('d', (d) => (negativeArea(d.data)));

        });

    var svg = d3.select(' #stacked-chart ').append('svg')
        .attr('id', 'stacked-svg')
        .attr('width', width)
        .attr('height', height + legendHgt);

    svg.append('g')
        .attr('id', 'positive-container')
        .selectAll('.positive-layer')
        .data(data)
        .enter().append('path')
            .attr('class', (d) => ('positive-layer stacked-layers layer-' + d.state ))
            .attr('d', (d) => (positiveArea(d.data)));

    svg.append('g')
        .attr('id', 'negative-container')
        .selectAll('.negative-layer')
        .data(data)
        .enter().append('path')
            .attr('class', (d) => ('negative-layer stacked-layers layer-' + d.state ))
            .attr('d', (d) => (negativeArea(d.data)));

    // centerLine
    svg.append('g')
        .attr('class', 'center-line')
        .attr('transform', 'translate(0,' + y(0) + ')')
        .attr('width', width)
        .call(xAxis)
        .selectAll('text')
            // .attr('dx', 23)
            // .attr('dy', 12)
            .attr('class', 'noselect cursor-default');

    svg.append('rect')
        .attr('id', 'zoom-pane')
        .attr('width', width)
        .attr('height', height + legendHgt)
        .attr('transform', 'translate(0,0)')
        .call(zoom);

    var legend  = svg.append('g')
        .attr('id', 'legend-group')
        .attr('transform', 'translate(' + (width * 3 / 4) + ', ' + (height + legendHgt - 20) + ')')
        .selectAll('.legend')
            .data(keys)
            .enter().append('g')
                .attr('class', 'legend noselect')
                .attr('transform', (o, i) => ('translate(' + (i * (width / 16))  + ', 0)'));

    legend.append('rect')
        .attr('class', (o) => ('rect-' + o));

    legend.append('text')
        .attr('y', 14)
        .attr('x', 23)
        .style('font-size', '12px')
        .attr('class', (o) => ('text-' + o))
        .text((o) => (_.upperFirst(o)));
}
<|endoftext|>


<commit_before>/*
 * Crypto-JS v2.5.4
 * http://code.google.com/p/crypto-js/
 * (c) 2009-2012 by Jeff Mott. All rights reserved.
 * http://code.google.com/p/crypto-js/wiki/License
 */
(typeof Crypto=="undefined"||!Crypto.util)&&function(){var f=window.Crypto={},l=f.util={rotl:function(b,a){return b<<a|b>>>32-a},rotr:function(b,a){return b<<32-a|b>>>a},endian:function(b){if(b.constructor==Number)return l.rotl(b,8)&16711935|l.rotl(b,24)&4278255360;for(var a=0;a<b.length;a++)b[a]=l.endian(b[a]);return b},randomBytes:function(b){for(var a=[];b>0;b--)a.push(Math.floor(Math.random()*256));return a},bytesToWords:function(b){for(var a=[],c=0,d=0;c<b.length;c++,d+=8)a[d>>>5]|=(b[c]&255)<<
24-d%32;return a},wordsToBytes:function(b){for(var a=[],c=0;c<b.length*32;c+=8)a.push(b[c>>>5]>>>24-c%32&255);return a},bytesToHex:function(b){for(var a=[],c=0;c<b.length;c++)a.push((b[c]>>>4).toString(16)),a.push((b[c]&15).toString(16));return a.join("")},hexToBytes:function(b){for(var a=[],c=0;c<b.length;c+=2)a.push(parseInt(b.substr(c,2),16));return a},bytesToBase64:function(b){for(var a=[],c=0;c<b.length;c+=3)for(var d=b[c]<<16|b[c+1]<<8|b[c+2],q=0;q<4;q++)c*8+q*6<=b.length*8?a.push("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(d>>>
6*(3-q)&63)):a.push("=");return a.join("")},base64ToBytes:function(b){for(var b=b.replace(/[^A-Z0-9+\/]/ig,""),a=[],c=0,d=0;c<b.length;d=++c%4)d!=0&&a.push(("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(b.charAt(c-1))&Math.pow(2,-2*d+8)-1)<<d*2|"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(b.charAt(c))>>>6-d*2);return a}},f=f.charenc={};f.UTF8={stringToBytes:function(b){return i.stringToBytes(unescape(encodeURIComponent(b)))},bytesToString:function(b){return decodeURIComponent(escape(i.bytesToString(b)))}};
var i=f.Binary={stringToBytes:function(b){for(var a=[],c=0;c<b.length;c++)a.push(b.charCodeAt(c)&255);return a},bytesToString:function(b){for(var a=[],c=0;c<b.length;c++)a.push(String.fromCharCode(b[c]));return a.join("")}}}();
(function(){var f=Crypto,l=f.util,i=f.charenc,b=i.UTF8,a=i.Binary,c=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,
2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],d=f.SHA256=function(b,c){var e=l.wordsToBytes(d._sha256(b));return c&&c.asBytes?e:c&&c.asString?a.bytesToString(e):l.bytesToHex(e)};d._sha256=function(a){a.constructor==String&&(a=b.stringToBytes(a));var d=l.bytesToWords(a),e=a.length*8,a=[1779033703,3144134277,
1013904242,2773480762,1359893119,2600822924,528734635,1541459225],f=[],m,n,i,h,o,p,r,s,g,k,j;d[e>>5]|=128<<24-e%32;d[(e+64>>9<<4)+15]=e;for(s=0;s<d.length;s+=16){e=a[0];m=a[1];n=a[2];i=a[3];h=a[4];o=a[5];p=a[6];r=a[7];for(g=0;g<64;g++){g<16?f[g]=d[g+s]:(k=f[g-15],j=f[g-2],f[g]=((k<<25|k>>>7)^(k<<14|k>>>18)^k>>>3)+(f[g-7]>>>0)+((j<<15|j>>>17)^(j<<13|j>>>19)^j>>>10)+(f[g-16]>>>0));j=e&m^e&n^m&n;var t=(e<<30|e>>>2)^(e<<19|e>>>13)^(e<<10|e>>>22);k=(r>>>0)+((h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25))+
(h&o^~h&p)+c[g]+(f[g]>>>0);j=t+j;r=p;p=o;o=h;h=i+k>>>0;i=n;n=m;m=e;e=k+j>>>0}a[0]+=e;a[1]+=m;a[2]+=n;a[3]+=i;a[4]+=h;a[5]+=o;a[6]+=p;a[7]+=r}return a};d._blocksize=16;d._digestsize=32})();
<commit_msg>Delete crypto-sha256.js<commit_after><|endoftext|>


<commit_before>/*

	audio player

*/

var diAudioPlayer = function (_opts) {
    var self = this,
        audio = null,
        audioLoaded = false,
        opts = $.extend({
            audio: null,
            onEnd: null
        }, _opts || {});

    this.PAUSE = 1;
    this.PLAY = 2;
    this.END = 3;
    this.UNKNOWN = 0;

    function constructor() {
        if (opts.audio) {
            self.setElement(opts.audio);

            if (opts.onEnd) {
                $(audio).on('ended', opts.onEnd);
            }
        }
    }

    this.getElement = function () {
        return audio;
    };

    this.setElement = function (e) {
        if (e instanceof jQuery) {
            e = e.length > 0 ? e.get(0) : null;
        }

        audio = e;
        audio.crossOrigin = 'anonymous';

        return this;
    };

    this.fixCORS = function (src) {
        src = src || audio.src;

        if (src) {
            this.setSource(null);

            audio.crossOrigin = 'anonymous';
            this.setSource(src);

            //console.log('diAudioPlayer: CORS fixed');
        }

        return this;
    };

    this.disableCORS = function () {
        if (typeof audio.crossOrigin !== 'undefined') {
            audio.crossOrigin = null;
        }

        return this;
    };

    this.setSource = function (source) {
        audio.src = source;
        audio.load();
        audioLoaded = true;

        return this;
    };

    this.play = function () {
        if (typeof audio.play !== 'undefined') {
            if (!audioLoaded) {
                audio.load();

                audioLoaded = true;
            }

            var promise = audio.play();

            if (promise !== undefined) {
                promise
                    .then(function () {
                        //console.log('diAudioPlayer: audio track started');
                    })
                    .catch(function (error) {
                        console.log('diAudioPlayer: error playing audio track', error);
                    });
            }
        } else {
            throw 'Audio player not initialized';
        }

        return this;
    };

    this.pause = function () {
        audio.pause();

        return this;
    };

    this.toggleState = function () {
        if (this.getState() != this.PAUSE) {
            this.pause();
        }
        else {
            this.play();
        }

        return this;
    };

    this.getState = function () {
        if (audio.paused) return this.PAUSE;
        else if (audio.ended) return this.END;
        else if (audio.played) return this.PLAY;
        else return this.UNKNOWN;
    };

    this.getCurrentTime = function () {
        return audio.currentTime;
    };

    this.setCurrentTime = function (time) {
        audio.currentTime = time;

        return this;
    };

    this.setPosition = function (percent) {
        this.setCurrentTime(this.getDuration() * percent / 100);

        return this;
    };

    this.getDuration = function () {
        return audio.duration;
    };

    this.isPlayed = function () {
        return this.getState() == this.PLAY;
    };

    this.isPaused = function () {
        return this.getState() == this.PAUSE;
    };

    this.isEnded = function () {
        return this.getState() == this.END;
    };

    /* 0.0 ... 1.0 */
    this.setVolume = function (volume) {
        volume *= 1;

        if (volume < 0) volume = 0;
        else if (volume > 1) volume = 1;

        audio.volume = volume;

        return this;
    };

    this.getVolume = function () {
        return audio.volume;
    };

    constructor();
};
<commit_msg>diaudioplayer fixes<commit_after>/*

	audio player

*/

var diAudioPlayer = function (_opts) {
    var self = this,
        audioLoaded = false,
        opts = $.extend({
            audio: null,
            onEnd: null
        }, _opts || {});

    this.audio = null;
    this.PAUSE = 1;
    this.PLAY = 2;
    this.END = 3;
    this.UNKNOWN = 0;

    function constructor() {
        if (opts.audio) {
            self.setElement(opts.audio);

            if (opts.onEnd) {
                $(self.audio).on('ended', opts.onEnd);
            }
        }
    }

    this.getElement = function () {
        return this.audio;
    };

    this.setElement = function (e) {
        if (e instanceof jQuery) {
            e = e.length > 0 ? e.get(0) : null;
        }

        if (e) {
            this.audio = e;
            this.audio.crossOrigin = 'anonymous';
        }

        return this;
    };

    this.fixCORS = function (src) {
        src = src || this.audio.src;

        if (src) {
            this.setSource(null);

            this.audio.crossOrigin = 'anonymous';
            this.setSource(src);

            //console.log('diAudioPlayer: CORS fixed');
        }

        return this;
    };

    this.disableCORS = function () {
        if (typeof this.audio.crossOrigin !== 'undefined') {
            this.audio.crossOrigin = null;
        }

        return this;
    };

    this.setSource = function (source) {
        this.audio.src = source;
        this.audio.load();
        audioLoaded = true;

        return this;
    };

    this.play = function () {
        if (typeof this.audio.play !== 'undefined') {
            if (!audioLoaded) {
                this.audio.load();

                audioLoaded = true;
            }

            var promise = this.audio.play();

            if (promise !== undefined) {
                promise
                    .then(function () {
                        //console.log('diAudioPlayer: audio track started');
                    })
                    .catch(function (error) {
                        console.log('diAudioPlayer: error playing audio track', error);
                    });
            }
        } else {
            throw 'Audio player not initialized';
        }

        return this;
    };

    this.pause = function () {
        this.audio.pause();

        return this;
    };

    this.toggleState = function () {
        if (this.getState() != this.PAUSE) {
            this.pause();
        }
        else {
            this.play();
        }

        return this;
    };

    this.getState = function () {
        if (this.audio.paused) return this.PAUSE;
        else if (this.audio.ended) return this.END;
        else if (this.audio.played) return this.PLAY;
        else return this.UNKNOWN;
    };

    this.getCurrentTime = function () {
        return this.audio.currentTime;
    };

    this.setCurrentTime = function (time) {
        this.audio.currentTime = time;

        return this;
    };

    this.setPosition = function (percent) {
        this.setCurrentTime(this.getDuration() * percent / 100);

        return this;
    };

    this.getDuration = function () {
        return this.audio.duration;
    };

    this.isPlayed = function () {
        return this.getState() == this.PLAY;
    };

    this.isPaused = function () {
        return this.getState() == this.PAUSE;
    };

    this.isEnded = function () {
        return this.getState() == this.END;
    };

    /* 0.0 ... 1.0 */
    this.setVolume = function (volume) {
        volume = parseFloat(volume) || 0;

        if (volume < 0) volume = 0;
        else if (volume > 1) volume = 1;

        if (this.audio) {
            this.audio.volume = volume;
        }

        return this;
    };

    this.getVolume = function () {
        return this.audio.volume;
    };

    constructor();
};
<|endoftext|>


<commit_before>
(function($) {

    var default_options = {
        template          : "<editor/><panel><button/></panel>",

        className         : "emojionearea",
        editorClassName   : "emojionearea-editor",
        panelClassName    : "emojionearea-panel",
        buttonClassName   : "emojionearea-button",

        dir               : "ltr",
        spellcheck        : true,
        autocomplete      : "off",
        autocorrect       : "off",
        autocapitalize    : "off"
    };

    var EmojioneArea = function(element, options) {
        this.element = element;
        this.options = $.extend({}, default_options, options);
        this.events = {};

        this.init();
    };

    EmojioneArea.prototype.on = function(events, handler) {
        if (!!events && !!handler && Array.prototype.toString.call(handler) == '[object Function]') {
            $.each(events.split(' '), $.proxy(function(i, event) {
                if (!this.events[event]) {
                    this.events[event] = [];
                }
                this.events[event].push(handler);
            }, this));
        }
        return this;
    };

    EmojioneArea.prototype.off = function(events, handler) {
        if (!!events) {
            if (!!handler) {
                if (Array.prototype.toString.call(handler) == '[object Function]') {
                    $.each(events.split(' '), $.proxy(function(i, event) {
                        if (!!this.events[event] && !!this.events[event].length) {
                            $.each(this.events[event], $.proxy(function(j, attachedHandler) {
                                if (attachedHandler === handler) {
                                    this.events[event] = this.events[event].splice(j, 1);
                                }
                            }, this));
                        }
                    }, this));
                }
            } else {
                $.each(events.split(' '), $.proxy(function(i, event) {
                    this.events[event] = [];
                }, this));
            }
        }
        return this;
    };

    EmojioneArea.prototype.trigger = function() {
        var result = true;
        if (!!arguments.length) {
            var args = Array.prototype.slice.call(arguments);
            args = args.slice(1);
            $.each(arguments[0].split(' '), $.proxy(function(i, event) {
                if (!!this.events[event] && !!this.events[event].length) {
                    $.each(this.events[event], function (i, f) {
                        return result = f.apply(f, args) !== false;
                    });
                }
                return result;
            }, this));
        }
        return result;
    };

    EmojioneArea.prototype.attach = function(element, elementEvents, events) {
        element.on(elementEvents, $.proxy(function() {
            return this.trigger((!!events ? events : elementEvents), arguments)
        }, this));

        return this;
    };

    EmojioneArea.prototype.setText = function(content) {
        content = content
            .replace(/</g, '<').replace(/>/g, '>')
            .replace(/(?:\r\n|\r|\n)/g, '\n')
            .replace(/(\n+)/g, '
$1
')
            .replace(/\n/g, '
')
            .replace(/
<\/div>/g, '
');

        var emojioneImageType = emojione.imageType;
        emojione.imageType = 'png';
        content = emojione.unicodeToImage(content);
        emojione.imageType = emojioneImageType;

        this.editor.html('
' + content + '
');
        this.content = this.editor.html();
        this.trigger('emojioneArea.change change', this.content);
    }

    EmojioneArea.prototype.getText = function() {
        return this.editor.html()
            .replace(/]+)"[^>]+>/ig, '$1')
            .replace(/\n/g, '')
            .replace(/
]+)?>/ig, '\n')
            .replace(/(?:
]+)?>)+/ig, '
')
            .replace(/(?:<\/div>)+/ig, '
')
            .replace(/(?:
]+)?>)+/ig, '
')
            .replace(/(?:<\/p>)+/ig, '
')
            .replace(/\n
<\/div>/ig, '\n')
            .replace(/
<\/div>\n/ig, '\n')
            .replace(/(?:
)+<\/div>/ig, '\n')
            .replace(/([^\n])<\/div>
/ig, '$1\n')
            .replace(/(?:<\/div>)+/ig, '')
            .replace(/([^\n])
/ig, '$1\n')
            .replace(/\n
/ig, '\n')
            .replace(/
\n/ig, '\n\n')
            .replace(/<(?:[^>]+)?>/ig, '');
    }

    EmojioneArea.prototype.init = function() {
        this.type = this.element.is("INPUT") ? 'val' : 'text';

        var html = this.options.template
            .replace("<editor/>", '

')
            .replace("<button/>", '

')
            .replace("<panel>", '
').replace("</panel>", '
');

        $.each(["editorClassName", "buttonClassName", "panelClassName"], $.proxy(function(i, name) {
            html = html.replace("{{" + name + "}}", this.options[name]);
        }, this));

        html = $('
' + html + '
').addClass(this.options.className).attr("role", "application");

        this.editor = html.find("." + this.options.editorClassName).attr("contenteditable", "true");
        this.button = html.find("." + this.options.buttonClassName);
        this.panel  = html.find("." + this.options.panelClassName);

        $.each(["dir", "spellcheck", "autocomplete", "autocorrect", "autocapitalize"], $.proxy(function(i, name) {
            this.editor.attr(name, this.options[name]);
        }, this));

        this.panel.on("mousedown", function(e) {
            e.preventDefault();
            return false;
        });

        this.button.on("mousedown", function(e) {
            e.preventDefault();
            return false;
        });

        this.attach(this.editor, "mousedown")
            .attach(this.editor, "mouseup")
            .attach(this.editor, "focus", "emojioneArea.focus focus")
            .attach(this.editor, "blur", "emojioneArea.blur blur")
            .attach(this.editor, "click")
            .attach(this.editor, "keyup")
            .attach(this.editor, "keydown");

        this.on("emojioneArea.change", $.proxy(function() {
            this.element[this.type](this.getText());
        }, this)).on("emojioneArea.focus", function() {
            html.addClass("focused");
        }).on("emojioneArea.blur", $.proxy(function() {
            html.removeClass("focused");
            var content = this.editor.html();
            if (this.content !== content) {
                this.content = content;
                this.trigger('emojioneArea.change change', this.content);
            }
        }, this));

        html.insertAfter(this.element);
        this.element.hide();
        this.setText(this.element[this.type]());
    };

    $.fn.emojioneArea = function(options) {
        return this.each(function(){
            if (!!this.emojioneArea) return this.emojioneArea;
            return this.emojioneArea = new EmojioneArea($(this), options);
        });
    };

}) (jQuery);

// smiles
// fa-smile-o, fa-clock-o, (fa-flag fa-flag-checkered fa-flag-o), fa-leaf, fa-track, fa-cutlery,  fa-trophy,  fa-gift, fa-heart,  fa-ellipsis-h<commit_msg>Update emojione-area.js<commit_after>
(function($) {

    var default_options = {
        template          : "<editor/><panel><button/></panel>",

        className         : "emojionearea",
        editorClassName   : "emojionearea-editor",
        panelClassName    : "emojionearea-panel",
        buttonClassName   : "emojionearea-button",

        dir               : "ltr",
        spellcheck        : true,
        autocomplete      : "off",
        autocorrect       : "off",
        autocapitalize    : "off"
    };

    var EmojioneArea = function(element, options) {
        this.element = element;
        this.options = $.extend({}, default_options, options);
        this.events = {};

        this.init();
    };

    EmojioneArea.prototype.on = function(events, handler) {
        if (!!events && !!handler && Array.prototype.toString.call(handler) == '[object Function]') {
            $.each(events.split(' '), $.proxy(function(i, event) {
                if (!this.events[event]) {
                    this.events[event] = [];
                }
                this.events[event].push(handler);
            }, this));
        }
        return this;
    };

    EmojioneArea.prototype.off = function(events, handler) {
        if (!!events) {
            if (!!handler) {
                if (Array.prototype.toString.call(handler) == '[object Function]') {
                    $.each(events.split(' '), $.proxy(function(i, event) {
                        if (!!this.events[event] && !!this.events[event].length) {
                            $.each(this.events[event], $.proxy(function(j, attachedHandler) {
                                if (attachedHandler === handler) {
                                    this.events[event] = this.events[event].splice(j, 1);
                                }
                            }, this));
                        }
                    }, this));
                }
            } else {
                $.each(events.split(' '), $.proxy(function(i, event) {
                    this.events[event] = [];
                }, this));
            }
        }
        return this;
    };

    EmojioneArea.prototype.trigger = function(events, args) {
        var result = true;
        if (!!events) {
            if (!args) {
                args = [];
            }
            $.each(events.split(' '), $.proxy(function(i, event) {
                if (!!this.events[event] && !!this.events[event].length) {
                    $.each(this.events[event], function (i, f) {
                        return result = f.apply(null, args) !== false;
                    });
                }
                return result;
            }, this));
        }
        return result;
    };

    EmojioneArea.prototype.attach = function(element, elementEvents, events) {
        $.each(element, $.proxy(function(i, e) {
            $(e).on(elementEvents, $.proxy(function() {
                return this.trigger((!!events ? events : elementEvents), arguments)
            }, this));
        }, this));

        return this;
    };

    EmojioneArea.prototype.setText = function(content) {
        content = content
            .replace(/</g, '<').replace(/>/g, '>')
            .replace(/(?:\r\n|\r|\n)/g, '\n')
            .replace(/(\n+)/g, '
$1
')
            .replace(/\n/g, '
')
            .replace(/
<\/div>/g, '
');

        var emojioneImageType = emojione.imageType;
        emojione.imageType = 'png';
        content = emojione.unicodeToImage(content);
        emojione.imageType = emojioneImageType;

        this.editor.html('
' + content + '
');
        this.content = this.editor.html();
        this.trigger('emojioneArea.change change', [this.content]);
    }

    EmojioneArea.prototype.getText = function() {
        return this.editor.html()
            .replace(/]+)"[^>]+>/ig, '$1')
            .replace(/\n/g, '')
            .replace(/
]+)?>/ig, '\n')
            .replace(/(?:
]+)?>)+/ig, '
')
            .replace(/(?:<\/div>)+/ig, '
')
            .replace(/(?:
]+)?>)+/ig, '
')
            .replace(/(?:<\/p>)+/ig, '
')
            .replace(/\n
<\/div>/ig, '\n')
            .replace(/
<\/div>\n/ig, '\n')
            .replace(/(?:
)+<\/div>/ig, '\n')
            .replace(/([^\n])<\/div>
/ig, '$1\n')
            .replace(/(?:<\/div>)+/ig, '')
            .replace(/([^\n])
/ig, '$1\n')
            .replace(/\n
/ig, '\n')
            .replace(/
\n/ig, '\n\n')
            .replace(/<(?:[^>]+)?>/ig, '');
    }

    EmojioneArea.prototype.init = function() {
        this.type = this.element.is("INPUT") ? 'val' : 'text';

        var html = this.options.template
            .replace("<editor/>", '

')
            .replace("<button/>", '

')
            .replace("<panel>", '
').replace("</panel>", '
');

        $.each(["editorClassName", "buttonClassName", "panelClassName"], $.proxy(function(i, name) {
            html = html.replace("{{" + name + "}}", this.options[name]);
        }, this));

        html = $('
' + html + '
').addClass(this.options.className).attr("role", "application");

        this.editor = html.find("." + this.options.editorClassName).attr("contenteditable", "true");
        this.button = html.find("." + this.options.buttonClassName);
        this.panel  = html.find("." + this.options.panelClassName);

        $.each(["dir", "spellcheck", "autocomplete", "autocorrect", "autocapitalize"], $.proxy(function(i, name) {
            this.editor.attr(name, this.options[name]);
        }, this));

        this.attach(this.editor, "mousedown")
            .attach([this.editor, this.panel], "mouseup")
            .attach(this.editor, "focus", "emojioneArea.focus focus")
            .attach(this.editor, "blur", "emojioneArea.blur blur")
            .attach([this.editor, this.panel], "click")
            .attach([this.editor, this.panel], "keyup")
            .attach([this.editor, this.panel], "keydown")
            .attach(this.panel, "mousedown", "emojioneArea.panel.mousedown panel.mousedown mousedown")
            .attach(this.button, "emojioneArea.button.mousedown button.mousedown");

        this.on("emojioneArea.panel.mousedown", function(e) {
            e.preventDefault();
            return false;
        });

        this.on("emojioneArea.button.mousedown", function(e) {
            e.preventDefault();
            return false;
        });

        this.on("emojioneArea.change", $.proxy(function() {
            this.element[this.type](this.getText());
        }, this)).on("emojioneArea.focus", function() {
            html.addClass("focused");
        }).on("emojioneArea.blur", $.proxy(function() {
            html.removeClass("focused");
            var content = this.editor.html();
            if (this.content !== content) {
                this.content = content;
                this.trigger('emojioneArea.change change', [this.content]);
            }
        }, this));

        html.insertAfter(this.element);
        this.element.hide();
        this.setText(this.element[this.type]());
    };

    $.fn.emojioneArea = function(options) {
        return this.each(function(){
            if (!!this.emojioneArea) return this.emojioneArea;
            return this.emojioneArea = new EmojioneArea($(this), options);
        });
    };

}) (jQuery);

// smiles
// fa-smile-o, fa-clock-o, (fa-flag fa-flag-checkered fa-flag-o), fa-leaf, fa-track, fa-cutlery,  fa-trophy,  fa-gift, fa-heart,  fa-ellipsis-h<|endoftext|>


<commit_before>//
// Emulation of the Google Gadget JavaScript API.
//
// Author: Max Kellermann <mk@cm4all.com>
//

function _IG_Prefs(widget) {
    if (typeof(widget) == "object")
        this.widget = widget;
    else
        rootWidget.getWidget(widget);
    this.values = new Array();

    if (this.widget._query_string != null) {
        values = this.widget._query_string.split('&');
        for (i in values) {
            var key = values[i], value;
            i = key.indexOf('=');
            if (i >= 0) {
                value = key.substring(i + 1);
                key = key.substring(0, i);
            } else
                value = "";
            this.values[unescape(key)] = unescape(value);
        }
    }

    this.getInt = function(name) {
        return parseInt(this.getString(name));
    }

    this.getBool = function(name) {
        var value = this.getString(name);
        return value == "1" || value == "yes" || value == "true";
    }

    this.getString = function(name) {
        return this.values[name];
    }

    this.getArray = function(name) {
        var value = new Array();
        // XXX
        return value;
    }

    this.set = function(name, value) {
        this.values[name] = value;
        this.widget.get("?" + escape(name) + "=" + escape(value), null, true);
    }

    return this;
}

function _IG_Analytics(foo, bar) {
}

function urchinTracker(page) {
}

function _IG_FetchContent(url, callback) {
    var req = beng_proxy_request();
    if (req == null)
        return null;
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status >= 200 && req.status < 300) {
            callback(req.responseText);
        } else {
            callback(null);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

function _IG_FetchXmlContent(url, callback) {
    var req = beng_proxy_request();
    if (req == null)
        return null;
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status >= 200 && req.status < 300) {
            callback(req.responseXML);
        } else {
            callback(null);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

function _IG_SetTitle(title) {
}

function _IG_GetCachedUrl(url) {
    return url;
}

function _IG_GetImageUrl(url) {
    return url;
}

function _IG_AdjustIFrameHeight() {
}

function _IG_RegisterOnloadHandler(load) {
    beng_register_onload(load);
}

function _gel(id) {
    return document.getElementById(id);
}

function _gelstn(tagname) {
    return document.getElementsByTagName(tagname);
}
<commit_msg>added empty _IG_AddDOMEventHandler()<commit_after>//
// Emulation of the Google Gadget JavaScript API.
//
// Author: Max Kellermann <mk@cm4all.com>
//

function _IG_Prefs(widget) {
    if (typeof(widget) == "object")
        this.widget = widget;
    else
        rootWidget.getWidget(widget);
    this.values = new Array();

    if (this.widget._query_string != null) {
        values = this.widget._query_string.split('&');
        for (i in values) {
            var key = values[i], value;
            i = key.indexOf('=');
            if (i >= 0) {
                value = key.substring(i + 1);
                key = key.substring(0, i);
            } else
                value = "";
            this.values[unescape(key)] = unescape(value);
        }
    }

    this.getInt = function(name) {
        return parseInt(this.getString(name));
    }

    this.getBool = function(name) {
        var value = this.getString(name);
        return value == "1" || value == "yes" || value == "true";
    }

    this.getString = function(name) {
        return this.values[name];
    }

    this.getArray = function(name) {
        var value = new Array();
        // XXX
        return value;
    }

    this.set = function(name, value) {
        this.values[name] = value;
        this.widget.get("?" + escape(name) + "=" + escape(value), null, true);
    }

    return this;
}

function _IG_Analytics(foo, bar) {
}

function urchinTracker(page) {
}

function _IG_FetchContent(url, callback) {
    var req = beng_proxy_request();
    if (req == null)
        return null;
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status >= 200 && req.status < 300) {
            callback(req.responseText);
        } else {
            callback(null);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

function _IG_FetchXmlContent(url, callback) {
    var req = beng_proxy_request();
    if (req == null)
        return null;
    req.onreadystatechange = function() {
        if (req.readyState == 4 && req.status >= 200 && req.status < 300) {
            callback(req.responseXML);
        } else {
            callback(null);
        }
    }
    req.open("GET", url, true);
    req.send(null);
    return req;
}

function _IG_SetTitle(title) {
}

function _IG_GetCachedUrl(url) {
    return url;
}

function _IG_GetImageUrl(url) {
    return url;
}

function _IG_AdjustIFrameHeight() {
}

function _IG_RegisterOnloadHandler(load) {
    beng_register_onload(load);
}

function _IG_AddDOMEventHandler(window, event, handler) {
}

function _gel(id) {
    return document.getElementById(id);
}

function _gelstn(tagname) {
    return document.getElementsByTagName(tagname);
}
<|endoftext|>


<commit_before>var Google_Loader = (function (window, document) {

	that = this;

	Google_Loader = function (opts) {

        	this.current_loop = 0;

        	window.addEventListener('load', function() {
			FastClick.attach(document.body);
		}, false);

		this.fn_loading_screen_animation();

		$('.replay-message-button').on('click', this.fn_replay.bind(this));

	};

	Google_Loader.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        	fn_replay: function() {

        		$('.replay-message-button').removeClass('animated bounceIn');
        		$('.replay-message-button').addClass('animated rotateOut');

        		setTimeout(function() {
        			$('.replay-message-button').fadeOut(0);
        			$('.replay-message-button').removeClass('animated rotateOut');
        		}, 500);

        		loading_circles = '
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
';

        		$('#loading-container').fadeIn(0);
        		$('#loading-circles-container').fadeIn(0);
        		$('#loading-circles-container').html('');
        		$('#loading-circles-container').html(loading_circles);

        		this.fn_loading_screen_animation();

        	},

        	fn_loading_screen_animation: function(int_degrees) {

        		if (this.current_loop == 0) {

            			setTimeout(function() {
            				$('#loading-inner-circle-1').fadeIn(0);
            				$('#loading-inner-circle-1').addClass('animated bounceIn');
            			}, 1000);

            			setTimeout(function() {
            				$('#loading-inner-circle-2').fadeIn(0);
            				$('#loading-inner-circle-2').addClass('animated bounceIn');
            			}, 1500);

            			setTimeout(function() {
            				$('#loading-inner-circle-3').fadeIn(0);
            				$('#loading-inner-circle-3').addClass('animated bounceIn');
            			}, 2000);

       				setTimeout(function() {
                			$('#loading-inner-circle-4').fadeIn(0);
            				$('#loading-inner-circle-4').addClass('animated bounceIn');
            			}, 2500);

            		}

            		else {

            			$('#loading-circle-1').fadeIn(0);
            			$('#loading-circle-1').addClass('animated zoomIn');

            			setTimeout(function() {
            				$('#loading-circle-2').fadeIn(0);
            				$('#loading-circle-2').addClass('animated zoomIn');
            			}, 75);

            			setTimeout(function() {
            				$('#loading-circle-3').fadeIn(0);
            				$('#loading-circle-3').addClass('animated zoomIn');
            			}, 150);

            			setTimeout(function() {
            				$('#loading-circle-4').fadeIn(0);
            				$('#loading-circle-4').addClass('animated zoomIn');
            			}, 225);

            			setTimeout(function() {
            				$('#loading-circle-1').removeClass('animated zoomIn');
            				$('#loading-circle-2').removeClass('animated zoomIn');
            				$('#loading-circle-3').removeClass('animated zoomIn');
            				$('#loading-circle-4').removeClass('animated zoomIn');
            			}, 1000);

            			setTimeout(function() {
        				$('#loading-inner-circle-1').fadeIn(0);
        				$('#loading-inner-circle-1').addClass('animated bounceIn');
        			}, 1225);

           			setTimeout(function() {
        				$('#loading-inner-circle-2').fadeIn(0);
       					$('#loading-inner-circle-2').addClass('animated bounceIn');
        			}, 1725);

            			setTimeout(function() {
        				$('#loading-inner-circle-3').fadeIn(0);
        				$('#loading-inner-circle-3').addClass('animated bounceIn');
        			}, 2225);

            			setTimeout(function() {
        				$('#loading-inner-circle-4').fadeIn(0);
        				$('#loading-inner-circle-4').addClass('animated bounceIn');
        			}, 2725);

            		}

            		// spin the colored circles, while removing the small white ones
            		setTimeout(function() {
            			$('#loading-inner-circle-1').removeClass('animated bounceIn');
                		$('#loading-circle-1').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
               			setTimeout(function() {
                			$('#loading-inner-circle-1').fadeOut(30);
                			$('#loading-inner-circle-1').removeClass('animated bounceIn')
            			}, 260);
            		}, 3900);

            		setTimeout(function() {
            			$('#loading-inner-circle-2').removeClass('animated bounceIn');
               			$('#loading-circle-2').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
               			setTimeout(function() {
               				$('#loading-inner-circle-2').fadeOut(30);
            			}, 260);
        	 	}, 4400);

            		setTimeout(function() {
            			$('#loading-inner-circle-3').removeClass('animated bounceIn');
                		$('#loading-circle-3').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
               			setTimeout(function() {
               				$('#loading-inner-circle-3').fadeOut(30);
            			}, 260);
            		}, 4900);

            		setTimeout(function() {
            			$('#loading-inner-circle-4').removeClass('animated bounceIn');
               			$('#loading-circle-4').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
               			setTimeout(function() {
                			$('#loading-inner-circle-4').fadeOut(30);
            			}, 260);
            		}, 5400);

            		setTimeout(function() {
       				$('#loading-inner-circle-1').fadeIn(0);
       				$('#loading-inner-circle-1').addClass('animated bounceIn');
            		}, 6400);

        	 	setTimeout(function() {
       				$('#loading-inner-circle-2').fadeIn(0);
       				$('#loading-inner-circle-2').addClass('animated bounceIn');
            		}, 6900);

            		setTimeout(function() {
       				$('#loading-inner-circle-3').fadeIn(0);
       				$('#loading-inner-circle-3').addClass('animated bounceIn');
            		}, 7400);

        		setTimeout(function() {
       				$('#loading-inner-circle-4').fadeIn(0);
       				$('#loading-inner-circle-4').addClass('animated bounceIn');
            		}, 7900);

            		setTimeout(function() {
           			$('#loading-circle-1').addClass('animated bounceOut');
            			$('#loading-circle-2').addClass('animated bounceOut');
            			$('#loading-circle-3').addClass('animated bounceOut');
            			$('#loading-circle-4').addClass('animated bounceOut');
            		}, 8400);

            		setTimeout(function() {
        			$('.replay-message-button').fadeIn(0);
        			$('.replay-message-button').addClass('animated bounceIn');
       				$('#loading-container').fadeOut(500);
            		}, 8925);

            		this.current_loop += 1;

        	},

	};

	return Google_Loader;

})(window, document);
<commit_msg>Update google-loader.js<commit_after>var Google_Loader = (function (window, document) {

	that = this;

	Google_Loader = function (opts) {

        	this.current_loop = 0;

        	window.addEventListener('load', function() {
			FastClick.attach(document.body);
		}, false);

		this.fn_loading_screen_animation();

		$('.replay-message-button').on('click', this.fn_replay.bind(this));

	};

	Google_Loader.prototype = {

		// ------------------------------------------------------
		// Skimmin Core Functions
		// ------------------------------------------------------

        	fn_replay: function() {

        		$('.replay-message-button').removeClass('animated bounceIn');
        		$('.replay-message-button').addClass('animated rotateOut');

        		setTimeout(function() {
        			$('.replay-message-button').fadeOut(0);
        			$('.replay-message-button').removeClass('animated rotateOut');
        		}, 300);

        		loading_circles = '
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
' +
				'
' +
					'

' +
					'

' +
				'
';

        		$('#loading-container').fadeIn(0);
        		$('#loading-circles-container').fadeIn(0);
        		$('#loading-circles-container').html('');
        		$('#loading-circles-container').html(loading_circles);

        		this.fn_loading_screen_animation();

        	},

        	fn_loading_screen_animation: function(int_degrees) {

        		if (this.current_loop == 0) {

            			setTimeout(function() {
            				$('#loading-inner-circle-1').fadeIn(0);
            				$('#loading-inner-circle-1').addClass('animated bounceIn');
            			}, 1000);

            			setTimeout(function() {
            				$('#loading-inner-circle-2').fadeIn(0);
            				$('#loading-inner-circle-2').addClass('animated bounceIn');
            			}, 1500);

            			setTimeout(function() {
            				$('#loading-inner-circle-3').fadeIn(0);
            				$('#loading-inner-circle-3').addClass('animated bounceIn');
            			}, 2000);

       				setTimeout(function() {
                			$('#loading-inner-circle-4').fadeIn(0);
            				$('#loading-inner-circle-4').addClass('animated bounceIn');
            			}, 2500);

            		}

            		else {

            			$('#loading-circle-1').fadeIn(0);
            			$('#loading-circle-1').addClass('animated zoomIn');

            			setTimeout(function() {
            				$('#loading-circle-2').fadeIn(0);
            				$('#loading-circle-2').addClass('animated zoomIn');
            			}, 75);

            			setTimeout(function() {
            				$('#loading-circle-3').fadeIn(0);
            				$('#loading-circle-3').addClass('animated zoomIn');
            			}, 150);

            			setTimeout(function() {
            				$('#loading-circle-4').fadeIn(0);
            				$('#loading-circle-4').addClass('animated zoomIn');
            			}, 225);

            			setTimeout(function() {
            				$('#loading-circle-1').removeClass('animated zoomIn');
            				$('#loading-circle-2').removeClass('animated zoomIn');
            				$('#loading-circle-3').removeClass('animated zoomIn');
            				$('#loading-circle-4').removeClass('animated zoomIn');
            			}, 1000);

            			setTimeout(function() {
        				$('#loading-inner-circle-1').fadeIn(0);
        				$('#loading-inner-circle-1').addClass('animated bounceIn');
        			}, 1225);

           			setTimeout(function() {
        				$('#loading-inner-circle-2').fadeIn(0);
       					$('#loading-inner-circle-2').addClass('animated bounceIn');
        			}, 1725);

            			setTimeout(function() {
        				$('#loading-inner-circle-3').fadeIn(0);
        				$('#loading-inner-circle-3').addClass('animated bounceIn');
        			}, 2225);

            			setTimeout(function() {
        				$('#loading-inner-circle-4').fadeIn(0);
        				$('#loading-inner-circle-4').addClass('animated bounceIn');
        			}, 2725);

            		}

            		// spin the colored circles, while removing the small white ones
            		setTimeout(function() {
            			$('#loading-inner-circle-1').removeClass('animated bounceIn');
                		$('#loading-circle-1').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
               			setTimeout(function() {
                			$('#loading-inner-circle-1').fadeOut(30);
                			$('#loading-inner-circle-1').removeClass('animated bounceIn')
            			}, 260);
            		}, 3900);

            		setTimeout(function() {
            			$('#loading-inner-circle-2').removeClass('animated bounceIn');
               			$('#loading-circle-2').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
               			setTimeout(function() {
               				$('#loading-inner-circle-2').fadeOut(30);
            			}, 260);
        	 	}, 4400);

            		setTimeout(function() {
            			$('#loading-inner-circle-3').removeClass('animated bounceIn');
                		$('#loading-circle-3').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
               			setTimeout(function() {
               				$('#loading-inner-circle-3').fadeOut(30);
            			}, 260);
            		}, 4900);

            		setTimeout(function() {
            			$('#loading-inner-circle-4').removeClass('animated bounceIn');
               			$('#loading-circle-4').css('-webkit-transform', 'rotateY(-' + '180' + 'deg)');
               			setTimeout(function() {
                			$('#loading-inner-circle-4').fadeOut(30);
            			}, 260);
            		}, 5400);

            		setTimeout(function() {
       				$('#loading-inner-circle-1').fadeIn(0);
       				$('#loading-inner-circle-1').addClass('animated bounceIn');
            		}, 6400);

        	 	setTimeout(function() {
       				$('#loading-inner-circle-2').fadeIn(0);
       				$('#loading-inner-circle-2').addClass('animated bounceIn');
            		}, 6900);

            		setTimeout(function() {
       				$('#loading-inner-circle-3').fadeIn(0);
       				$('#loading-inner-circle-3').addClass('animated bounceIn');
            		}, 7400);

        		setTimeout(function() {
       				$('#loading-inner-circle-4').fadeIn(0);
       				$('#loading-inner-circle-4').addClass('animated bounceIn');
            		}, 7900);

            		setTimeout(function() {
           			$('#loading-circle-1').addClass('animated bounceOut');
            			$('#loading-circle-2').addClass('animated bounceOut');
            			$('#loading-circle-3').addClass('animated bounceOut');
            			$('#loading-circle-4').addClass('animated bounceOut');
            		}, 8400);

            		setTimeout(function() {
        			$('.replay-message-button').fadeIn(0);
        			$('.replay-message-button').addClass('animated bounceIn');
       				$('#loading-container').fadeOut(500);
            		}, 8925);

            		this.current_loop += 1;

        	},

	};

	return Google_Loader;

})(window, document);
<|endoftext|>