<commit_before>// ephemeral.js
// scene where glitchy controls thrive

var SCENE_HEIGHT = 1000;

// create scene, camera, one plane, light,
var camera, scene, renderer, deviceControls, ground;

function init() {
  var plane, light, groundTexture;

  camera = new THREE.PerspectiveCamera( 45, window.innerWidth /
      window.innerHeight, 1, 2000 );

	camera.position.set( 0, 200, 800 );

  deviceControls = new THREE.DeviceOrientationControls( camera );

	scene = new THREE.Scene();
  scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 );

  scene.add( new THREE.AmbientLight( 0x666666 ) );

  var light = new THREE.PointLight( 0xaaddaa, .5 );
  light.position.set( 50, 1200, -500 );
  scene.add( light );

  groundTexture = THREE.ImageUtils.loadTexture(
      "textures/moon.png" );

  // groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
  // groundTexture.repeat.set( 432, 432 );
  groundTexture.anisotropy = 16;

  var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff,
      specular: 0x111111, map: groundTexture } );

	ground = new THREE.Mesh( new THREE.PlaneBufferGeometry( 10000, 10000 ),
      groundMaterial );

	ground.position.y = 10;
	ground.rotation.x = -Math.PI / 2;
  camera.rotation.x = -Math.PI / 2;
	ground.receiveShadow = true;
	scene.add( ground );

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  startBalloons();
}

function animate() {

  requestAnimationFrame( animate );

  deviceControls.update();

  TWEEN.update();

  renderer.render( scene, camera );

}

function startBalloons () {
  setInterval(function() {

    if (balloons.length < 50) {
      makeBalloon({
        x: 2000 * Math.random() - 1000,
        y: 0, //-200,
        z: 2000 * Math.random() - 1000
      });

    } else {
      resetBalloon();
    }

  }, 500);
}

var balloons = [];

/*
 *  make new balloon
 *  setBalloon()
 */
function makeBalloon (pos) {
  // make sphere
  var geometry = new THREE.SphereGeometry(15, 10, 10)
  groundTexture = THREE.ImageUtils.loadTexture(
      "textures/moon.png" );
  // TODO: random color
  var material = new THREE.MeshPhongMaterial({
    color: 0xaff00,
    map: groundTexture
  })

  var mesh = new THREE.Mesh( geometry, material );

  mesh.position.set(pos.x, pos.y, pos.z);

  balloons.push(mesh);

  scene.add(mesh);

  // tween up to top position
  var target = {
    x: pos.x,
    y: SCENE_HEIGHT,
    z: pos.z
  };

  doTween(pos, target, mesh, TWEEN.Easing.Cubic.In, 25000)
}

var lastBalloonReset = 0;

function resetBalloon () {
  var b, pos, target;

  for (var i = lastBalloonReset; i < balloons.length; i++) {
    b = balloons[i];

    if (b.position.y === SCENE_HEIGHT) {
      target = {
        x: b.position.x,
        y: b.position.y,
        z: b.position.z
      };
      pos = {
        x: b.position.x,
        y: 0,
        z: b.position.z
      };

      doTween(pos, target, b, TWEEN.Easing.Cubic.In, 25000)
      break;
    }

    if (i + 1 === balloons.length) {
      lastBalloonReset = 0;
    }
  }
}

// animate item from start position, to target,
function doTween (position, target, obj, easing, time) {
  var tween = new TWEEN.Tween(position).to(target, time);

  tween.onUpdate(function(){
    obj.position.x = position.x;
    obj.position.y = position.y;
    obj.position.z = position.z;
  });

  tween.easing(easing);

  tween.start();
}

init();
animate();
<commit_msg>adding movement controls, still a bit iffy, might need to use velocity instead of exact position<commit_after>// ephemeral.js
// scene where glitchy controls thrive
var QUARTER_CIRCLE_RADIANS = 1.57079633; // Math.PI / 2
var SCENE_HEIGHT = 1000;

// create scene, camera, one plane, light,
var camera, scene, renderer, deviceControls, ground;

function init() {
  var plane, light, groundTexture;

  camera = new THREE.PerspectiveCamera( 45, window.innerWidth /
      window.innerHeight, 1, 2000 );

	camera.position.set( 0, 0, 0 );

  deviceControls = new THREE.DeviceOrientationControls( camera );

	scene = new THREE.Scene();
  scene.fog = new THREE.Fog( 0xcce0ff, 500, 10000 );

  scene.add( new THREE.AmbientLight( 0x666666 ) );

  var light = new THREE.PointLight( 0xaaddaa, .5 );
  light.position.set( 50, 1200, -500 );
  scene.add( light );

  groundTexture = THREE.ImageUtils.loadTexture(
      "textures/moon.png" );

  // groundTexture.wrapS = groundTexture.wrapT = THREE.RepeatWrapping;
  // groundTexture.repeat.set( 432, 432 );
  groundTexture.anisotropy = 16;

  var groundMaterial = new THREE.MeshPhongMaterial( { color: 0xffffff,
      specular: 0x111111, map: groundTexture } );

	ground = new THREE.Mesh( new THREE.PlaneBufferGeometry( 10000, 10000 ),
      groundMaterial );

	ground.position.y = -10;
	ground.rotation.x = -Math.PI / 2;
  camera.rotation.x = -Math.PI / 2;
	ground.receiveShadow = true;
	scene.add( ground );

  renderer = new THREE.WebGLRenderer();
  renderer.setPixelRatio( window.devicePixelRatio );
  renderer.setSize( window.innerWidth, window.innerHeight );
  document.body.appendChild( renderer.domElement );

  startBalloons();
  makeHUD();
}

function animate() {

  requestAnimationFrame( animate );

  deviceControls.update();

  TWEEN.update();

  renderer.render( scene, camera );

}

function startBalloons () {
  setInterval(function() {

    if (balloons.length < 50) {
      makeBalloon({
        x: 2000 * Math.random() - 1000,
        y: 0, //-200,
        z: 2000 * Math.random() - 1000
      });

    } else {
      resetBalloon();
    }

  }, 500);
}

var balloons = [];

/*
 *  make new balloon
 *  setBalloon()
 */
function makeBalloon (pos) {
  // make sphere
  var geometry = new THREE.SphereGeometry(15, 10, 10);

  var groundTexture = THREE.ImageUtils.loadTexture(
      "textures/moon.png" );

  // TODO: random color
  var material = new THREE.MeshPhongMaterial({
    color: 0xaff00,
    map: groundTexture
  });

  var mesh = new THREE.Mesh( geometry, material );

  mesh.position.set(pos.x, pos.y, pos.z);

  balloons.push(mesh);

  scene.add(mesh);

  // tween up to top position
  var target = {
    x: pos.x,
    y: SCENE_HEIGHT,
    z: pos.z
  };

  doTween(pos, target, mesh, TWEEN.Easing.Cubic.Out, 25000)
}

var lastBalloonReset = 0;

function resetBalloon () {
  var b, pos, target;

  for (var i = lastBalloonReset; i < balloons.length; i++) {
    b = balloons[i];

    if (b.position.y === SCENE_HEIGHT) {
      target = {
        x: b.position.x,
        y: b.position.y,
        z: b.position.z
      };
      pos = {
        x: b.position.x,
        y: 0,
        z: b.position.z
      };

      doTween(pos, target, b, TWEEN.Easing.Cubic.In, 25000)
      break;
    }

    if (i + 1 === balloons.length) {
      lastBalloonReset = 0;
    }
  }
}

// animate item from start position, to target,
function doTween (position, target, obj, easing, time) {
  var tween = new TWEEN.Tween(position).to(target, time);

  tween.onUpdate(function(){
    obj.position.x = position.x;
    obj.position.y = position.y;
    obj.position.z = position.z;
  });

  tween.easing(easing);

  tween.start();
}

function findNewPoint (x, y, angleRadians, distance) {
    var result = {};

    result.x = Math.round(Math.cos(angleRadians) * distance + x);
    result.z = Math.round(Math.sin(angleRadians) * distance + y);

    return result;
}

function addKeyHandler () {
  document.addEventListener( 'keyup', onKeyUp, false);
}

// TODO: start using velocities as demonstrated in example_3d_movement.html
function onKeyUp (event) {
  var increment = 50,
      angleY    = camera.rotation.y,
      x         = camera.position.x,
      z         = camera.position.z,
      distance;

  event.preventDefault();

  console.log(event.keyCode);

  switch(event.keyCode) {
    case 38: //Up
    angleY += QUARTER_CIRCLE_RADIANS
    distance = increment;
    break;

    case 40: //Down
    angleY -= QUARTER_CIRCLE_RADIANS
    distance = increment;
    break;

    case 39: //Right
    distance = -increment;
    break;

    case 37:// left
    distance = increment;
    break;
  }

  var newPoint = findNewPoint(x, z, angleY, distance);

  camera.position.x = newPoint.x;
  camera.position.z = newPoint.z;
}

function makeHUD () {
  var geometry = new THREE.SphereGeometry(15, 10, 10);

  var texture = THREE.ImageUtils.loadTexture(
      "textures/golfball.jpg" );

  var material = new THREE.MeshPhongMaterial({
    color: 0xaff00,
    map: texture
  });

  var huds = [];

  for (var i = 0; i < 6; i++) {
    huds[i] = new THREE.Mesh( geometry, material );
    camera.add(huds[i]);
  }

  var offset = 20;

  huds[0].position.z =  offset;
  huds[1].position.z = -offset;

  huds[2].position.y =  offset;
  huds[3].position.y = -offset;

  huds[4].position.x =  offset;
  huds[5].position.x = -offset;

  // huds.lookAt(camera.position);

  console.log("mesh", huds);
  console.log("camera", camera);
}

init();
animate();
addKeyHandler();
<|endoftext|>


<commit_before>ScriptLoader.load(
    'GridManager'
);
var FILE_COOKIE_NAME = 'NRGNFRPID';

Grid.implement({
    _popImage:function (path, tmplElement) {
        var popUpImg = new Element('img', {'src':'resizer/w298-h224/' + path, 'width':60, 'height':45, 'styles':{
            border:'1px solid gray',
            'border-radius':'10px',
            'z-index':100
        }, 'events':{
            'click':function (e) {
                this.destroy()
            },
            'mouseleave':function (e) {
                this.destroy();
            }
        }}).inject(document.body).position({'relativeTo':tmplElement, 'position':'center'}).set('morph', {duration:'short', transition:'linear'});
        var p = popUpImg.getPosition();
        popUpImg.morph({width:298, height:224, left:p.x - 112, top:p.y - 149});
    },

    iterateFields:function (record, fieldName, row) {
// Пропускаем невидимые поля.
        if (!this.metadata[fieldName].visible ||
            this.metadata[fieldName].type == 'hidden') return;
        var cell = new Element('td').injectInside(row);
        if (fieldName == 'upl_path') {
            cell.setStyles({ 'text-align':'center', 'vertical-align':'middle' });

            var image = new Element('img', {src:'about:blank'});
            var tmt, dimensions = {'width':40, 'height':40};
            var container = new Element('div', {'class':'thumb_container'}).inject(cell);

            switch (record['upl_internal_type']) {
                case 'folder':
                    image.setProperty('src', 'images/icons/icon_folder.gif');
                    break;
                case 'repo':
                    image.setProperty('src', 'images/icons/icon_repository.gif');
                    break;
                case 'folderup':
                    image.setProperty('src', 'images/icons/icon_folder_up.gif');
                    break;
                case 'video':
                case 'image':
                    dimensions = {'width':60, 'height':45};
                    image.setProperty('src', 'resizer/w60-h45/' + record[fieldName]).addEvents({
                        'error':function () {
                            image.setProperty('src', 'images/icons/icon_error_image.gif');
                            container.removeEvents('mouseenter').removeEvent('mouseleave');
                        }
                    }).setStyles({'border-radius':'5px', 'border':'1px solid transparent'});
                    container.addEvents({
                        'mouseenter':function (e) {
                            var el = $(e.target);
                            if (el.get('tag') != 'img') {
                                el = el.getElement('img');
                            }
                            el.setStyle('border', '1px solid gray');
                            tmt = this._popImage.delay(700, this, [record[fieldName], el])
                        }.bind(this),
                        'mouseleave':function (e) {
                            var el = $(e.target);
                            if (el.get('tag') != 'img') {
                                el = el.getElement('img');
                            }
                            el.setStyle('border', '1px solid transparent');
                            if (tmt) {
                                clearTimeout(tmt);
                            }
                        }
                    });

                    if (record['upl_internal_type'] == 'video') {
                        container.grab(new Element('div', {'class':'video_file'}));
                    }
                    break;
                default:
                    dimensions = {'width':39, 'height':48};
                    image.setProperty('src', 'images/icons/icon_undefined.gif');
                    break;
            }
            image.setProperties(dimensions).inject(container);
        }
        else if (fieldName == 'upl_properties') {
            cell.addClass('properties');
            var propsTable = new Element('tbody');
            cell.grab(new Element('table').grab(propsTable));
            if (!record['upl_internal_type'].test('folder')) {
                new Element('tr').inject(propsTable).adopt([
                    new Element('td', {'html':this.metadata['upl_mime_type'].title + ' :'}),
                    new Element('td', {'html':record['upl_mime_type']})
                ]
                );
                switch (record['upl_internal_type']) {
                    case 'video':
                        if (record['upl_duration'])
                            new Element('tr').inject(propsTable).adopt([
                                new Element('td', {'html':this.metadata['upl_duration'].title + ' :'}),
                                new Element('td', {'html':record['upl_duration']})
                            ]
                            );
                        break;
                    case 'image':
                        if (record['upl_width'])
                            new Element('tr').inject(propsTable).adopt([
                                new Element('td', {'html':this.metadata['upl_width'].title + ' :'}),
                                new Element('td', {'html':record['upl_width']})
                            ]
                            );
                        if (record['upl_height'])
                            new Element('tr').inject(propsTable).adopt([
                                new Element('td', {'html':this.metadata['upl_height'].title + ' :'}),
                                new Element('td', {'html':record['upl_height']})
                            ]
                            );
                        break;
                    default :
                        break;
                }
                new Element('tr').inject(propsTable).adopt([
                    new Element('td', {'html':this.metadata['upl_publication_date'].title + ' :'}),
                    new Element('td', {'html':record['upl_publication_date']})
                ]
                );
            }
        }
        else {
            var fieldValue = '';
            if (record[fieldName]) {
                var fieldValue = record[fieldName].clean();
            }
            if (fieldValue != '') cell.set('html', fieldValue);
            //if (fieldValue != '') cell.appendText(fieldValue);
            else cell.set('html', ' ');
        }
    }
});
var FileRepository = new Class({
    Extends:GridManager,
    initialize:function (element) {
        this.parent(element);
        this.currentPID = false;
    },
    onDoubleClick:function () {
        this.open();
    },
    onSelect:function () {
        var r = this.grid.getSelectedRecord(), control;
        this.toolbar.enableControls();
        var openBtn = this.toolbar.getControlById('open');
        switch (r.upl_internal_type) {
            case 'folder':
                if (openBtn)openBtn.enable();
                break;
            case 'folderup':
                this.toolbar.disableControls();
                if (openBtn)openBtn.enable();
                this.toolbar.getControlById('addDir').enable();
                this.toolbar.getControlById('add').enable()
                break;
            case 'repo':
                this.toolbar.disableControls();
                if (openBtn)openBtn.enable();
                break;
            default:
                //this.toolbar.getControlById('open').disable();
                break;
        }
    },
    processServerResponse:function (result) {

        if (!this.initialized) {
            this.grid.setMetadata(result.meta);
            this.initialized = true;
        }
        if (!result.data) {
            result.data = [];
        }
        if (this.currentPID)
            Cookie.write(FILE_COOKIE_NAME, this.currentPID, {path:new URI(Energine.base).get('directory'), duration:1});
        /*if (this.currentPID) {
         result.data.unshift({'upl_id':0, 'upl_internal_type':'folderup', 'upl_path':'', 'upl_pid':'', 'upl_title':'...'});
         }*/
        this.grid.setData(result.data);

        if (result.pager)
            this.pageList.build(result.pager.count, result.pager.current, result.pager.records);

        if (!this.grid.isEmpty()) {
            this.toolbar.enableControls();
            this.pageList.enable();
        }

        var controlsEnabledByDefault = ['add'];
        for (var i = 0, l = controlsEnabledByDefault.length; i < l; i++) {
            if (control = this.toolbar.getControlById(controlsEnabledByDefault[i])) control.enable();
        }

        this.grid.build();
        this.overlay.hide();
    },
    open:function () {
        var r = this.grid.getSelectedRecord();
        switch (r.upl_internal_type) {
            case 'repo':
            case 'folder':
                this.currentPID = r.upl_id;
                this.filter.remove();
                this.loadPage(1);
                break;
            case 'folderup':
                this.currentPID = r.upl_id;
                this.loadPage(1);
                break;
            default:
                ModalBox.setReturnValue(r);
                ModalBox.close();
                break;
        }
    },
    add:function () {
        var pid = this.grid.getSelectedRecord().upl_pid;
        if (pid) {
            pid += '/';
        }
        ModalBox.open({
            url:this.singlePath + pid + 'add/',
            onClose:this._processAfterCloseAction.bind(this)
        });
    },
    addDir:function () {
        var pid = this.grid.getSelectedRecord().upl_pid;
        if (pid) {
            pid += '/';
        }
        ModalBox.open({
            url:this.singlePath + pid + 'add-dir/',
            //onClose:this._processAfterCloseAction.bind(this)
            onClose:function (response) {
                if (response && response.result) {
                    this.currentPID = response.data;
                    this._processAfterCloseAction(response);
                }

            }.bind(this)
        });
    },
    uploadZip:function (data) {
        this.request(this.singlePath + 'upload-zip', 'PID=' + this.grid.getSelectedRecord().upl_pid + '&data=' + encodeURIComponent(data.result), function (response) {
            console.log(response)
        });
        //this.singlePath + 'upload-zip',
    },
    loadPage:function (pageNum) {
        this.pageList.disable();
        this.toolbar.disableControls();
        this.overlay.show();
        this.grid.clear();
        var level = '', cookiePID;

        if (this.currentPID === 0) {
            level = '';
        }
        else if (this.currentPID) {
            level = this.currentPID + '/';
        }
        else if (cookiePID = Cookie.read(FILE_COOKIE_NAME)) {
            this.currentPID = cookiePID;
            level = this.currentPID + '/';
        }

        var postBody = '', url = this.singlePath + level + 'get-data/' + 'page-' + pageNum + '/';
        //if (this.langId) postBody += 'languageID=' + this.langId + '&';
        postBody += this.filter.getValue();
        /*if (this.grid.sort.order) {
         url = this.singlePath + 'get-data/' + this.grid.sort.field + '-' +
         this.grid.sort.order + '/page-' + pageNum
         }*/
        this.request(url,
            postBody,
            this.processServerResponse.bind(this),
            null,
            this.processServerError.bind(this)
        );
    }
});
<commit_msg><commit_after>ScriptLoader.load(
    'GridManager'
);
var FILE_COOKIE_NAME = 'NRGNFRPID';

Grid.implement({
    _popImage:function (path, tmplElement) {
        var popUpImg = new Element('img', {'src':'resizer/w298-h224/' + path, 'width':60, 'height':45, 'styles':{
            border:'1px solid gray',
            'border-radius':'10px',
            'z-index':100
        }, 'events':{
            'click':function (e) {
                this.destroy()
            },
            'mouseleave':function (e) {
                this.destroy();
            }
        }}).inject(document.body).position({'relativeTo':tmplElement, 'position':'center'}).set('morph', {duration:'short', transition:'linear'});
        var p = popUpImg.getPosition();
        popUpImg.morph({width:298, height:224, left:p.x - 112, top:p.y - 149});
    },

    iterateFields:function (record, fieldName, row) {
// Пропускаем невидимые поля.
        if (!this.metadata[fieldName].visible ||
            this.metadata[fieldName].type == 'hidden') return;
        var cell = new Element('td').injectInside(row);
        if (fieldName == 'upl_path') {
            cell.setStyles({ 'text-align':'center', 'vertical-align':'middle' });

            var image = new Element('img', {src:'about:blank'});
            var tmt, dimensions = {'width':40, 'height':40};
            var container = new Element('div', {'class':'thumb_container'}).inject(cell);

            switch (record['upl_internal_type']) {
                case 'folder':
                    image.setProperty('src', 'images/icons/icon_folder.gif');
                    break;
                case 'repo':
                    image.setProperty('src', 'images/icons/icon_repository.gif');
                    break;
                case 'folderup':
                    image.setProperty('src', 'images/icons/icon_folder_up.gif');
                    break;
                case 'video':
                case 'image':
                    dimensions = {'width':60, 'height':45};
                    image.setProperty('src', 'resizer/w60-h45/' + record[fieldName]).addEvents({
                        'error':function () {
                            image.setProperty('src', 'images/icons/icon_error_image.gif');
                            container.removeEvents('mouseenter').removeEvent('mouseleave');
                        }
                    }).setStyles({'border-radius':'5px', 'border':'1px solid transparent'});
                    container.addEvents({
                        'mouseenter':function (e) {
                            var el = $(e.target);
                            if (el.get('tag') != 'img') {
                                el = el.getElement('img');
                            }
                            el.setStyle('border', '1px solid gray');
                            tmt = this._popImage.delay(700, this, [record[fieldName], el])
                        }.bind(this),
                        'mouseleave':function (e) {
                            var el = $(e.target);
                            if (el.get('tag') != 'img') {
                                el = el.getElement('img');
                            }
                            el.setStyle('border', '1px solid transparent');
                            if (tmt) {
                                clearTimeout(tmt);
                            }
                        }
                    });

                    if (record['upl_internal_type'] == 'video') {
                        container.grab(new Element('div', {'class':'video_file'}));
                    }
                    break;
                default:
                    dimensions = {'width':39, 'height':48};
                    image.setProperty('src', 'images/icons/icon_undefined.gif');
                    break;
            }
            image.setProperties(dimensions).inject(container);
        }
        else if (fieldName == 'upl_properties') {
            cell.addClass('properties');
            var propsTable = new Element('tbody');
            cell.grab(new Element('table').grab(propsTable));
            if (!record['upl_internal_type'].test('[folder|repo]')) {
                if (record['upl_mime_type'])
                    new Element('tr').inject(propsTable).adopt([
                        new Element('td', {'html':this.metadata['upl_mime_type'].title + ' :'}),
                        new Element('td', {'html':record['upl_mime_type']})
                    ]
                    );
                switch (record['upl_internal_type']) {
                    case 'video':
                        if (record['upl_duration'])
                            new Element('tr').inject(propsTable).adopt([
                                new Element('td', {'html':this.metadata['upl_duration'].title + ' :'}),
                                new Element('td', {'html':record['upl_duration']})
                            ]
                            );
                        break;
                    case 'image':
                        if (record['upl_width'])
                            new Element('tr').inject(propsTable).adopt([
                                new Element('td', {'html':this.metadata['upl_width'].title + ' :'}),
                                new Element('td', {'html':record['upl_width']})
                            ]
                            );
                        if (record['upl_height'])
                            new Element('tr').inject(propsTable).adopt([
                                new Element('td', {'html':this.metadata['upl_height'].title + ' :'}),
                                new Element('td', {'html':record['upl_height']})
                            ]
                            );
                        break;
                    default :
                        break;
                }
                new Element('tr').inject(propsTable).adopt([
                    new Element('td', {'html':this.metadata['upl_publication_date'].title + ' :'}),
                    new Element('td', {'html':record['upl_publication_date']})
                ]
                );
            }
        }
        else {
            var fieldValue = '';
            if (record[fieldName]) {
                var fieldValue = record[fieldName].clean();
            }
            if (fieldValue != '') cell.set('html', fieldValue);
            //if (fieldValue != '') cell.appendText(fieldValue);
            else cell.set('html', ' ');
        }
    }
});
var FileRepository = new Class({
    Extends:GridManager,
    initialize:function (element) {
        this.parent(element);
        this.currentPID = false;
    },
    onDoubleClick:function () {
        this.open();
    },
    onSelect:function () {
        var r = this.grid.getSelectedRecord(), control;
        this.toolbar.enableControls();
        var openBtn = this.toolbar.getControlById('open');
        switch (r.upl_internal_type) {
            case 'folder':
                if (openBtn)openBtn.enable();
                break;
            case 'folderup':
                this.toolbar.disableControls();
                if (openBtn)openBtn.enable();
                this.toolbar.getControlById('addDir').enable();
                this.toolbar.getControlById('add').enable()
                break;
            case 'repo':
                this.toolbar.disableControls();
                if (openBtn)openBtn.enable();
                break;
            default:
                //this.toolbar.getControlById('open').disable();
                break;
        }
    },
    processServerResponse:function (result) {

        if (!this.initialized) {
            this.grid.setMetadata(result.meta);
            this.initialized = true;
        }
        if (!result.data) {
            result.data = [];
        }
        if (this.currentPID)
            Cookie.write(FILE_COOKIE_NAME, this.currentPID, {path:new URI(Energine.base).get('directory'), duration:1});
        /*if (this.currentPID) {
         result.data.unshift({'upl_id':0, 'upl_internal_type':'folderup', 'upl_path':'', 'upl_pid':'', 'upl_title':'...'});
         }*/
        this.grid.setData(result.data);

        if (result.pager)
            this.pageList.build(result.pager.count, result.pager.current, result.pager.records);

        if (!this.grid.isEmpty()) {
            this.toolbar.enableControls();
            this.pageList.enable();
        }

        var controlsEnabledByDefault = ['add'];
        for (var i = 0, l = controlsEnabledByDefault.length; i < l; i++) {
            if (control = this.toolbar.getControlById(controlsEnabledByDefault[i])) control.enable();
        }

        this.grid.build();
        this.overlay.hide();
    },
    open:function () {
        var r = this.grid.getSelectedRecord();
        switch (r.upl_internal_type) {
            case 'repo':
            case 'folder':
                this.currentPID = r.upl_id;
                this.filter.remove();
                this.loadPage(1);
                break;
            case 'folderup':
                this.currentPID = r.upl_id;
                this.loadPage(1);
                break;
            default:
                ModalBox.setReturnValue(r);
                ModalBox.close();
                break;
        }
    },
    add:function () {
        var pid = this.grid.getSelectedRecord().upl_pid;
        if (pid) {
            pid += '/';
        }
        ModalBox.open({
            url:this.singlePath + pid + 'add/',
            onClose:this._processAfterCloseAction.bind(this)
        });
    },
    addDir:function () {
        var pid = this.grid.getSelectedRecord().upl_pid;
        if (pid) {
            pid += '/';
        }
        ModalBox.open({
            url:this.singlePath + pid + 'add-dir/',
            //onClose:this._processAfterCloseAction.bind(this)
            onClose:function (response) {
                if (response && response.result) {
                    this.currentPID = response.data;
                    this._processAfterCloseAction(response);
                }

            }.bind(this)
        });
    },
    uploadZip:function (data) {
        this.request(this.singlePath + 'upload-zip', 'PID=' + this.grid.getSelectedRecord().upl_pid + '&data=' + encodeURIComponent(data.result), function (response) {
            console.log(response)
        });
        //this.singlePath + 'upload-zip',
    },
    loadPage:function (pageNum) {
        this.pageList.disable();
        this.toolbar.disableControls();
        this.overlay.show();
        this.grid.clear();
        var level = '', cookiePID;

        if (this.currentPID === 0) {
            level = '';
        }
        else if (this.currentPID) {
            level = this.currentPID + '/';
        }
        else if (cookiePID = Cookie.read(FILE_COOKIE_NAME)) {
            this.currentPID = cookiePID;
            level = this.currentPID + '/';
        }

        var postBody = '', url = this.singlePath + level + 'get-data/' + 'page-' + pageNum + '/';
        //if (this.langId) postBody += 'languageID=' + this.langId + '&';
        postBody += this.filter.getValue();
        /*if (this.grid.sort.order) {
         url = this.singlePath + 'get-data/' + this.grid.sort.field + '-' +
         this.grid.sort.order + '/page-' + pageNum
         }*/
        this.request(url,
            postBody,
            this.processServerResponse.bind(this),
            null,
            this.processServerError.bind(this)
        );
    }
});
<|endoftext|>


<commit_before>"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var PriorityQueue = function () {
  function PriorityQueue() {
    _classCallCheck(this, PriorityQueue);

    this.data = [];
    this._highestPriority = Infinity;
    this._lowestPriority = 0;
  }

  _createClass(PriorityQueue, [{
    key: "enqueue",
    value: function enqueue(element) {
      this.data[this.data.length] = element;
      if (element.priority > this._lowestPriority) {
        this._lowestPriority = element.priority;
      }
    }
  }, {
    key: "dequeue",
    value: function dequeue() {
      if (!this.data.length) {
        return null;
      }
      var index = void 0;
      for (var i = 0; i < this.data.length; i++) {
        if (this.data[i].priority < this._highestPriority) {
          this._highestPriority = this.data[i].priority;
          index = i;
        }
      }
      return this.data.splice(index, 1);
    }
  }, {
    key: "front",
    value: function front() {
      if (!this.data.length) {
        return null;
      }
      var index = void 0;
      for (var i = 0; i < this.data.length; i++) {
        if (this.data[i].priority < this._highestPriority) {
          this._highestPriority = this.data[i].priority;
          index = i;
        }
      }
      return this.data[index];
    }
  }, {
    key: "back",
    value: function back() {
      if (!this.data.length) {
        return null;
      }
      var index = void 0;
      for (var i = 0; i < this.data.length; i++) {
        if (this.data[i].priority >= this._lowestPriority) {
          this._lowestPriority = this.data[i].priority;
          index = i;
        }
      }
      return this.data[index];
    }
  }, {
    key: "isEmpty",
    value: function isEmpty() {
      return this.data.length === 0;
    }
  }, {
    key: "length",
    value: function length() {
      return this.data.length;
    }
  }]);

  return PriorityQueue;
}();

exports.default = PriorityQueue;<commit_msg>Delete PriorityQueue.js<commit_after><|endoftext|>


<commit_before>(function (m, config, gettext, IssueUtils) {
  var bootstrapFormField = IssueUtils.bootstrapFormField;
  var services = m.request({
    method: 'GET',
    url: config.api_root + 'services.json',
    initialValue: [],
  });
  var map = null;

  function initiateSearch() {
    var params = {
      extensions: 'citysdk',
      page: state.page(),
    };
    if (state.search()) {
      params.search = state.search();
    }
    if (state.service()) {
      params.service_code = state.service();
    }
    if (state.bbox()) {
      params.bbox = state.bbox();  // already in string format
    }
    if (state.circle()) {
      Object.assign(params, state.circle()); // unpack lat/lng/radius into params
    }
    state.searching(true);
    m.request({
      method: 'GET',
      url: config.api_root + 'requests.json',
      data: params,
      initialValue: state.results(),  // Use the previous value while we wait
      background: true,
      extract: function (xhr) {
        var results = JSON.parse(xhr.responseText);
        return {
          results: results,
          pageCount: xhr.getResponseHeader('X-Page-Count'),
          resultCount: xhr.getResponseHeader('X-Result-Count'),
        };
      },
      deserialize: function (value) {
        return value;  // already handled in extract
      },
    }).then(function (res) {
      state.searching(false);
      state.results(res);
      m.redraw(true);
    });
  }

  var initiateNewSearchSoon = IssueUtils.debounce(function () {
    state.page(1);
    initiateSearch();
  }, 150);

  var state = {
    search: IssueUtils.observeProp(m.prop(''), initiateNewSearchSoon),
    service: IssueUtils.observeProp(m.prop(''), initiateNewSearchSoon),
    bbox: IssueUtils.observeProp(m.prop(null), initiateNewSearchSoon),
    circle: IssueUtils.observeProp(m.prop(null), initiateNewSearchSoon),
    page: IssueUtils.observeProp(m.prop(1), initiateSearch),
    searching: m.prop(false),
    results: m.prop(null),
  };

  var getServiceSelectOptions = IssueUtils.purify(function (serviceList) {
    return [{value: '', text: gettext('any service')}].concat(serviceList.map(function (s) {
      return {value: s.service_code, text: s.service_name || s.service_code};
    })).map(function (opt) {
      return m('option', {value: opt.value, key: opt.value}, opt.text);
    });
  }, function () {
    return services();
  });

  function getBaseFilterRow() {
    return m('.row', [
      m('.col-md-12', bootstrapFormField({
        type: 'search',
        id: 'search',
        bind: state.search,
        label: gettext('Search for issues'),
        placeholder: gettext('Search for text...'),
      })),
      m('.col-md-12', bootstrapFormField({
        tag: 'select',
        id: 'service',
        bind: state.service,
        label: gettext('Select a service'),
        children: getServiceSelectOptions(),
      })),
    ]);
  }

  function getGeoFilterPanel() {
    return m('div', [
      m('.btn-group', [
        m('a.btn.btn-default', {
          href: '#',
          onclick: function () {
            map.startLittlePen('box');
          },
        }, gettext('Search by box')),
        m('a.btn.btn-default', {
          href: '#',
          onclick: function () {
            map.startLittlePen('circle');
          },
        }, gettext('Search by circle')),
        m('a.btn.btn-default', {
          href: '#',
          onclick: function () {
            map.clearLittlePen();
            state.bbox(null);
            state.circle(null);
          },
        }, gettext('Clear search')),
      ]),
      m('div', {
        config: IssueUtils.getLeafletSetup(function (context) {
          map = context.map;

          map.on('littlePenSelectBox', function (args) {
            state.circle(null);
            state.bbox([
              args.bounds.getSouth(),
              args.bounds.getWest(),
              args.bounds.getNorth(),
              args.bounds.getEast(),
            ].join(','));
          });
          map.on('littlePenSelectCircle', function (args) {
            state.bbox(null);
            state.circle({
              lat: args.center.lat,
              long: args.center.lng,
              radius: args.radius,
            });
          });
        }),
      }),
    ]);
  }

  function tryLocalizeDateTime(val) {
    try {
      return new Date(val).toLocaleString();
    } catch (e) {
      return val;
    }
  }

  function renderResult(result) {
    var ea = result.extended_attributes || {};
    return m('div.result', [
      m('div.row', [
        m('div.col-md-8', [
          (ea.title ? m('h2', ea.title) : null),
          m('p', result.description),
          (result.status_notes ? m('blockquote', [
            result.status_notes,
            (result.agency_responsible ? m('footer', result.agency_responsible) : null),
          ]) : null),
          (result.address ? m('.text-muted', result.address) : null),
        ]),
        m('div.col-md-4', [
          gettext('Sent ') + tryLocalizeDateTime(result.requested_datetime),
          gettext('Updated ') + tryLocalizeDateTime(result.updated_datetime),
          gettext('Status ') + result.status,
        ].map(function (t) {
          return (t ? m('div', t) : null);
        })),
      ]),
      m('hr'),
    ]);
  }

  function getPaginator(results, id) {
    if (results.pageCount <= 1) return;
    var paginator = results._mithril_paginator;
    if (!paginator) {
      var range = [];
      for (var page = 1; page <= parseInt(results.pageCount); page++) {
        range.push(page);
      }
      paginator = m('ul.pagination', {id: id}, range.map(function (page) {
        return m(
          'li' + (state.page() === page ? '.active' : ''),
          m('a', {
            href: '#' + id,
            onclick: function () {
              results._mithril_paginator = null; // Uncache
              state.page(page);
            },
          }, page)
        );
      }));
      results._mithril_paginator = paginator;
    }
    return paginator;
  }

  function getResults() {
    var results = state.results();
    if (!results) {
      return null;
    }
    return m('div.results-container', [
      m('nav', getPaginator(results, 'top-nav')),
      (results.results || []).map(function (result) {
        return (result._mithril || (result._mithril = renderResult(result)));
      }),
      m('nav', getPaginator(results, 'btm-nav')),
    ]);
  }

  function view() {
    return m('div', [
      m('.well', [
        m('.row', [
          m('.col-md-4', getBaseFilterRow()),
          m('.col-md-8', getGeoFilterPanel()),
        ]),
      ]),
      getResults(),
    ]);
  }

  m.mount(document.getElementById('browse-app-container'), {view: view});
  initiateSearch();
}(window.m, window.config, window.gettext, window.IssueUtils));
<commit_msg>Make the simple UI pass bbox coordinates in the OSM order (as changed in 8846578)<commit_after>(function (m, config, gettext, IssueUtils) {
  var bootstrapFormField = IssueUtils.bootstrapFormField;
  var services = m.request({
    method: 'GET',
    url: config.api_root + 'services.json',
    initialValue: [],
  });
  var map = null;

  function initiateSearch() {
    var params = {
      extensions: 'citysdk',
      page: state.page(),
    };
    if (state.search()) {
      params.search = state.search();
    }
    if (state.service()) {
      params.service_code = state.service();
    }
    if (state.bbox()) {
      params.bbox = state.bbox();  // already in string format
    }
    if (state.circle()) {
      Object.assign(params, state.circle()); // unpack lat/lng/radius into params
    }
    state.searching(true);
    m.request({
      method: 'GET',
      url: config.api_root + 'requests.json',
      data: params,
      initialValue: state.results(),  // Use the previous value while we wait
      background: true,
      extract: function (xhr) {
        var results = JSON.parse(xhr.responseText);
        return {
          results: results,
          pageCount: xhr.getResponseHeader('X-Page-Count'),
          resultCount: xhr.getResponseHeader('X-Result-Count'),
        };
      },
      deserialize: function (value) {
        return value;  // already handled in extract
      },
    }).then(function (res) {
      state.searching(false);
      state.results(res);
      m.redraw(true);
    });
  }

  var initiateNewSearchSoon = IssueUtils.debounce(function () {
    state.page(1);
    initiateSearch();
  }, 150);

  var state = {
    search: IssueUtils.observeProp(m.prop(''), initiateNewSearchSoon),
    service: IssueUtils.observeProp(m.prop(''), initiateNewSearchSoon),
    bbox: IssueUtils.observeProp(m.prop(null), initiateNewSearchSoon),
    circle: IssueUtils.observeProp(m.prop(null), initiateNewSearchSoon),
    page: IssueUtils.observeProp(m.prop(1), initiateSearch),
    searching: m.prop(false),
    results: m.prop(null),
  };

  var getServiceSelectOptions = IssueUtils.purify(function (serviceList) {
    return [{value: '', text: gettext('any service')}].concat(serviceList.map(function (s) {
      return {value: s.service_code, text: s.service_name || s.service_code};
    })).map(function (opt) {
      return m('option', {value: opt.value, key: opt.value}, opt.text);
    });
  }, function () {
    return services();
  });

  function getBaseFilterRow() {
    return m('.row', [
      m('.col-md-12', bootstrapFormField({
        type: 'search',
        id: 'search',
        bind: state.search,
        label: gettext('Search for issues'),
        placeholder: gettext('Search for text...'),
      })),
      m('.col-md-12', bootstrapFormField({
        tag: 'select',
        id: 'service',
        bind: state.service,
        label: gettext('Select a service'),
        children: getServiceSelectOptions(),
      })),
    ]);
  }

  function getGeoFilterPanel() {
    return m('div', [
      m('.btn-group', [
        m('a.btn.btn-default', {
          href: '#',
          onclick: function () {
            map.startLittlePen('box');
          },
        }, gettext('Search by box')),
        m('a.btn.btn-default', {
          href: '#',
          onclick: function () {
            map.startLittlePen('circle');
          },
        }, gettext('Search by circle')),
        m('a.btn.btn-default', {
          href: '#',
          onclick: function () {
            map.clearLittlePen();
            state.bbox(null);
            state.circle(null);
          },
        }, gettext('Clear search')),
      ]),
      m('div', {
        config: IssueUtils.getLeafletSetup(function (context) {
          map = context.map;

          map.on('littlePenSelectBox', function (args) {
            state.circle(null);
            state.bbox(args.bounds.toBBoxString());
          });
          map.on('littlePenSelectCircle', function (args) {
            state.bbox(null);
            state.circle({
              lat: args.center.lat,
              long: args.center.lng,
              radius: args.radius,
            });
          });
        }),
      }),
    ]);
  }

  function tryLocalizeDateTime(val) {
    try {
      return new Date(val).toLocaleString();
    } catch (e) {
      return val;
    }
  }

  function renderResult(result) {
    var ea = result.extended_attributes || {};
    return m('div.result', [
      m('div.row', [
        m('div.col-md-8', [
          (ea.title ? m('h2', ea.title) : null),
          m('p', result.description),
          (result.status_notes ? m('blockquote', [
            result.status_notes,
            (result.agency_responsible ? m('footer', result.agency_responsible) : null),
          ]) : null),
          (result.address ? m('.text-muted', result.address) : null),
        ]),
        m('div.col-md-4', [
          gettext('Sent ') + tryLocalizeDateTime(result.requested_datetime),
          gettext('Updated ') + tryLocalizeDateTime(result.updated_datetime),
          gettext('Status ') + result.status,
        ].map(function (t) {
          return (t ? m('div', t) : null);
        })),
      ]),
      m('hr'),
    ]);
  }

  function getPaginator(results, id) {
    if (results.pageCount <= 1) return;
    var paginator = results._mithril_paginator;
    if (!paginator) {
      var range = [];
      for (var page = 1; page <= parseInt(results.pageCount); page++) {
        range.push(page);
      }
      paginator = m('ul.pagination', {id: id}, range.map(function (page) {
        return m(
          'li' + (state.page() === page ? '.active' : ''),
          m('a', {
            href: '#' + id,
            onclick: function () {
              results._mithril_paginator = null; // Uncache
              state.page(page);
            },
          }, page)
        );
      }));
      results._mithril_paginator = paginator;
    }
    return paginator;
  }

  function getResults() {
    var results = state.results();
    if (!results) {
      return null;
    }
    return m('div.results-container', [
      m('nav', getPaginator(results, 'top-nav')),
      (results.results || []).map(function (result) {
        return (result._mithril || (result._mithril = renderResult(result)));
      }),
      m('nav', getPaginator(results, 'btm-nav')),
    ]);
  }

  function view() {
    return m('div', [
      m('.well', [
        m('.row', [
          m('.col-md-4', getBaseFilterRow()),
          m('.col-md-8', getGeoFilterPanel()),
        ]),
      ]),
      getResults(),
    ]);
  }

  m.mount(document.getElementById('browse-app-container'), {view: view});
  initiateSearch();
}(window.m, window.config, window.gettext, window.IssueUtils));
<|endoftext|>


<commit_before>'use strict';

module.exports = function(config) {
    if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
        console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
        process.exit(1);
    }

    var customLaunchers = {
        sl_chrome: {
            base: 'SauceLabs',
            browserName: 'chrome',
            platform: 'Windows 7',
            version: '35'
        },

        sl_firefox: {
            base: 'SauceLabs',
            browserName: 'firefox',
            version: '30'
        },

        sl_ios_safari: {
            base: 'SauceLabs',
            browserName: 'iphone',
            platform: 'OS X 10.9',
            version: '7.1'
        },

        sl_ie_11: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 8.1',
            version: '11'
        }
    };

    config.set({
        sauceLabs: {
            testName: 'lory Browser Tests'
        },

        customLaunchers: customLaunchers,
        browsers: Object.keys(customLaunchers),
        reporters: ['dots', 'saucelabs'],

        frameworks: [
            'mocha',
            'chai',
            'fixture'
        ],

       files: [
            'dist/lory.js',
            'test/lory.test.js',
            'demo/app.css',

            {
                pattern: 'test/*.html'
            }
        ],

        plugins: [
            'karma-mocha',
            'karma-mocha-reporter',
            'karma-chai',
            'karma-fixture',
            'karma-chrome-launcher',
            'karma-phantomjs-launcher',
            'karma-ie-launcher',
            'karma-opera-launcher',
            'karma-firefox-launcher',
            'karma-safari-launcher',
            'karma-html2js-preprocessor'
        ],

        preprocessors: {
            'test/*.html': ['html2js']
        },

        singleRun: true
    });
};
<commit_msg>fix(travis): try fix saucelabs.conf<commit_after>'use strict';

module.exports = function(config) {
    if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
        console.log('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.');
        process.exit(1);
    }

    var customLaunchers = {
        sauceLabsInternetExplorer9: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 7',
            version: '9.0'
        },
        sauceLabsInternetExplorer10: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 7',
            version: '10.0'
        },
        sauceLabsInternetExplorer11: {
            base: 'SauceLabs',
            browserName: 'internet explorer',
            platform: 'Windows 7',
            version: '11.0'
        },
        sauceLabsChrome: {
            base: 'SauceLabs',
            browserName: 'chrome',
            platform: 'Linux',
            version: '39.0'
        },
        sauceLabsFirefox: {
            base: 'SauceLabs',
            browserName: 'firefox',
            platform: 'Linux',
            version: '34.0'
        },
        sauceLabsSafari7: {
            base: 'SauceLabs',
            browserName: 'safari',
            platform: 'Mac 10.9',
            version: '7.0'
        },
        sauceLabsSafari8: {
            base: 'SauceLabs',
            browserName: 'safari',
            platform: 'Mac 10.10',
            version: '8.0'
        }
    };

    config.set({
        sauceLabs: {
            testName: 'lory Browser Tests',
            connectOptions: {
                port: 5757
            }
        },

        customLaunchers: customLaunchers,
        browsers: Object.keys(customLaunchers),
        reporters: ['dots', 'saucelabs'],

        frameworks: [
            'mocha',
            'chai',
            'fixture'
        ],

       files: [
            'dist/lory.js',
            'test/lory.test.js',
            'demo/app.css',

            {
                pattern: 'test/*.html'
            }
        ],

        plugins: [
            'karma-mocha',
            'karma-mocha-reporter',
            'karma-chai',
            'karma-fixture',
            'karma-sauce-launcher',
            'karma-html2js-preprocessor'
        ],

        preprocessors: {
            'test/*.html': ['html2js']
        },

        singleRun: true
    });
};
<|endoftext|>


<commit_before>var Bell 	= require("bell");
var Config 	= require("../config");
var Jobs 	= require("../models/jobs");
var Users 	= require("../models/users");
var Chat  	= require("../models/chat");
var Photos 	= require("../models/photos");
var Aws 	= require('aws-sdk');

module.exports = {

//To serve public files, css, lib, etc
	serveFile: {
		auth: false,
		handler: {
			directory: {
				path: "../public"
			}
		}
	},

	home: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.redirect("/dashboard");
			} else {
				reply.view("home");
			}
		}
	},

	signupSocial: {
			auth: {
				mode: "optional"
			},
		handler: function(request, reply) {
				reply.view("signupSocial");
		}
	},

	facebook: {
		auth: {
			strategy: "facebook"
			},
		handler: function(request, reply) {

			var fb = request.auth.credentials.profile;

			var profile;

			//Find user if exist, add user if they are a new user
			Users.getUser(fb.id, function(err, data) {

				console.log("Checking if user exists");

				if(data === null) {

					Users.addUser(profile, function(err, data){

						profile = {
							auth: "Facebook",
							id: fb.id,
							username: fb.username,
							displayName: fb.displayName,
							firstName: fb.name.first,
							lastName: fb.name.last,
							email: fb.email,
							link: fb.raw.link,
							picture: ('https://graph.facebook.com/' + fb.id + '/picture?width=300&height=300'),
							gender: fb.raw.gender,
							website: "",
							usertype: "nouser",
							talkingTo: "noone"
						};

						request.auth.session.set(profile);
						console.log("User added to database");
						reply.redirect("/signup/iam");
					});

				} else {

					console.log("Found user in database");

					profile = {
						auth: data.auth,
						id: data.id,
						username: data.userName,
						displayName: data.displayName,
						firstName: data.firstName,
						lastName: data.lastName,
						email: data.email,
						link: data.link,
						picture: data.picture,
						gender: data.gender,
						website: data.website,
						usertype: data.usertype,
						talkingTo: "noone"
					};

					request.auth.session.set(profile);
					reply.redirect("/dashboard");

				}
			});

		}
	},

	google: {
		auth: {
			strategy: "google"
			},
		handler: function(request, reply) {

			var g = request.auth.credentials.profile;

			//Setup session with no usertype default
			var profile;

			//Find user if exist, add user if they are a new user
			Users.getUser(g.id, function(err, data) {

				console.log("Checking if user exists");

				if(data === null) {

					Users.addUser(profile, function(err, data){

						profile = {
							auth: "Google",
							id: g.id,
							username: g.username,
							displayName: g.displayName,
							firstName: g.name.first,
							lastName: g.name.last,
							email: g.email,
							link: g.raw.link,
							picture: g.raw.picture,
							gender: g.raw.gender,
							website: "",
							usertype: "nouser",
							talkingTo: "noone"
						};

						request.auth.session.set(profile);
						console.log("User added to database");
						reply.redirect("/signup/iam");
					});

				} else {

					profile = {
						auth: data.auth,
						id: data.id,
						username: data.userName,
						displayName: data.displayName,
						firstName: data.firstName,
						lastName: data.lastName,
						email: data.email,
						link: data.link,
						picture: data.picture,
						gender: data.gender,
						website: data.website,
						usertype: data.usertype,
						talkingTo: "noone"
					};

					request.auth.session.set(profile);
					console.log("found user in database");
					reply.redirect("/dashboard");

				}
			});

		}
	},

	signupIam: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			if(request.auth.isAuthenticated) {
				reply.view("signupIam");
			} else {
				reply.redirect("/");
			}
		}
	},

	signupPhotographer: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			//Set usertype session and update to database
			request.auth.session.set("usertype", "photographer");
			var id = request.auth.credentials.id;
			var update = {"usertype": "photographer"};

			Users.updateUser(id, update, function(err, data){
				reply.redirect("/dashboard");
			});
		}
	},

	signupClient: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			//Set usertype session and update to database
			request.auth.session.set("usertype", "client");
			var profile = request.auth.credentials;
			var update = {"usertype": "client"};

			Users.updateUser(profile.id, update, function(err, data){
				reply.redirect("/dashboard");
			});
		}
	},

	dashboard: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			console.log(request.auth.credentials);

			if(request.auth.isAuthenticated) {

				Jobs.getAllJobs(function(err, data) {
					reply.view("dashboard", {jobs: data});
				});
			} else {
				reply.redirect("/");
			}
		}
	},

	profile: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				var profile = request.auth.credentials;

				Photos.findGallery(profile.id, function(err, data){

					if(data === null) {

						reply.view("profile", {profile: profile});
					} else {

						var photos = data.photos;

						reply.view("profile", {profile: profile, photos: photos});
					}

				});

			} else {

				reply.redirect("/");
			}
		}
	},

	profileEdit: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			var profile = request.auth.credentials;
			reply.view("profileEdit", {profile: profile});
		}
	},

	profileEditP: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var update = request.payload;
			console.log(update);

			profile.firstName = update.firstName;
			profile.lastName = update.lastName;
			profile.website = update.website;

			request.auth.session.set(profile);
			Users.updateUser(profile.id, update, function(err, data) {
				reply.redirect("/profile");
			});

		}
	},

	photoDelete: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var id = request.auth.credentials.id;
			var url = Object.keys(request.payload)[0];
			var file = url.split('/').slice(4)[0];

			Aws.config.update({accessKeyId: Config.s3.key, secretAccessKey: Config.s3.secret});
			var s3 = new Aws.S3();
			var params = {
			  Bucket: Config.s3.bucket,
			  Key: id + "/" + file,
			};
			s3.deleteObject(params, function(err, data) {

			  	if (err) {
			  		console.log("Error deleting from S3", err, err.stack);
			  	} else{
			  		console.log("Deleted from S3");
			  	}
			});

			Photos.deleteURL(id, request.payload, function(err, data) {
				reply.redirect("/profile");
			});
		}
	},

	newJobForm: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.view("newJob");
			} else {
				reply.redirect("/");
			}
		}
	},

	newJobPost: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {

			var user_id = request.auth.credentials.id;

			var new_job = {
				user: user_id,
				dateAdded: new Date(),
				postingAs: request.payload.postingAs,
				eventName: request.payload.eventName,
				dateTime: request.payload.dateTime,
				jobDuration: request.payload.jobDuration,
				location: request.payload.location,
				description: request.payload.description,
				useOfPhotos: request.payload.useOfPhotos,
				dateRequired: request.payload.dateRequired,
				noOfPhotographers: request.payload.noOfPhotographers
			};

			Jobs.newjob(new_job, function(err, data) {
				reply.redirect("/dashboard");
			});

			} else {
				reply.redirect("/");
			}

		}
	},

	upload: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply.view("upload");
		}
	},

	signS3: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var randomKey = Math.floor((Math.random() * 1000) + 1);
			//S3 setup
			Aws.config.update({accessKeyId: Config.s3.key, secretAccessKey: Config.s3.secret});
			var s3 = new Aws.S3();
			var s3_params = {
			    Bucket: Config.s3.bucket,
			    Key: request.auth.credentials.id + "/" + randomKey + "_" + request.query.file_name,
			    Expires: 60,
			    ContentType: request.query.file_type,
			    ACL: Config.s3.acl
			};
			// request.query.file_type (type of file you want to upload)

			s3.getSignedUrl('putObject', s3_params, function(err, data){
			    if(err){
			        console.log(err);
			    }
			    else{
			        var return_data = {
			            signed_request: data,
			            url: 'https://'+Config.s3.bucket+'.s3.amazonaws.com/'+request.auth.credentials.id+'/'+ randomKey + "_" + request.query.file_name
			        };
			        reply(JSON.stringify(return_data));
			    }
			});
		}
	},

	submitForm: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			console.log(request.payload);

			var id = request.auth.credentials.id;
			var update = { $push: {"photos": {
				"title": request.payload.title,
				"url": request.payload.photo_url,
			}}};

			Photos.findGallery(id, function(err, data) {
				if(data === null) {
					var object = {"user": id};
					Photos.newGallery(object, function(err, data) {
						Photos.newPhoto(id, update, function(err, data) {
							reply.redirect("/profile");
						});
					});
				} else {
					Photos.newPhoto(id, update, function(err, data) {
						reply.redirect("/profile");
					});
				}
			});

		}
	},

	users: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var myid = request.auth.credentials.id;

			Users.getAllUsers(function(err, data) {
				reply.view("users", {users: data, myid: myid});
			});
		}
	},

	chatWith: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = Object.keys(request.payload)[0];
			var users = {"users": [myid, chatWith]};

			profile.talkingTo = chatWith;
			request.auth.session.set(profile);

			Chat.findChat(myid, chatWith, function(err, data) {
				if(data.length === 0) {

					console.log("New chat");
					Chat.newChat(users, function(err, data){
						reply.redirect("/chat/" + chatWith);
					});

				} else {

					console.log("Chat exists");
					reply.redirect("/chat/" + chatWith);
				}
			});

		}
	},

	chat: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = profile.talkingTo;

			Chat.findChat(myid, chatWith, function(err, data) {
				console.log(data[0]);

				Users.getUser(chatWith, function(err, result){
					console.log(result);
					reply.view("chat", {data: data[0], profile: profile, talkingTo: result});
				});
			});

		}
	},

	chatSubmit: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = profile.talkingTo;

			var chat = { $push: {"chat": {
				"sender": myid,
				"name": profile.firstName + " " + profile.lastName,
				"message": request.payload.chat,
				"time": Date()
			}}};

			Chat.addChat(myid, chatWith, chat, function(err, data) {
				reply.redirect("/chat/"+ profile.talkingTo);
			});
		}
	},

	help: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply("Help");
		}
	},

	logout: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			request.auth.session.clear();
			reply.redirect("/");
		}
	}

};<commit_msg>fix broken delete<commit_after>var Bell 	= require("bell");
var Config 	= require("../config");
var Jobs 	= require("../models/jobs");
var Users 	= require("../models/users");
var Chat  	= require("../models/chat");
var Photos 	= require("../models/photos");
var Aws 	= require('aws-sdk');

module.exports = {

//To serve public files, css, lib, etc
	serveFile: {
		auth: false,
		handler: {
			directory: {
				path: "../public"
			}
		}
	},

	home: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.redirect("/dashboard");
			} else {
				reply.view("home");
			}
		}
	},

	signupSocial: {
			auth: {
				mode: "optional"
			},
		handler: function(request, reply) {
				reply.view("signupSocial");
		}
	},

	facebook: {
		auth: {
			strategy: "facebook"
			},
		handler: function(request, reply) {

			var fb = request.auth.credentials.profile;

			var profile;

			//Find user if exist, add user if they are a new user
			Users.getUser(fb.id, function(err, data) {

				console.log("Checking if user exists");

				if(data === null) {

					Users.addUser(profile, function(err, data){

						profile = {
							auth: "Facebook",
							id: fb.id,
							username: fb.username,
							displayName: fb.displayName,
							firstName: fb.name.first,
							lastName: fb.name.last,
							email: fb.email,
							link: fb.raw.link,
							picture: ('https://graph.facebook.com/' + fb.id + '/picture?width=300&height=300'),
							gender: fb.raw.gender,
							website: "",
							usertype: "nouser",
							talkingTo: "noone"
						};

						request.auth.session.set(profile);
						console.log("User added to database");
						reply.redirect("/signup/iam");
					});

				} else {

					console.log("Found user in database");

					profile = {
						auth: data.auth,
						id: data.id,
						username: data.userName,
						displayName: data.displayName,
						firstName: data.firstName,
						lastName: data.lastName,
						email: data.email,
						link: data.link,
						picture: data.picture,
						gender: data.gender,
						website: data.website,
						usertype: data.usertype,
						talkingTo: "noone"
					};

					request.auth.session.set(profile);
					reply.redirect("/dashboard");

				}
			});

		}
	},

	google: {
		auth: {
			strategy: "google"
			},
		handler: function(request, reply) {

			var g = request.auth.credentials.profile;

			//Setup session with no usertype default
			var profile;

			//Find user if exist, add user if they are a new user
			Users.getUser(g.id, function(err, data) {

				console.log("Checking if user exists");

				if(data === null) {

					Users.addUser(profile, function(err, data){

						profile = {
							auth: "Google",
							id: g.id,
							username: g.username,
							displayName: g.displayName,
							firstName: g.name.first,
							lastName: g.name.last,
							email: g.email,
							link: g.raw.link,
							picture: g.raw.picture,
							gender: g.raw.gender,
							website: "",
							usertype: "nouser",
							talkingTo: "noone"
						};

						request.auth.session.set(profile);
						console.log("User added to database");
						reply.redirect("/signup/iam");
					});

				} else {

					profile = {
						auth: data.auth,
						id: data.id,
						username: data.userName,
						displayName: data.displayName,
						firstName: data.firstName,
						lastName: data.lastName,
						email: data.email,
						link: data.link,
						picture: data.picture,
						gender: data.gender,
						website: data.website,
						usertype: data.usertype,
						talkingTo: "noone"
					};

					request.auth.session.set(profile);
					console.log("found user in database");
					reply.redirect("/dashboard");

				}
			});

		}
	},

	signupIam: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			if(request.auth.isAuthenticated) {
				reply.view("signupIam");
			} else {
				reply.redirect("/");
			}
		}
	},

	signupPhotographer: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			//Set usertype session and update to database
			request.auth.session.set("usertype", "photographer");
			var id = request.auth.credentials.id;
			var update = {"usertype": "photographer"};

			Users.updateUser(id, update, function(err, data){
				reply.redirect("/dashboard");
			});
		}
	},

	signupClient: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			//Set usertype session and update to database
			request.auth.session.set("usertype", "client");
			var profile = request.auth.credentials;
			var update = {"usertype": "client"};

			Users.updateUser(profile.id, update, function(err, data){
				reply.redirect("/dashboard");
			});
		}
	},

	dashboard: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			console.log(request.auth.credentials);

			if(request.auth.isAuthenticated) {

				Jobs.getAllJobs(function(err, data) {
					reply.view("dashboard", {jobs: data});
				});
			} else {
				reply.redirect("/");
			}
		}
	},

	profile: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				var profile = request.auth.credentials;

				Photos.findGallery(profile.id, function(err, data){

					if(data === null) {

						reply.view("profile", {profile: profile});
					} else {

						var photos = data.photos;

						reply.view("profile", {profile: profile, photos: photos});
					}

				});

			} else {

				reply.redirect("/");
			}
		}
	},

	profileEdit: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			var profile = request.auth.credentials;
			reply.view("profileEdit", {profile: profile});
		}
	},

	profileEditP: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var update = request.payload;
			console.log(update);

			profile.firstName = update.firstName;
			profile.lastName = update.lastName;
			profile.website = update.website;

			request.auth.session.set(profile);
			Users.updateUser(profile.id, update, function(err, data) {
				reply.redirect("/profile");
			});

		}
	},

	photoDelete: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			var id = request.auth.credentials.id;

			//Big mess to get url from input
			var mess = Object.keys(request.payload)[0];
			var filename = mess.split(" ")[0];
			var ext = mess.split(" ")[1];
			var path = id + "/" + filename + "." + ext;
			var url = "https://camunity.s3.amazonaws.com/" + path;

			Aws.config.update({accessKeyId: Config.s3.key, secretAccessKey: Config.s3.secret});
			var s3 = new Aws.S3();
			var params = {
			  Bucket: Config.s3.bucket,
			  Key: path,
			};
			s3.deleteObject(params, function(err, data) {

			  	if (err) {
			  		console.log("Error deleting from S3", err, err.stack);
			  	} else{
			  		console.log("Deleted from S3");
			  	}
			});

			Photos.deleteURL(id, url, function(err, data) {
				reply.redirect("/profile");
			});
		}
	},

	newJobForm: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {
				reply.view("newJob");
			} else {
				reply.redirect("/");
			}
		}
	},

	newJobPost: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			if(request.auth.isAuthenticated) {

			var user_id = request.auth.credentials.id;

			var new_job = {
				user: user_id,
				dateAdded: new Date(),
				postingAs: request.payload.postingAs,
				eventName: request.payload.eventName,
				dateTime: request.payload.dateTime,
				jobDuration: request.payload.jobDuration,
				location: request.payload.location,
				description: request.payload.description,
				useOfPhotos: request.payload.useOfPhotos,
				dateRequired: request.payload.dateRequired,
				noOfPhotographers: request.payload.noOfPhotographers
			};

			Jobs.newjob(new_job, function(err, data) {
				reply.redirect("/dashboard");
			});

			} else {
				reply.redirect("/");
			}

		}
	},

	upload: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply.view("upload");
		}
	},

	signS3: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var randomKey = Math.floor((Math.random() * 1000) + 1);
			//S3 setup
			Aws.config.update({accessKeyId: Config.s3.key, secretAccessKey: Config.s3.secret});
			var s3 = new Aws.S3();
			var s3_params = {
			    Bucket: Config.s3.bucket,
			    Key: request.auth.credentials.id + "/" + randomKey + "_" + request.query.file_name,
			    Expires: 60,
			    ContentType: request.query.file_type,
			    ACL: Config.s3.acl
			};
			// request.query.file_type (type of file you want to upload)

			s3.getSignedUrl('putObject', s3_params, function(err, data){
			    if(err){
			        console.log(err);
			    }
			    else{
			        var return_data = {
			            signed_request: data,
			            url: 'https://'+Config.s3.bucket+'.s3.amazonaws.com/'+request.auth.credentials.id+'/'+ randomKey + "_" + request.query.file_name,
			        };
			        reply(JSON.stringify(return_data));
			    }
			});
		}
	},

	submitForm: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var id = request.auth.credentials.id;
			var url = request.payload.photo_url;

			var file = url.split('/').slice(4)[0];
			var name = file.split(".")[0];
			var ext = file.split(".")[1];

			var update = { $push: {"photos": {
				"title": request.payload.title,
				"name": name,
				"ext": ext,
				"url": url
			}}};

			Photos.findGallery(id, function(err, data) {
				if(data === null) {
					var object = {"user": id};
					Photos.newGallery(object, function(err, data) {
						Photos.newPhoto(id, update, function(err, data) {
							reply.redirect("/profile");
						});
					});
				} else {
					Photos.newPhoto(id, update, function(err, data) {
						reply.redirect("/profile");
					});
				}
			});

		}
	},

	users: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var myid = request.auth.credentials.id;

			Users.getAllUsers(function(err, data) {
				reply.view("users", {users: data, myid: myid});
			});
		}
	},

	chatWith: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = Object.keys(request.payload)[0];
			var users = {"users": [myid, chatWith]};

			profile.talkingTo = chatWith;
			request.auth.session.set(profile);

			Chat.findChat(myid, chatWith, function(err, data) {
				if(data.length === 0) {

					console.log("New chat");
					Chat.newChat(users, function(err, data){
						reply.redirect("/chat/" + chatWith);
					});

				} else {

					console.log("Chat exists");
					reply.redirect("/chat/" + chatWith);
				}
			});

		}
	},

	chat: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = profile.talkingTo;

			Chat.findChat(myid, chatWith, function(err, data) {
				console.log(data[0]);

				Users.getUser(chatWith, function(err, result){
					console.log(result);
					reply.view("chat", {data: data[0], profile: profile, talkingTo: result});
				});
			});

		}
	},

	chatSubmit: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {

			var profile = request.auth.credentials;
			var myid = profile.id;
			var chatWith = profile.talkingTo;

			var chat = { $push: {"chat": {
				"sender": myid,
				"name": profile.firstName + " " + profile.lastName,
				"message": request.payload.chat,
				"time": Date()
			}}};

			Chat.addChat(myid, chatWith, chat, function(err, data) {
				reply.redirect("/chat/"+ profile.talkingTo);
			});
		}
	},

	help: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			reply("Help");
		}
	},

	logout: {
		auth: {
			mode: "optional"
		},
		handler: function(request, reply) {
			request.auth.session.clear();
			reply.redirect("/");
		}
	}

};<|endoftext|>