<commit_before>'use strict';

angular.module('mean.icu.ui.folderdetails', []).controller('FolderDetailsController', FolderDetailsController);

function FolderDetailsController($rootScope, $scope, entity, me, tasks, people, folders, offices, $timeout, context, $state, FoldersService, PermissionsService, $stateParams, OfficesService, ActivitiesService, EntityService, DetailsPaneService) {

  // ==================================================== init ==================================================== //

  $scope.tabs = DetailsPaneService.orderTabs(['activities', 'documents', 'officeDocuments']);

  let currentState = $state.current.name;

  if (($state.$current.url.source.includes("search")) || ($state.$current.url.source.includes("folders"))) {
    $scope.item = entity || context.entity;
  } else {
    $scope.item = context.entity || entity;
  }

  if (!$scope.item) {
    $state.go('main.folders.byentity', {
      entity: context.entityName,
      entityId: context.entityId
    });
  }

  $scope.options = {
    theme: 'bootstrap',
    buttons: ['bold', 'italic', 'underline', 'anchor', 'quote', 'orderedlist', 'unorderedlist']
  };
  $scope.statuses = ['new', 'in-progress', 'canceled', 'done', 'archived'];

  $scope.entity = entity || context.entity;
  $scope.tasks = tasks.data || tasks;
  $scope.items = folders.data || folders;
  $scope.offices = offices.data || offices;

  // backup for previous changes - for updates
  var backupEntity = JSON.parse(JSON.stringify($scope.item));

  $scope.people = people.data || people;

  $scope.updateCurrentFolder = function(){
    FoldersService.currentFolderName = $scope.item.title;
  }

  FoldersService.getTags().then(result =>
    $scope.tags = result
  );

  FoldersService.getStarred().then(function(starred) {
    $scope.item.star = _(starred).any(function(s) {
      return s._id === $scope.item._id;
    });
  });

  // ==================================================== onChanges ==================================================== //

  function navigateToDetails(folder) {
    $scope.detailsState = context.entityName === 'all' ? 'main.folders.all.details' : 'main.folders.byentity.details';

    $state.go($scope.detailsState, {
      id: folder._id,
      entity: context.entityName,
      entityId: context.entityId,
      starred: $stateParams.starred
    }, {
      reload: true
    });
  }

  $scope.onStar = function(value) {

    $scope.update($scope.item, {
      name: 'star'
    });

    FoldersService.star($scope.item).then(function () {
      navigateToDetails($scope.item);
      // "$scope.item.star" will be change in 'ProjectsService.star' function
    });
  }

  $scope.onStatus = function(value) {
    $scope.item.status = value;
    $scope.update($scope.item, {
      name: 'status'
    })
  }

  $scope.onColor = function(value) {
    $scope.update($scope.item, value);
  }

  $scope.onWantToCreateRoom = function() {
    $scope.item.WantRoom = true;

    $scope.update($scope.item, context);

    FoldersService.WantToCreateRoom($scope.item).then(function(data) {
      navigateToDetails($scope.item);
      if(data.roomName) {
        $window.open(window.config.rocketChat.uri + '/group/' + data.roomName);
        return true;
      }
      else {
        return false;
      }
    });
};

  $scope.onTags = function(value) {
    $scope.item.tags = value;
    $scope.update($scope.item,context);
  }

  // ==================================================== Menu events ==================================================== //

    $scope.recycle = function() {
        EntityService.recycle('folders', $scope.item._id).then(function() {
            let clonedEntity = JSON.parse(JSON.stringify($scope.item));
            clonedEntity.status = "Recycled"
            // just for activity status
            FoldersService.updateStatus(clonedEntity, $scope.item).then(function(result) {
                ActivitiesService.data.push(result);
            });

            refreshList();
            if (currentState.indexOf('search') != -1) {
                $state.go(currentState, {
                    entity: context.entityName,
                    entityId: context.entityId
                }, {
                    reload: true,
                    query: $stateParams.query
                });
            } else {
                $state.go('main.folders.all', {
                    entity: 'all'
                }, {
                    reload: true
                });
            }
        });
    }

    $scope.recycleRestore = function() {
        EntityService.recycleRestore('folders', $scope.item._id).then(function() {
            let clonedEntity = JSON.parse(JSON.stringify($scope.item));
            clonedEntity.status = "un-deleted";
            // just for activity status
            FoldersService.updateStatus(clonedEntity, $scope.item).then(function(result) {
                ActivitiesService.data.push(result);
            });

            refreshList();

            var state = currentState.indexOf('search') !== -1 ? $state.current.name : 'main.folders.all';
            $state.go(state, {
                entity: context.entityName,
                entityId: context.entityId
            }, {
                reload: true
            });
        });
    }

    function refreshList() {
        $rootScope.$broadcast('refreshList');
    }

  $scope.menuItems = [{
    label: 'deleteFolder',
    fa: 'fa-times-circle',
    display: !$scope.item.hasOwnProperty('recycled'),
    action: $scope.recycle,
  },{
    label: 'Say Hi!',
    icon: 'chat',
    display: true,
    action: $scope.onWantToCreateRoom
  },{
    label: 'unrecycleFolder',
    fa: 'fa-times-circle',
    display: $scope.item.hasOwnProperty('recycled'),
    action: $scope.recycleRestore,
  }];

  // ==================================================== Category ==================================================== //

  $scope.onCategory = function(value) {
    if (!value) {
      delete  $scope.item.office;
      $scope.update($scope.item);
      return;
    }

    $scope.item.office = value;

    $scope.item.watchers = $scope.item.watchers.concat($scope.item.office.watchers);
    $scope.item.watchers = _.map(_.groupBy($scope.item.watchers, function(doc) {
      return doc._id;
    }), function(grouped) {
      return grouped[0];
    });

    FoldersService.update($scope.item).then(function(result) {
        backupEntity = JSON.parse(JSON.stringify($scope.item));
      //if (context.entityName === 'office') {
      var officeId = result.office ? result.office._id : undefined;
      if (!officeId) {
        $state.go('main.folders.all.details', {
          entity: 'folder',
          id: $scope.item._id
        }, {
          reload: true
        });
      } else {
        if (officeId !== context.entityId || type === 'office') {
          $state.go('main.folders.byentity.details', {
            entity: context.entityName,
            entityId: officeId,
            id: $scope.item._id
          }, {
            reload: true
          });
        }
      }
    });
  }

  $scope.newCategory = function(value) {
    var office = {
      color: '0097A7',
      title: value,
      watchers: [],
   };
    return OfficesService.create(office).then(function(result) {
      $scope.offices.push(result);
      return result;
    });
  }

  // ==================================================== $watch: title / desc ==================================================== //

  $scope.$watch('item.title', function(nVal, oVal) {
    if (nVal !== oVal) {
      var context = {
        name: 'title',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, context);
      FoldersService.currentFolderName = $scope.item.title;
    }
  });

  var nText, oText;
  $scope.$watch('item.description', function(nVal, oVal) {
    nText = nVal ? nVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    oText = oVal ? oVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    if (nText != oText) {
      var context = {
        name: 'description',
        oldVal: oVal,
        newVal: nVal,
      };
      $scope.delayedUpdate($scope.item, context);
    }
  });

  // ==================================================== Update ==================================================== //

  $scope.update = function(folder, context) {
      if (context.name === 'color') {
          folder.color = context.newVal;
      }
    FoldersService.update(folder, context).then(function(res) {
      if (FoldersService.selected && res._id === FoldersService.selected._id) {
        if (context.name === 'title') {
          FoldersService.selected.title = res.title;
        }
      }
      switch (context.name) {
      case 'status':
        FoldersService.updateStatus(folder, me, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;

      case 'star':
        FoldersService.updateStar(folder, me, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;

      case 'color':
        FoldersService.updateColor(folder, me, backupEntity).then(function(result) {
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;
      case 'title':
          FoldersService.updateTitle(folder, me, backupEntity).then(function(result) {
              backupEntity = JSON.parse(JSON.stringify($scope.item));
              ActivitiesService.data = ActivitiesService.data || [];
              ActivitiesService.data.push(result);
          });
          break;
      case 'description':
        FoldersService.updateDescription(folder, me, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;
      }
    });
  }

  $scope.delayedUpdate = _.debounce($scope.update, 2000);

  // ==================================================== havePermissions ==================================================== //

  $scope.enableRecycled = true;
  $scope.havePermissions = function(type, enableRecycled) {
    if (entity) {
      enableRecycled = enableRecycled || !$scope.isRecycled;
      return (PermissionsService.havePermissions(entity, type) && enableRecycled);
    }
  }

  $scope.haveEditiorsPermissions = function() {
    return PermissionsService.haveEditorsPerms($scope.entity);
  }

  $scope.permsToSee = function() {
    return PermissionsService.haveAnyPerms($scope.entity);
  }

}
<commit_msg>delete office tag from folder details pane bug fix<commit_after>'use strict';

angular.module('mean.icu.ui.folderdetails', []).controller('FolderDetailsController', FolderDetailsController);

function FolderDetailsController($rootScope, $scope, entity, me, tasks, people, folders, offices, $timeout, context, $state, FoldersService, PermissionsService, $stateParams, OfficesService, ActivitiesService, EntityService, DetailsPaneService) {

  // ==================================================== init ==================================================== //

  $scope.tabs = DetailsPaneService.orderTabs(['activities', 'documents', 'officeDocuments']);

  let currentState = $state.current.name;

  if (($state.$current.url.source.includes("search")) || ($state.$current.url.source.includes("folders"))) {
    $scope.item = entity || context.entity;
  } else {
    $scope.item = context.entity || entity;
  }

  if (!$scope.item) {
    $state.go('main.folders.byentity', {
      entity: context.entityName,
      entityId: context.entityId
    });
  }

  $scope.options = {
    theme: 'bootstrap',
    buttons: ['bold', 'italic', 'underline', 'anchor', 'quote', 'orderedlist', 'unorderedlist']
  };
  $scope.statuses = ['new', 'in-progress', 'canceled', 'done', 'archived'];

  $scope.entity = entity || context.entity;
  $scope.tasks = tasks.data || tasks;
  $scope.items = folders.data || folders;
  $scope.offices = offices.data || offices;

  // backup for previous changes - for updates
  var backupEntity = JSON.parse(JSON.stringify($scope.item));

  $scope.people = people.data || people;

  $scope.updateCurrentFolder = function(){
    FoldersService.currentFolderName = $scope.item.title;
  }

  FoldersService.getTags().then(result =>
    $scope.tags = result
  );

  FoldersService.getStarred().then(function(starred) {
    $scope.item.star = _(starred).any(function(s) {
      return s._id === $scope.item._id;
    });
  });

  // ==================================================== onChanges ==================================================== //

  function navigateToDetails(folder) {
    $scope.detailsState = context.entityName === 'all' ? 'main.folders.all.details' : 'main.folders.byentity.details';

    $state.go($scope.detailsState, {
      id: folder._id,
      entity: context.entityName,
      entityId: context.entityId,
      starred: $stateParams.starred
    }, {
      reload: true
    });
  }

  $scope.onStar = function(value) {

    $scope.update($scope.item, {
      name: 'star'
    });

    FoldersService.star($scope.item).then(function () {
      navigateToDetails($scope.item);
      // "$scope.item.star" will be change in 'ProjectsService.star' function
    });
  }

  $scope.onStatus = function(value) {
    $scope.item.status = value;
    $scope.update($scope.item, {
      name: 'status'
    })
  }

  $scope.onColor = function(value) {
    $scope.update($scope.item, value);
  }

  $scope.onWantToCreateRoom = function() {
    $scope.item.WantRoom = true;

    $scope.update($scope.item, context);

    FoldersService.WantToCreateRoom($scope.item).then(function(data) {
      navigateToDetails($scope.item);
      if(data.roomName) {
        $window.open(window.config.rocketChat.uri + '/group/' + data.roomName);
        return true;
      }
      else {
        return false;
      }
    });
};

  $scope.onTags = function(value) {
    $scope.item.tags = value;
    $scope.update($scope.item,context);
  }

  // ==================================================== Menu events ==================================================== //

    $scope.recycle = function() {
        EntityService.recycle('folders', $scope.item._id).then(function() {
            let clonedEntity = JSON.parse(JSON.stringify($scope.item));
            clonedEntity.status = "Recycled"
            // just for activity status
            FoldersService.updateStatus(clonedEntity, $scope.item).then(function(result) {
                ActivitiesService.data.push(result);
            });

            refreshList();
            if (currentState.indexOf('search') != -1) {
                $state.go(currentState, {
                    entity: context.entityName,
                    entityId: context.entityId
                }, {
                    reload: true,
                    query: $stateParams.query
                });
            } else {
                $state.go('main.folders.all', {
                    entity: 'all'
                }, {
                    reload: true
                });
            }
        });
    }

    $scope.recycleRestore = function() {
        EntityService.recycleRestore('folders', $scope.item._id).then(function() {
            let clonedEntity = JSON.parse(JSON.stringify($scope.item));
            clonedEntity.status = "un-deleted";
            // just for activity status
            FoldersService.updateStatus(clonedEntity, $scope.item).then(function(result) {
                ActivitiesService.data.push(result);
            });

            refreshList();

            var state = currentState.indexOf('search') !== -1 ? $state.current.name : 'main.folders.all';
            $state.go(state, {
                entity: context.entityName,
                entityId: context.entityId
            }, {
                reload: true
            });
        });
    }

    function refreshList() {
        $rootScope.$broadcast('refreshList');
    }

  $scope.menuItems = [{
    label: 'deleteFolder',
    fa: 'fa-times-circle',
    display: !$scope.item.hasOwnProperty('recycled'),
    action: $scope.recycle,
  },{
    label: 'Say Hi!',
    icon: 'chat',
    display: true,
    action: $scope.onWantToCreateRoom
  },{
    label: 'unrecycleFolder',
    fa: 'fa-times-circle',
    display: $scope.item.hasOwnProperty('recycled'),
    action: $scope.recycleRestore,
  }];

  // ==================================================== Category ==================================================== //

  $scope.onCategory = function(value) {

    if (value) {
      $scope.item.office = value;
      $scope.item.watchers = $scope.item.watchers.concat($scope.item.office.watchers);
      $scope.item.watchers = _.map(_.groupBy($scope.item.watchers, function(doc) {
        return doc._id;
      }), function(grouped) {
        return grouped[0];
      });
    } else {
      $scope.item.office = {}
    }

    FoldersService.update($scope.item).then(function(result) {
        backupEntity = JSON.parse(JSON.stringify($scope.item));
      //if (context.entityName === 'office') {
      var officeId = result.office ? result.office._id : undefined;
      if (!officeId) {
        $state.go('main.folders.all.details', {
          entity: 'folder',
          id: $scope.item._id
        }, {
          reload: true
        });
      } else {
        if (officeId !== context.entityId || type === 'office') {
          $state.go('main.folders.byentity.details', {
            entity: context.entityName,
            entityId: officeId,
            id: $scope.item._id
          }, {
            reload: true
          });
        }
      }
    });
  }

  $scope.newCategory = function(value) {
    var office = {
      color: '0097A7',
      title: value,
      watchers: [],
   };
    return OfficesService.create(office).then(function(result) {
      $scope.offices.push(result);
      return result;
    });
  }

  // ==================================================== $watch: title / desc ==================================================== //

  $scope.$watch('item.title', function(nVal, oVal) {
    if (nVal !== oVal) {
      var context = {
        name: 'title',
        oldVal: oVal,
        newVal: nVal,
        action: 'renamed'
      };
      $scope.delayedUpdate($scope.item, context);
      FoldersService.currentFolderName = $scope.item.title;
    }
  });

  var nText, oText;
  $scope.$watch('item.description', function(nVal, oVal) {
    nText = nVal ? nVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    oText = oVal ? oVal.replace(/<(?:.|\n)*?>/gm, '') : '';
    if (nText != oText) {
      var context = {
        name: 'description',
        oldVal: oVal,
        newVal: nVal,
      };
      $scope.delayedUpdate($scope.item, context);
    }
  });

  // ==================================================== Update ==================================================== //

  $scope.update = function(folder, context) {
      if (context.name === 'color') {
          folder.color = context.newVal;
      }
    FoldersService.update(folder, context).then(function(res) {
      if (FoldersService.selected && res._id === FoldersService.selected._id) {
        if (context.name === 'title') {
          FoldersService.selected.title = res.title;
        }
      }
      switch (context.name) {
      case 'status':
        FoldersService.updateStatus(folder, me, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;

      case 'star':
        FoldersService.updateStar(folder, me, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;

      case 'color':
        FoldersService.updateColor(folder, me, backupEntity).then(function(result) {
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;
      case 'title':
          FoldersService.updateTitle(folder, me, backupEntity).then(function(result) {
              backupEntity = JSON.parse(JSON.stringify($scope.item));
              ActivitiesService.data = ActivitiesService.data || [];
              ActivitiesService.data.push(result);
          });
          break;
      case 'description':
        FoldersService.updateDescription(folder, me, backupEntity).then(function(result) {
          backupEntity = JSON.parse(JSON.stringify($scope.item));
          ActivitiesService.data = ActivitiesService.data || [];
          ActivitiesService.data.push(result);
        });
        break;
      }
    });
  }

  $scope.delayedUpdate = _.debounce($scope.update, 2000);

  // ==================================================== havePermissions ==================================================== //

  $scope.enableRecycled = true;
  $scope.havePermissions = function(type, enableRecycled) {
    if (entity) {
      enableRecycled = enableRecycled || !$scope.isRecycled;
      return (PermissionsService.havePermissions(entity, type) && enableRecycled);
    }
  }

  $scope.haveEditiorsPermissions = function() {
    return PermissionsService.haveEditorsPerms($scope.entity);
  }

  $scope.permsToSee = function() {
    return PermissionsService.haveAnyPerms($scope.entity);
  }

}
<|endoftext|>


<commit_before>var superagent = require('superagent')
var expect = require('expect.js')
var _ = require('../lib/underscore/underscore');
var parser = require("../app/util/odata-parser");
var country = require("../app/model/country");

describe('OData Parser Tests', function (done) {

    describe('OData parsing tests', function () {

        it('Simple binary expression test', function () {
            var s = "name eq 'test'";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("name");
            expect(obj.type).to.be.eql("eq");
            expect(obj.right).to.be.eql("'test'");
        });

        it('Simple binary expression with String with spaces', function () {
            var s = "name eq 'test of strings'";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("name");
            expect(obj.type).to.be.eql("eq");
            expect(obj.right).to.be.eql("'test of strings'");
        });

        it('Simple binary expression with a number value', function () {
            var s = "id gt 5";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("id");
            expect(obj.type).to.be.eql("gt");
            expect(_.isNumber(obj.right)).to.be.ok();
            expect(obj.right).to.be.eql(5);
        });

        it('Simple binary expression with a number value enclosed with parenthesis', function () {
            var s = "(id lt 5)";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("id");
            expect(obj.type).to.be.eql("lt");
            expect(_.isNumber(obj.right)).to.be.ok();
            expect(obj.right).to.be.eql(5);
        });

        it('Compound binary expression with parenthesis on right', function () {
            var s = "((name eq 'Bob') and (id gt 5))";
            var obj = parser.parse(s);
            var left = obj.left;
            var right = obj.right;
            expect(obj.type).to.be.eql("and");
            expect(left.left).to.be.eql("name");
            expect(left.type).to.be.eql("eq");
            expect(left.right).to.be.eql("\'Bob\'");
            expect(right.left).to.be.eql("id");
            expect(right.type).to.be.eql("gt");
            expect(right.right).to.be.eql(5);
        });

        it('More complex multiple binary expressions', function() {
            var s = "(name eq 'Bob' and (lastName eq 'Smiley' and (weather ne 'sunny' or temp ge 54)))";
            var obj = parser.parse(s);
            var left = obj.left;
            var right = obj.right;
            expect(obj.type).to.be.eql("and");
            expect(left.left).to.be.eql("name");
            expect(left.type).to.be.eql("eq");
            expect(left.right).to.be.eql("\'Bob\'");
            expect(right.type).to.be.eql("and");
            left = right.left;
            right = right.right;
            expect(left.left).to.be.eql("lastName");
            expect(left.type).to.be.eql("eq");
            expect(left.right).to.be.eql("\'Smiley\'");

            expect(right.type).to.be.eql("or");
            left = right.left;
            right = right.right;
            expect(left.left).to.be.eql("weather");
            expect(left.type).to.be.eql("ne");
            expect(left.right).to.be.eql("\'sunny\'");
            expect(right.left).to.be.eql("temp");
            expect(right.type).to.be.eql("ge");
            expect(right.right).to.be.eql("54");

        });

        it('Verify startsWith condition', function() {
            var s = "startswith(name,'Ja')";
            var obj = parser.parse(s);
            expect( obj.left).to.be.eql('name');
            expect( obj.right).to.be.eql('\'Ja*\'');
            expect( obj.type).to.be.eql('like');
        })

        it('Verify endsWith condition', function() {
            var s = "endswith(name,'Hole')";
            var obj = parser.parse(s);
            expect( obj.left).to.be.eql('name');
            expect( obj.right).to.be.eql('\'*Hole\'');
            expect( obj.type).to.be.eql('like');
        });

        it('Verify contains condition', function() {
            var s = "contains(name,'Something')";
            var obj = parser.parse(s);
            expect( obj.left).to.be.eql('name');
            expect( obj.right).to.be.eql('\'*Something*\'');
            expect( obj.type).to.be.eql('like');
        });

    });
});
<commit_msg>tests for the OData Parenthesis tests<commit_after>var superagent = require('superagent')
var expect = require('expect.js')
var _ = require('../lib/underscore/underscore');
var parser = require("../app/util/odata-parser");
var country = require("../app/model/country");

describe('OData Parser Tests', function (done) {

    describe('OData parsing tests', function () {

        it('Simple binary expression test', function () {
            var s = "name eq 'test'";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("name");
            expect(obj.type).to.be.eql("eq");
            expect(obj.right).to.be.eql("'test'");
        });

        it('Simple binary expression with String with spaces', function () {
            var s = "name eq 'test of strings'";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("name");
            expect(obj.type).to.be.eql("eq");
            expect(obj.right).to.be.eql("'test of strings'");
        });

        it('Simple binary expression with a number value', function () {
            var s = "id gt 5";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("id");
            expect(obj.type).to.be.eql("gt");
            expect(_.isNumber(obj.right)).to.be.ok();
            expect(obj.right).to.be.eql(5);
        });

        it('Simple binary expression with a number value enclosed with parenthesis', function () {
            var s = "(id lt 5)";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("id");
            expect(obj.type).to.be.eql("lt");
            expect(_.isNumber(obj.right)).to.be.ok();
            expect(obj.right).to.be.eql(5);
        });

        it('Simple binary expression with text containing parenthesis', function() {
            var s = "name eq 'ultramarine (R)'";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("name");
            expect(obj.type).to.be.eql("eq");
            expect(obj.right).to.be.eql("'ultramarine (R)'");
        });

        it('Simple binary expression with text containing parenthesis and bracketted parenthesis', function() {
            var s = "(name eq 'ultramarine (R)')";
            var obj = parser.parse(s);
            expect(obj.left).to.be.eql("name");
            expect(obj.type).to.be.eql("eq");
            expect(obj.right).to.be.eql("'ultramarine (R)'");
        });

        it.skip('Compound binary expression with text containing parenthesis', function() {
            var s = "((name eq 'ultramarine (R)') and (rate eq '1d'))";
            var obj = parser.parse(s);
            var left = obj.left;
            var right = obj.right;
            expect( obj.type).to.be.eql("and");
            expect(left.left).to.be.eql("name");
            expect(left.type).to.be.eql("eq");
            expect(left.right).to.be.eql("'ultramarine (R)'");
            expect(right.left).to.be.eql("rate");
            expect(right.type).to.be.eql("eq");
            expect(right.right).to.be.eql("1d");
        });

        it('Compound binary expression with parenthesis on right', function () {
            var s = "((name eq 'Bob') and (id gt 5))";
            var obj = parser.parse(s);
            var left = obj.left;
            var right = obj.right;
            expect(obj.type).to.be.eql("and");
            expect(left.left).to.be.eql("name");
            expect(left.type).to.be.eql("eq");
            expect(left.right).to.be.eql("\'Bob\'");
            expect(right.left).to.be.eql("id");
            expect(right.type).to.be.eql("gt");
            expect(right.right).to.be.eql(5);
        });

        it('More complex multiple binary expressions', function() {
            var s = "(name eq 'Bob' and (lastName eq 'Smiley' and (weather ne 'sunny' or temp ge 54)))";
            var obj = parser.parse(s);
            var left = obj.left;
            var right = obj.right;
            expect(obj.type).to.be.eql("and");
            expect(left.left).to.be.eql("name");
            expect(left.type).to.be.eql("eq");
            expect(left.right).to.be.eql("\'Bob\'");
            expect(right.type).to.be.eql("and");
            left = right.left;
            right = right.right;
            expect(left.left).to.be.eql("lastName");
            expect(left.type).to.be.eql("eq");
            expect(left.right).to.be.eql("\'Smiley\'");

            expect(right.type).to.be.eql("or");
            left = right.left;
            right = right.right;
            expect(left.left).to.be.eql("weather");
            expect(left.type).to.be.eql("ne");
            expect(left.right).to.be.eql("\'sunny\'");
            expect(right.left).to.be.eql("temp");
            expect(right.type).to.be.eql("ge");
            expect(right.right).to.be.eql("54");

        });

        it('Verify startsWith condition', function() {
            var s = "startswith(name,'Ja')";
            var obj = parser.parse(s);
            expect( obj.left).to.be.eql('name');
            expect( obj.right).to.be.eql('\'Ja*\'');
            expect( obj.type).to.be.eql('like');
        })

        it('Verify endsWith condition', function() {
            var s = "endswith(name,'Hole')";
            var obj = parser.parse(s);
            expect( obj.left).to.be.eql('name');
            expect( obj.right).to.be.eql('\'*Hole\'');
            expect( obj.type).to.be.eql('like');
        });

        it('Verify contains condition', function() {
            var s = "contains(name,'Something')";
            var obj = parser.parse(s);
            expect( obj.left).to.be.eql('name');
            expect( obj.right).to.be.eql('\'*Something*\'');
            expect( obj.type).to.be.eql('like');
        });

    });
});
<|endoftext|>


<commit_before>iD.Map = function(context) {
    var dimensions = [1, 1],
        dispatch = d3.dispatch('move', 'drawn'),
        projection = d3.geo.mercator()
            .scale(512 / Math.PI)
            .precision(0),
        roundedProjection = iD.svg.RoundProjection(projection),
        zoom = d3.behavior.zoom()
            .translate(projection.translate())
            .scale(projection.scale() * 2 * Math.PI)
            .scaleExtent([1024, 256 * Math.pow(2, 24)])
            .on('zoom', zoomPan),
        dblclickEnabled = true,
        transformStart,
        transformed = false,
        minzoom = 0,
        layers = [
            iD.Background().projection(projection),
            iD.LocalGpx(context).projection(projection),
            iD.Background('overlay').projection(projection)
        ],
        transformProp = iD.util.prefixCSSProperty('Transform'),
        points = iD.svg.Points(roundedProjection, context),
        vertices = iD.svg.Vertices(roundedProjection, context),
        lines = iD.svg.Lines(projection),
        areas = iD.svg.Areas(roundedProjection),
        midpoints = iD.svg.Midpoints(roundedProjection, context),
        labels = iD.svg.Labels(roundedProjection, context),
        supersurface, surface,
        mouse;

    function map(selection) {
        context.history()
            .on('change.map', redraw);

        selection.call(zoom);

        supersurface = selection.append('div')
            .attr('id', 'supersurface');

        layers.forEach(function(layer) {
            supersurface.call(layer);
        });

        // Need a wrapper div because Opera can't cope with an absolutely positioned
        // SVG element: http://bl.ocks.org/jfirebaugh/6fbfbd922552bf776c16
        var dataLayer = supersurface.append('div')
            .attr('class', 'layer-layer layer-data');

        surface = dataLayer.append('svg')
            .on('mousedown.zoom', function() {
                if (d3.event.button == 2) {
                    d3.event.stopPropagation();
                }
            }, true)
            .on('mouseup.zoom', function() {
                if (resetTransform()) redraw();
            })
            .attr('id', 'surface')
            .call(iD.svg.Surface(context));

        surface.on('mouseover.vertices', function() {
            if (map.editable() && !transformed) {
                var hover = d3.event.target.__data__;
                surface.call(vertices.drawHover, context.graph(), hover, map.extent(), map.zoom());
                dispatch.drawn(map);
            }
        });

        surface.on('mouseout.vertices', function() {
            if (map.editable() && !transformed) {
                var hover = d3.event.relatedTarget && d3.event.relatedTarget.__data__;
                surface.call(vertices.drawHover, context.graph(), hover, map.extent(), map.zoom());
                dispatch.drawn(map);
            }
        });

        context.on('select.map', function() {
            if (map.editable() && !transformed) {
                var all = context.intersects(map.extent()),
                    filter = d3.functor(true),
                    extent = map.extent(),
                    graph = context.graph();
                surface.call(vertices, graph, all, filter, extent, map.zoom());
                surface.call(midpoints, graph, all, filter, extent);
                dispatch.drawn(map);
            }
        });

        map.size(selection.size());
        map.surface = surface;

        labels.supersurface(supersurface);
        mouse = iD.util.fastMouse(supersurface.node());
    }

    function pxCenter() { return [dimensions[0] / 2, dimensions[1] / 2]; }

    function drawVector(difference) {
        var filter, all,
            extent = map.extent(),
            graph = context.graph();

        if (!difference) {
            all = context.intersects(extent);
            filter = d3.functor(true);
        } else {
            var complete = difference.complete(extent);
            all = _.compact(_.values(complete));
            filter = function(d) {
                if (d.type === 'midpoint') {

                    var a = d.edge[0],
                        b = d.edge[1];

                    // redraw a midpoint if it needs to be
                    // - moved (either edge node moved)
                    // - deleted (edge nodes not consecutive in any parent way)
                    if (a in complete || b in complete) return true;

                    var parentsWays = graph.parentWays({ id: a });
                    for (var i = 0; i < parentsWays.length; i++) {
                        var nodes = parentsWays[i].nodes;
                        for (var n = 0; n < nodes.length; n++) {
                            if (nodes[n] === a && (nodes[n - 1] === b || nodes[n + 1] === b)) return false;
                        }
                    }
                    return true;

                } else {
                    return d.id in complete;
                }
            };
        }

        surface
            .call(points, graph, all, filter)
            .call(vertices, graph, all, filter, extent, map.zoom())
            .call(lines, graph, all, filter)
            .call(areas, graph, all, filter)
            .call(midpoints, graph, all, filter, extent)
            .call(labels, graph, all, filter, dimensions, !difference);

        dispatch.drawn(map);
    }

    function editOff() {
        surface.selectAll('.layer *').remove();
    }

    var translate3d = !iD.detect().opera &&
        iD.util.stringQs(location.search.substring(1)).translate3d !== '0';

    function zoomPan() {
        if (d3.event && d3.event.sourceEvent.type === 'dblclick') {
            if (!dblclickEnabled) {
                zoom.scale(projection.scale() * 2 * Math.PI)
                    .translate(projection.translate());
                return d3.event.sourceEvent.preventDefault();
            }
        }

        if (Math.log(d3.event.scale / Math.LN2 - 8) < minzoom + 1) {
            iD.ui.flash(context.container())
                .select('.content')
                .text(t('cannot_zoom'));
            return setZoom(16, true);
        }

        projection
            .translate(d3.event.translate)
            .scale(d3.event.scale / (2 * Math.PI));

        var ascale = d3.event.scale;
        var bscale = transformStart[0];
        var scale = (ascale / bscale);

        var tX = Math.round((d3.event.translate[0] / scale) - (transformStart[1][0]));
        var tY = Math.round((d3.event.translate[1] / scale) - (transformStart[1][1]));

        var transform =
            'scale(' + scale + ')' +
            (translate3d ?
                'translate3d(' + tX + 'px,' + tY + 'px, 0)' :
                'translate(' + tX + 'px,' + tY + 'px)');

        transformed = true;
        supersurface.style(transformProp, transform);
        queueRedraw();

        dispatch.move(map);
    }

    function resetTransform() {
        if (!transformed) return false;
        supersurface.style(transformProp, '');
        transformed = false;
        return true;
    }

    function redraw(difference) {

        if (!surface) return;

        clearTimeout(timeoutId);

        // If we are in the middle of a zoom/pan, we can't do differenced redraws.
        // It would result in artifacts where differenced entities are redrawn with
        // one transform and unchanged entities with another.
        if (resetTransform()) {
            difference = undefined;
        }

        var zoom = String(~~map.zoom());
        if (surface.attr('data-zoom') !== zoom) {
            surface.attr('data-zoom', zoom);
        }

        if (!difference) {
            layers.forEach(function(layer) {
                supersurface.call(layer);
            });
        }

        if (map.editable()) {
            context.connection().loadTiles(projection, dimensions);
            drawVector(difference);
        } else {
            editOff();
        }

        transformStart = [
            projection.scale() * 2 * Math.PI,
            projection.translate().slice()];

        return map;
    }

    var timeoutId;
    function queueRedraw() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() { redraw(); }, 300);
    }

    function pointLocation(p) {
        var translate = projection.translate(),
            scale = projection.scale() * 2 * Math.PI;
        return [(p[0] - translate[0]) / scale, (p[1] - translate[1]) / scale];
    }

    function locationPoint(l) {
        var translate = projection.translate(),
            scale = projection.scale() * 2 * Math.PI;
        return [l[0] * scale + translate[0], l[1] * scale + translate[1]];
    }

    map.mouse = function() {
        var e = d3.event, s;
        while (s = e.sourceEvent) e = s;
        return mouse(e);
    };

    map.mouseCoordinates = function() {
        return projection.invert(map.mouse());
    };

    map.dblclickEnable = function(_) {
        if (!arguments.length) return dblclickEnabled;
        dblclickEnabled = _;
        return map;
    };

    function setZoom(z, force) {
        if (z === map.zoom() && !force)
            return false;
        var scale = 256 * Math.pow(2, z),
            center = pxCenter(),
            l = pointLocation(center);
        scale = Math.max(1024, Math.min(256 * Math.pow(2, 24), scale));
        projection.scale(scale / (2 * Math.PI));
        zoom.scale(scale);
        var t = projection.translate();
        l = locationPoint(l);
        t[0] += center[0] - l[0];
        t[1] += center[1] - l[1];
        projection.translate(t);
        zoom.translate(projection.translate());
        return true;
    }

    function setCenter(loc) {
        var t = projection.translate(),
            c = pxCenter(),
            ll = projection(loc);
        if (ll[0] === c[0] && ll[1] === c[1])
            return false;
        projection.translate([
            t[0] - ll[0] + c[0],
            t[1] - ll[1] + c[1]]);
        zoom.translate(projection.translate());
        return true;
    }

    map.pan = function(d) {
        var t = projection.translate();
        t[0] += d[0];
        t[1] += d[1];
        projection.translate(t);
        zoom.translate(projection.translate());
        dispatch.move(map);
        return redraw();
    };

    map.size = function(_) {
        if (!arguments.length) return dimensions;
        var center = map.center();
        dimensions = _;
        surface.size(dimensions);
        layers.forEach(function(layer) {
            layer.size(dimensions);
        });
        projection.clipExtent([[0, 0], dimensions]);
        setCenter(center);
        return redraw();
    };

    map.zoomIn = function() { return map.zoom(Math.ceil(map.zoom() + 1)); };
    map.zoomOut = function() { return map.zoom(Math.floor(map.zoom() - 1)); };

    map.center = function(loc) {
        if (!arguments.length) {
            return projection.invert(pxCenter());
        }

        if (setCenter(loc)) {
            dispatch.move(map);
        }

        return redraw();
    };

    map.zoom = function(z) {
        if (!arguments.length) {
            return Math.max(Math.log(projection.scale() * 2 * Math.PI) / Math.LN2 - 8, 0);
        }

        if (setZoom(z)) {
            dispatch.move(map);
        }

        return redraw();
    };

    map.zoomTo = function(entity) {
        var extent = entity.extent(context.graph()),
            zoom = map.extentZoom(extent);
        map.centerZoom(extent.center(), zoom);
    };

    map.centerZoom = function(loc, z) {
        var centered = setCenter(loc),
            zoomed   = setZoom(z);

        if (centered || zoomed) {
            dispatch.move(map);
        }

        return redraw();
    };

    map.centerEase = function(loc) {
        var from = map.center().slice(),
            t = 0,
            stop;

        surface.one('mousedown.ease', function() {
            stop = true;
        });

        d3.timer(function() {
            if (stop) return true;
            map.center(iD.geo.interp(from, loc, (t += 1) / 10));
            return t == 10;
        }, 20);
        return map;
    };

    map.extent = function(_) {
        if (!arguments.length) {
            return new iD.geo.Extent(projection.invert([0, dimensions[1]]),
                                 projection.invert([dimensions[0], 0]));
        } else {
            var extent = iD.geo.Extent(_);
            map.centerZoom(extent.center(), map.extentZoom(extent));
        }
    };

    map.extentZoom = function(_) {
        var extent = iD.geo.Extent(_),
            tl = projection([extent[0][0], extent[1][1]]),
            br = projection([extent[1][0], extent[0][1]]);

        // Calculate maximum zoom that fits extent
        var hFactor = (br[0] - tl[0]) / dimensions[0],
            vFactor = (br[1] - tl[1]) / dimensions[1],
            hZoomDiff = Math.log(Math.abs(hFactor)) / Math.LN2,
            vZoomDiff = Math.log(Math.abs(vFactor)) / Math.LN2,
            newZoom = map.zoom() - Math.max(hZoomDiff, vZoomDiff);

        return newZoom;
    };

    map.flush = function() {
        context.connection().flush();
        context.history().reset();
        return map;
    };

    map.editable = function() {
        return map.zoom() >= 16;
    };

    map.minzoom = function(_) {
        if (!arguments.length) return minzoom;
        minzoom = _;
        return map;
    };

    map.layers = layers;
    map.projection = projection;
    map.redraw = redraw;

    return d3.rebind(map, dispatch, 'on');
};
<commit_msg>Revert "Add URL flag for translate3d"<commit_after>iD.Map = function(context) {
    var dimensions = [1, 1],
        dispatch = d3.dispatch('move', 'drawn'),
        projection = d3.geo.mercator()
            .scale(512 / Math.PI)
            .precision(0),
        roundedProjection = iD.svg.RoundProjection(projection),
        zoom = d3.behavior.zoom()
            .translate(projection.translate())
            .scale(projection.scale() * 2 * Math.PI)
            .scaleExtent([1024, 256 * Math.pow(2, 24)])
            .on('zoom', zoomPan),
        dblclickEnabled = true,
        transformStart,
        transformed = false,
        minzoom = 0,
        layers = [
            iD.Background().projection(projection),
            iD.LocalGpx(context).projection(projection),
            iD.Background('overlay').projection(projection)
        ],
        transformProp = iD.util.prefixCSSProperty('Transform'),
        points = iD.svg.Points(roundedProjection, context),
        vertices = iD.svg.Vertices(roundedProjection, context),
        lines = iD.svg.Lines(projection),
        areas = iD.svg.Areas(roundedProjection),
        midpoints = iD.svg.Midpoints(roundedProjection, context),
        labels = iD.svg.Labels(roundedProjection, context),
        supersurface, surface,
        mouse;

    function map(selection) {
        context.history()
            .on('change.map', redraw);

        selection.call(zoom);

        supersurface = selection.append('div')
            .attr('id', 'supersurface');

        layers.forEach(function(layer) {
            supersurface.call(layer);
        });

        // Need a wrapper div because Opera can't cope with an absolutely positioned
        // SVG element: http://bl.ocks.org/jfirebaugh/6fbfbd922552bf776c16
        var dataLayer = supersurface.append('div')
            .attr('class', 'layer-layer layer-data');

        surface = dataLayer.append('svg')
            .on('mousedown.zoom', function() {
                if (d3.event.button == 2) {
                    d3.event.stopPropagation();
                }
            }, true)
            .on('mouseup.zoom', function() {
                if (resetTransform()) redraw();
            })
            .attr('id', 'surface')
            .call(iD.svg.Surface(context));

        surface.on('mouseover.vertices', function() {
            if (map.editable() && !transformed) {
                var hover = d3.event.target.__data__;
                surface.call(vertices.drawHover, context.graph(), hover, map.extent(), map.zoom());
                dispatch.drawn(map);
            }
        });

        surface.on('mouseout.vertices', function() {
            if (map.editable() && !transformed) {
                var hover = d3.event.relatedTarget && d3.event.relatedTarget.__data__;
                surface.call(vertices.drawHover, context.graph(), hover, map.extent(), map.zoom());
                dispatch.drawn(map);
            }
        });

        context.on('select.map', function() {
            if (map.editable() && !transformed) {
                var all = context.intersects(map.extent()),
                    filter = d3.functor(true),
                    extent = map.extent(),
                    graph = context.graph();
                surface.call(vertices, graph, all, filter, extent, map.zoom());
                surface.call(midpoints, graph, all, filter, extent);
                dispatch.drawn(map);
            }
        });

        map.size(selection.size());
        map.surface = surface;

        labels.supersurface(supersurface);
        mouse = iD.util.fastMouse(supersurface.node());
    }

    function pxCenter() { return [dimensions[0] / 2, dimensions[1] / 2]; }

    function drawVector(difference) {
        var filter, all,
            extent = map.extent(),
            graph = context.graph();

        if (!difference) {
            all = context.intersects(extent);
            filter = d3.functor(true);
        } else {
            var complete = difference.complete(extent);
            all = _.compact(_.values(complete));
            filter = function(d) {
                if (d.type === 'midpoint') {

                    var a = d.edge[0],
                        b = d.edge[1];

                    // redraw a midpoint if it needs to be
                    // - moved (either edge node moved)
                    // - deleted (edge nodes not consecutive in any parent way)
                    if (a in complete || b in complete) return true;

                    var parentsWays = graph.parentWays({ id: a });
                    for (var i = 0; i < parentsWays.length; i++) {
                        var nodes = parentsWays[i].nodes;
                        for (var n = 0; n < nodes.length; n++) {
                            if (nodes[n] === a && (nodes[n - 1] === b || nodes[n + 1] === b)) return false;
                        }
                    }
                    return true;

                } else {
                    return d.id in complete;
                }
            };
        }

        surface
            .call(points, graph, all, filter)
            .call(vertices, graph, all, filter, extent, map.zoom())
            .call(lines, graph, all, filter)
            .call(areas, graph, all, filter)
            .call(midpoints, graph, all, filter, extent)
            .call(labels, graph, all, filter, dimensions, !difference);

        dispatch.drawn(map);
    }

    function editOff() {
        surface.selectAll('.layer *').remove();
    }

    function zoomPan() {
        if (d3.event && d3.event.sourceEvent.type === 'dblclick') {
            if (!dblclickEnabled) {
                zoom.scale(projection.scale() * 2 * Math.PI)
                    .translate(projection.translate());
                return d3.event.sourceEvent.preventDefault();
            }
        }

        if (Math.log(d3.event.scale / Math.LN2 - 8) < minzoom + 1) {
            iD.ui.flash(context.container())
                .select('.content')
                .text(t('cannot_zoom'));
            return setZoom(16, true);
        }

        projection
            .translate(d3.event.translate)
            .scale(d3.event.scale / (2 * Math.PI));

        var ascale = d3.event.scale;
        var bscale = transformStart[0];
        var scale = (ascale / bscale);

        var tX = Math.round((d3.event.translate[0] / scale) - (transformStart[1][0]));
        var tY = Math.round((d3.event.translate[1] / scale) - (transformStart[1][1]));

        var transform =
            'scale(' + scale + ')' +
            (iD.detect().opera ?
                'translate(' + tX + 'px,' + tY + 'px)' :
                'translate3d(' + tX + 'px,' + tY + 'px, 0)');

        transformed = true;
        supersurface.style(transformProp, transform);
        queueRedraw();

        dispatch.move(map);
    }

    function resetTransform() {
        if (!transformed) return false;
        supersurface.style(transformProp, '');
        transformed = false;
        return true;
    }

    function redraw(difference) {

        if (!surface) return;

        clearTimeout(timeoutId);

        // If we are in the middle of a zoom/pan, we can't do differenced redraws.
        // It would result in artifacts where differenced entities are redrawn with
        // one transform and unchanged entities with another.
        if (resetTransform()) {
            difference = undefined;
        }

        var zoom = String(~~map.zoom());
        if (surface.attr('data-zoom') !== zoom) {
            surface.attr('data-zoom', zoom);
        }

        if (!difference) {
            layers.forEach(function(layer) {
                supersurface.call(layer);
            });
        }

        if (map.editable()) {
            context.connection().loadTiles(projection, dimensions);
            drawVector(difference);
        } else {
            editOff();
        }

        transformStart = [
            projection.scale() * 2 * Math.PI,
            projection.translate().slice()];

        return map;
    }

    var timeoutId;
    function queueRedraw() {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(function() { redraw(); }, 300);
    }

    function pointLocation(p) {
        var translate = projection.translate(),
            scale = projection.scale() * 2 * Math.PI;
        return [(p[0] - translate[0]) / scale, (p[1] - translate[1]) / scale];
    }

    function locationPoint(l) {
        var translate = projection.translate(),
            scale = projection.scale() * 2 * Math.PI;
        return [l[0] * scale + translate[0], l[1] * scale + translate[1]];
    }

    map.mouse = function() {
        var e = d3.event, s;
        while (s = e.sourceEvent) e = s;
        return mouse(e);
    };

    map.mouseCoordinates = function() {
        return projection.invert(map.mouse());
    };

    map.dblclickEnable = function(_) {
        if (!arguments.length) return dblclickEnabled;
        dblclickEnabled = _;
        return map;
    };

    function setZoom(z, force) {
        if (z === map.zoom() && !force)
            return false;
        var scale = 256 * Math.pow(2, z),
            center = pxCenter(),
            l = pointLocation(center);
        scale = Math.max(1024, Math.min(256 * Math.pow(2, 24), scale));
        projection.scale(scale / (2 * Math.PI));
        zoom.scale(scale);
        var t = projection.translate();
        l = locationPoint(l);
        t[0] += center[0] - l[0];
        t[1] += center[1] - l[1];
        projection.translate(t);
        zoom.translate(projection.translate());
        return true;
    }

    function setCenter(loc) {
        var t = projection.translate(),
            c = pxCenter(),
            ll = projection(loc);
        if (ll[0] === c[0] && ll[1] === c[1])
            return false;
        projection.translate([
            t[0] - ll[0] + c[0],
            t[1] - ll[1] + c[1]]);
        zoom.translate(projection.translate());
        return true;
    }

    map.pan = function(d) {
        var t = projection.translate();
        t[0] += d[0];
        t[1] += d[1];
        projection.translate(t);
        zoom.translate(projection.translate());
        dispatch.move(map);
        return redraw();
    };

    map.size = function(_) {
        if (!arguments.length) return dimensions;
        var center = map.center();
        dimensions = _;
        surface.size(dimensions);
        layers.forEach(function(layer) {
            layer.size(dimensions);
        });
        projection.clipExtent([[0, 0], dimensions]);
        setCenter(center);
        return redraw();
    };

    map.zoomIn = function() { return map.zoom(Math.ceil(map.zoom() + 1)); };
    map.zoomOut = function() { return map.zoom(Math.floor(map.zoom() - 1)); };

    map.center = function(loc) {
        if (!arguments.length) {
            return projection.invert(pxCenter());
        }

        if (setCenter(loc)) {
            dispatch.move(map);
        }

        return redraw();
    };

    map.zoom = function(z) {
        if (!arguments.length) {
            return Math.max(Math.log(projection.scale() * 2 * Math.PI) / Math.LN2 - 8, 0);
        }

        if (setZoom(z)) {
            dispatch.move(map);
        }

        return redraw();
    };

    map.zoomTo = function(entity) {
        var extent = entity.extent(context.graph()),
            zoom = map.extentZoom(extent);
        map.centerZoom(extent.center(), zoom);
    };

    map.centerZoom = function(loc, z) {
        var centered = setCenter(loc),
            zoomed   = setZoom(z);

        if (centered || zoomed) {
            dispatch.move(map);
        }

        return redraw();
    };

    map.centerEase = function(loc) {
        var from = map.center().slice(),
            t = 0,
            stop;

        surface.one('mousedown.ease', function() {
            stop = true;
        });

        d3.timer(function() {
            if (stop) return true;
            map.center(iD.geo.interp(from, loc, (t += 1) / 10));
            return t == 10;
        }, 20);
        return map;
    };

    map.extent = function(_) {
        if (!arguments.length) {
            return new iD.geo.Extent(projection.invert([0, dimensions[1]]),
                                 projection.invert([dimensions[0], 0]));
        } else {
            var extent = iD.geo.Extent(_);
            map.centerZoom(extent.center(), map.extentZoom(extent));
        }
    };

    map.extentZoom = function(_) {
        var extent = iD.geo.Extent(_),
            tl = projection([extent[0][0], extent[1][1]]),
            br = projection([extent[1][0], extent[0][1]]);

        // Calculate maximum zoom that fits extent
        var hFactor = (br[0] - tl[0]) / dimensions[0],
            vFactor = (br[1] - tl[1]) / dimensions[1],
            hZoomDiff = Math.log(Math.abs(hFactor)) / Math.LN2,
            vZoomDiff = Math.log(Math.abs(vFactor)) / Math.LN2,
            newZoom = map.zoom() - Math.max(hZoomDiff, vZoomDiff);

        return newZoom;
    };

    map.flush = function() {
        context.connection().flush();
        context.history().reset();
        return map;
    };

    map.editable = function() {
        return map.zoom() >= 16;
    };

    map.minzoom = function(_) {
        if (!arguments.length) return minzoom;
        minzoom = _;
        return map;
    };

    map.layers = layers;
    map.projection = projection;
    map.redraw = redraw;

    return d3.rebind(map, dispatch, 'on');
};
<|endoftext|>


<commit_before>//EXTERNAL MODULES//
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var mongoose = require("mongoose");

//CONFIG//
var config = require("./config.js");

//EXPRESS//
var app = express();

app.use(express.static(__dirname + "/public"));

app.use(bodyParser.json());
app.use(session({
  secret: config.SESSION_SECRET,
  saveUninitialized: false,
  resave: false
}));

//ROUTES//
app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname + "/public" });
});

//CONNECTIONS//
//CONNECTIONS//
var port = 80;

app.listen(port, function(){
    console.log("Jake the Snake", port);
});

module.exports = app;
<commit_msg>Removed a line<commit_after>//EXTERNAL MODULES//
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var mongoose = require("mongoose");

//CONFIG//
var config = require("./config.js");

//EXPRESS//
var app = express();

app.use(express.static(__dirname + "/public"));

app.use(bodyParser.json());
app.use(session({
  secret: config.SESSION_SECRET,
  saveUninitialized: false,
  resave: false
}));

//ROUTES//
app.all('/*', function(req, res, next) {
    // Just send the index.html for other files to support HTML5Mode
    res.sendFile('index.html', { root: __dirname + "/public" });
});

//CONNECTIONS//
var port = 80;

app.listen(port, function(){
    console.log("Jake the Snake", port);
});

module.exports = app;
<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Applies listview styling of various types (standard, numbered, split button, etc.)
//>>label: Listview
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.listview.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.buttonMarkup", "./page", "./page.sections", "./addFirstLastClasses", "../jquery.mobile.registry" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

//Keeps track of the number of lists per page UID
//This allows support for multiple nested list in the same page
//https://github.com/jquery/jquery-mobile/issues/1617
var getAttr = $.mobile.getAttribute;

$.widget( "mobile.listview", $.mobile.widget, $.extend( {

	options: {
		theme: null,
		countTheme: "c",
		headerTheme: "b",
		dividerTheme: "b",
		icon: "arrow-r",
		splitIcon: "arrow-r",
		splitTheme: "b",
		corners: true,
		shadow: true,
		inset: false
	},

	_create: function() {
		var t = this,
			listviewClasses = "";

		listviewClasses += t.options.inset ? " ui-listview-inset" : "";

		if ( !!t.options.inset ) {
			listviewClasses += t.options.corners ? " ui-corner-all" : "";
			listviewClasses += t.options.shadow ? " ui-shadow" : "";
		}

		// create listview markup
		t.element.addClass(function( i, orig ) {
			return orig + " ui-listview" + listviewClasses;
		});

		t.refresh( true );
	},

	// This is a generic utility method for finding the first
	// node with a given nodeName. It uses basic DOM traversal
	// to be fast and is meant to be a substitute for simple
	// $.fn.closest() and $.fn.children() calls on a single
	// element. Note that callers must pass both the lowerCase
	// and upperCase version of the nodeName they are looking for.
	// The main reason for this is that this function will be
	// called many times and we want to avoid having to lowercase
	// the nodeName from the element every time to ensure we have
	// a match. Note that this function lives here for now, but may
	// be moved into $.mobile if other components need a similar method.
	_findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) {
		var dict = {};
		dict[ lcName ] = dict[ ucName ] = true;
		while ( ele ) {
			if ( dict[ ele.nodeName ] ) {
				return ele;
			}
			ele = ele[ nextProp ];
		}
		return null;
	},
	_getChildrenByTagName: function( ele, lcName, ucName ) {
		var results = [],
			dict = {};
		dict[ lcName ] = dict[ ucName ] = true;
		ele = ele.firstChild;
		while ( ele ) {
			if ( dict[ ele.nodeName ] ) {
				results.push( ele );
			}
			ele = ele.nextSibling;
		}
		return $( results );
	},

	_addThumbClasses: function( containers ) {
		var i, img, len = containers.length;
		for ( i = 0; i < len; i++ ) {
			img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
			if ( img.length ) {
				img.addClass( "ui-li-thumb" );
				$( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.hasClass( "ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
			}
		}
	},

	refresh: function( create ) {
		this.parentPage = this.element.closest( ".ui-page" );

		var o = this.options,
			$list = this.element,
			dividertheme = getAttr( $list[ 0 ], "dividertheme", true ) || o.dividerTheme,
			listsplittheme = getAttr( $list[ 0 ], "splittheme", true ),
			listspliticon = getAttr( $list[ 0 ], "spliticon", true ),
			listicon = getAttr( $list[ 0 ], "icon", true ),
			li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
			ol = !!$.nodeName( $list[ 0 ], "ol" ),
			jsCount = !$.support.cssPseudoElement,
			start = $list.attr( "start" ),
			itemClassDict = {},
			item, itemClass, itemTheme,
			a, last, splittheme, counter, startCount, newStartCount, countParent, icon, linkIcon,
			pos, numli, isDivider;

		if ( ol && jsCount ) {
			$list.find( ".ui-li-dec" ).remove();
		}

		if ( ol ) {
			// Check if a start attribute has been set while taking a value of 0 into account
			if ( start || start === 0 ) {
				if ( !jsCount ) {
					startCount = parseInt( start , 10 ) - 1;
					$list.css( "counter-reset", "listnumbering " + startCount );
				} else {
					counter = parseInt( start , 10 );
				}
			} else if ( jsCount ) {
					counter = 1;
			}
		}

		if ( !o.theme ) {
			o.theme = $.mobile.getInheritedTheme( this.element, "c" );
		}

		for ( pos = 0, numli = li.length; pos < numli; pos++ ) {
			item = li.eq( pos );
			itemClass = "ui-li";

			// If we're creating the element, we update it regardless
			if ( create || !item.hasClass( "ui-li" ) ) {
				itemTheme = getAttr( item[ 0 ], "theme", true ) || o.theme;
				a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
				isDivider = ( getAttr( item[ 0 ], "role", true ) === "list-divider" );

				if ( a.length && !isDivider ) {
					icon = getAttr( item[ 0 ], "icon", true );

					item.buttonMarkup({
						wrapperEls: "div",
						shadow: false,
						corners: false,
						iconpos: "right",
						icon: a.length > 1 || icon === false ? false : icon || listicon || o.icon,
						theme: itemTheme
					});

					if ( ( icon !== false ) && ( a.length === 1 ) ) {
						item.addClass( "ui-li-has-arrow" );
					}

					a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" );

					if ( a.length > 1 ) {
						itemClass += " ui-li-has-alt";

						last = a.last();
						splittheme = listsplittheme || getAttr( last[ 0 ], "theme", true ) || o.splitTheme;
						linkIcon = getAttr( last[ 0 ], "icon", true );

						last.appendTo( item )
							.attr( "title", $.trim(last.getEncodedText()) )
							.addClass( "ui-li-link-alt" )
							.empty()
							.buttonMarkup({
								shadow: false,
								corners: false,
								theme: itemTheme,
								icon: false,
								iconpos: "notext"
							})
							.find( ".ui-btn-inner" )
								.append(
									$( document.createElement( "span" ) ).buttonMarkup({
										shadow: true,
										corners: true,
										theme: splittheme,
										iconpos: "notext",
										// link icon overrides list item icon overrides ul element overrides options
										icon: linkIcon || icon || listspliticon || o.splitIcon
									})
								);
					}
				} else if ( isDivider ) {

					itemClass += " ui-li-divider ui-bar-" + ( getAttr( item[ 0 ], "theme", true ) || dividertheme );
					item.attr( "role", "heading" );

					if ( ol ) {
						//reset counter when a divider heading is encountered
						if ( start || start === 0 ) {
							if ( !jsCount ) {
								newStartCount = parseInt( start , 10 ) - 1;
								item.css( "counter-reset", "listnumbering " + newStartCount );
							} else {
								counter = parseInt( start , 10 );
							}
						} else if ( jsCount ) {
								counter = 1;
						}
					}

				} else {
					itemClass += " ui-li-static ui-btn-up-" + itemTheme;
				}
			}

			if ( ol && jsCount && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
				countParent = itemClass.indexOf( "ui-li-static" ) > 0 ? item : item.find( ".ui-link-inherit" );

				countParent.addClass( "ui-li-jsnumbering" )
					.prepend( "" + ( counter++ ) + ". " );
			}

			// Instead of setting item class directly on the list item and its
			// btn-inner at this point in time, push the item into a dictionary
			// that tells us what class to set on it so we can do this after this
			// processing loop is finished.

			if ( !itemClassDict[ itemClass ] ) {
				itemClassDict[ itemClass ] = [];
			}

			itemClassDict[ itemClass ].push( item[ 0 ] );
		}

		// Set the appropriate listview item classes on each list item
		// and their btn-inner elements. The main reason we didn't do this
		// in the for-loop above is because we can eliminate per-item function overhead
		// by calling addClass() and children() once or twice afterwards. This
		// can give us a significant boost on platforms like WP7.5.

		for ( itemClass in itemClassDict ) {
			$( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
		}

		$list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
			.end()

			.find( "p, dl" ).addClass( "ui-li-desc" )
			.end()

			.find( ".ui-li-aside" ).each(function() {
					var $this = $( this );
					$this.prependTo( $this.parent() ); //shift aside to front for css float
				})
			.end()

			.find( ".ui-li-count" ).each(function() {
					$( this ).closest( "li" ).addClass( "ui-li-has-count" );
				}).addClass( "ui-btn-up-" + ( getAttr( $list[ 0 ], "counttheme", true ) || this.options.countTheme) + " ui-btn-corner-all" );

		// The idea here is to look at the first image in the list item
		// itself, and any .ui-link-inherit element it may contain, so we
		// can place the appropriate classes on the image and list item.
		// Note that we used to use something like:
		//
		//    li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
		//
		// But executing a find() like that on Windows Phone 7.5 took a
		// really long time. Walking things manually with the code below
		// allows the 400 listview item page to load in about 3 seconds as
		// opposed to 30 seconds.

		this._addThumbClasses( li );
		this._addThumbClasses( $list.find( ".ui-link-inherit" ) );

		this._addFirstLastClasses( li, this._getVisibles( li, create ), create );
		// autodividers binds to this to redraw dividers after the listview refresh
		this._trigger( "afterrefresh" );
	},

	//create a string for ID/subpage url creation
	_idStringEscape: function( str ) {
		return str.replace(/[^a-zA-Z0-9]/g, "-");
	}
}, $.mobile.behaviors.addFirstLastClasses ) );

$.mobile.listview.initSelector = ":jqmData(role='listview')";

//auto self-init widgets
$.mobile._enhancer.add( "mobile.listview" );

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>Listview: remove all js dependancy on page<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Applies listview styling of various types (standard, numbered, split button, etc.)
//>>label: Listview
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.listview.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.buttonMarkup", "./page", "./page.sections", "./addFirstLastClasses", "../jquery.mobile.registry" ], function( jQuery ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {

var getAttr = $.mobile.getAttribute;

$.widget( "mobile.listview", $.mobile.widget, $.extend( {

	options: {
		theme: null,
		countTheme: "c",
		headerTheme: "b",
		dividerTheme: "b",
		icon: "arrow-r",
		splitIcon: "arrow-r",
		splitTheme: "b",
		corners: true,
		shadow: true,
		inset: false
	},

	_create: function() {
		var t = this,
			listviewClasses = "";

		listviewClasses += t.options.inset ? " ui-listview-inset" : "";

		if ( !!t.options.inset ) {
			listviewClasses += t.options.corners ? " ui-corner-all" : "";
			listviewClasses += t.options.shadow ? " ui-shadow" : "";
		}

		// create listview markup
		t.element.addClass(function( i, orig ) {
			return orig + " ui-listview" + listviewClasses;
		});

		t.refresh( true );
	},

	// This is a generic utility method for finding the first
	// node with a given nodeName. It uses basic DOM traversal
	// to be fast and is meant to be a substitute for simple
	// $.fn.closest() and $.fn.children() calls on a single
	// element. Note that callers must pass both the lowerCase
	// and upperCase version of the nodeName they are looking for.
	// The main reason for this is that this function will be
	// called many times and we want to avoid having to lowercase
	// the nodeName from the element every time to ensure we have
	// a match. Note that this function lives here for now, but may
	// be moved into $.mobile if other components need a similar method.
	_findFirstElementByTagName: function( ele, nextProp, lcName, ucName ) {
		var dict = {};
		dict[ lcName ] = dict[ ucName ] = true;
		while ( ele ) {
			if ( dict[ ele.nodeName ] ) {
				return ele;
			}
			ele = ele[ nextProp ];
		}
		return null;
	},
	_getChildrenByTagName: function( ele, lcName, ucName ) {
		var results = [],
			dict = {};
		dict[ lcName ] = dict[ ucName ] = true;
		ele = ele.firstChild;
		while ( ele ) {
			if ( dict[ ele.nodeName ] ) {
				results.push( ele );
			}
			ele = ele.nextSibling;
		}
		return $( results );
	},

	_addThumbClasses: function( containers ) {
		var i, img, len = containers.length;
		for ( i = 0; i < len; i++ ) {
			img = $( this._findFirstElementByTagName( containers[ i ].firstChild, "nextSibling", "img", "IMG" ) );
			if ( img.length ) {
				img.addClass( "ui-li-thumb" );
				$( this._findFirstElementByTagName( img[ 0 ].parentNode, "parentNode", "li", "LI" ) ).addClass( img.hasClass( "ui-li-icon" ) ? "ui-li-has-icon" : "ui-li-has-thumb" );
			}
		}
	},

	refresh: function( create ) {
		var o = this.options,
			$list = this.element,
			dividertheme = getAttr( $list[ 0 ], "dividertheme", true ) || o.dividerTheme,
			listsplittheme = getAttr( $list[ 0 ], "splittheme", true ),
			listspliticon = getAttr( $list[ 0 ], "spliticon", true ),
			listicon = getAttr( $list[ 0 ], "icon", true ),
			li = this._getChildrenByTagName( $list[ 0 ], "li", "LI" ),
			ol = !!$.nodeName( $list[ 0 ], "ol" ),
			jsCount = !$.support.cssPseudoElement,
			start = $list.attr( "start" ),
			itemClassDict = {},
			item, itemClass, itemTheme,
			a, last, splittheme, counter, startCount, newStartCount, countParent, icon, linkIcon,
			pos, numli, isDivider;

		if ( ol && jsCount ) {
			$list.find( ".ui-li-dec" ).remove();
		}

		if ( ol ) {
			// Check if a start attribute has been set while taking a value of 0 into account
			if ( start || start === 0 ) {
				if ( !jsCount ) {
					startCount = parseInt( start , 10 ) - 1;
					$list.css( "counter-reset", "listnumbering " + startCount );
				} else {
					counter = parseInt( start , 10 );
				}
			} else if ( jsCount ) {
					counter = 1;
			}
		}

		if ( !o.theme ) {
			o.theme = $.mobile.getInheritedTheme( this.element, "c" );
		}

		for ( pos = 0, numli = li.length; pos < numli; pos++ ) {
			item = li.eq( pos );
			itemClass = "ui-li";

			// If we're creating the element, we update it regardless
			if ( create || !item.hasClass( "ui-li" ) ) {
				itemTheme = getAttr( item[ 0 ], "theme", true ) || o.theme;
				a = this._getChildrenByTagName( item[ 0 ], "a", "A" );
				isDivider = ( getAttr( item[ 0 ], "role", true ) === "list-divider" );

				if ( a.length && !isDivider ) {
					icon = getAttr( item[ 0 ], "icon", true );

					item.buttonMarkup({
						wrapperEls: "div",
						shadow: false,
						corners: false,
						iconpos: "right",
						icon: a.length > 1 || icon === false ? false : icon || listicon || o.icon,
						theme: itemTheme
					});

					if ( ( icon !== false ) && ( a.length === 1 ) ) {
						item.addClass( "ui-li-has-arrow" );
					}

					a.first().removeClass( "ui-link" ).addClass( "ui-link-inherit" );

					if ( a.length > 1 ) {
						itemClass += " ui-li-has-alt";

						last = a.last();
						splittheme = listsplittheme || getAttr( last[ 0 ], "theme", true ) || o.splitTheme;
						linkIcon = getAttr( last[ 0 ], "icon", true );

						last.appendTo( item )
							.attr( "title", $.trim(last.getEncodedText()) )
							.addClass( "ui-li-link-alt" )
							.empty()
							.buttonMarkup({
								shadow: false,
								corners: false,
								theme: itemTheme,
								icon: false,
								iconpos: "notext"
							})
							.find( ".ui-btn-inner" )
								.append(
									$( document.createElement( "span" ) ).buttonMarkup({
										shadow: true,
										corners: true,
										theme: splittheme,
										iconpos: "notext",
										// link icon overrides list item icon overrides ul element overrides options
										icon: linkIcon || icon || listspliticon || o.splitIcon
									})
								);
					}
				} else if ( isDivider ) {

					itemClass += " ui-li-divider ui-bar-" + ( getAttr( item[ 0 ], "theme", true ) || dividertheme );
					item.attr( "role", "heading" );

					if ( ol ) {
						//reset counter when a divider heading is encountered
						if ( start || start === 0 ) {
							if ( !jsCount ) {
								newStartCount = parseInt( start , 10 ) - 1;
								item.css( "counter-reset", "listnumbering " + newStartCount );
							} else {
								counter = parseInt( start , 10 );
							}
						} else if ( jsCount ) {
								counter = 1;
						}
					}

				} else {
					itemClass += " ui-li-static ui-btn-up-" + itemTheme;
				}
			}

			if ( ol && jsCount && itemClass.indexOf( "ui-li-divider" ) < 0 ) {
				countParent = itemClass.indexOf( "ui-li-static" ) > 0 ? item : item.find( ".ui-link-inherit" );

				countParent.addClass( "ui-li-jsnumbering" )
					.prepend( "" + ( counter++ ) + ". " );
			}

			// Instead of setting item class directly on the list item and its
			// btn-inner at this point in time, push the item into a dictionary
			// that tells us what class to set on it so we can do this after this
			// processing loop is finished.

			if ( !itemClassDict[ itemClass ] ) {
				itemClassDict[ itemClass ] = [];
			}

			itemClassDict[ itemClass ].push( item[ 0 ] );
		}

		// Set the appropriate listview item classes on each list item
		// and their btn-inner elements. The main reason we didn't do this
		// in the for-loop above is because we can eliminate per-item function overhead
		// by calling addClass() and children() once or twice afterwards. This
		// can give us a significant boost on platforms like WP7.5.

		for ( itemClass in itemClassDict ) {
			$( itemClassDict[ itemClass ] ).addClass( itemClass ).children( ".ui-btn-inner" ).addClass( itemClass );
		}

		$list.find( "h1, h2, h3, h4, h5, h6" ).addClass( "ui-li-heading" )
			.end()

			.find( "p, dl" ).addClass( "ui-li-desc" )
			.end()

			.find( ".ui-li-aside" ).each(function() {
					var $this = $( this );
					$this.prependTo( $this.parent() ); //shift aside to front for css float
				})
			.end()

			.find( ".ui-li-count" ).each(function() {
					$( this ).closest( "li" ).addClass( "ui-li-has-count" );
				}).addClass( "ui-btn-up-" + ( getAttr( $list[ 0 ], "counttheme", true ) || this.options.countTheme) + " ui-btn-corner-all" );

		// The idea here is to look at the first image in the list item
		// itself, and any .ui-link-inherit element it may contain, so we
		// can place the appropriate classes on the image and list item.
		// Note that we used to use something like:
		//
		//    li.find(">img:eq(0), .ui-link-inherit>img:eq(0)").each( ... );
		//
		// But executing a find() like that on Windows Phone 7.5 took a
		// really long time. Walking things manually with the code below
		// allows the 400 listview item page to load in about 3 seconds as
		// opposed to 30 seconds.

		this._addThumbClasses( li );
		this._addThumbClasses( $list.find( ".ui-link-inherit" ) );

		this._addFirstLastClasses( li, this._getVisibles( li, create ), create );
		// autodividers binds to this to redraw dividers after the listview refresh
		this._trigger( "afterrefresh" );
	}}, $.mobile.behaviors.addFirstLastClasses ) );

$.mobile.listview.initSelector = ":jqmData(role='listview')";

//auto self-init widgets
$.mobile._enhancer.add( "mobile.listview" );

})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>//Language & messages configuration
//Note: also see /config/messages.json for further messages configuration
var lsmsg = {
    "defaultLanguage" : "en",
    "msgs": {
        "en":{
              privateMessage: 'Private',
              settings: 'Settings',
              uploadImagesTitle: 'Upload images or video.',
              uploadImagesTitleSorry: 'Sorry image uploads are only supported on IE10+, or any other browser.',
              sendTo: 'Send to',
              emoticonsTitle: 'Emoticons'
        },
        "es":{
              privateMessage: 'Privado',
              settings: 'Settings',
              uploadImagesTitle: 'Sube imágenes o vídeo.',
              uploadImagesTitleSorry: 'La subida de imágenes Lo siento, sólo se admiten en IE10+, o cualquier otro navegador.',
              sendTo: 'Enviar a',
              emoticonsTitle: 'Emoticonos'
        }
    }
}
var lang = lsmsg.defaultLanguage;

function myTrim(x)
{
	return x.replace(/^\s+|\s+$/gm,'');
}

function getCookie(cname)
{
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++)
	{
		var c = myTrim(ca[i]);// ie8 didn't support .trim();
		if (c.indexOf(name)==0) return c.substring(name.length,c.length);
	}
	return "";
}

function cookieOffset()
{
  //Should output: Thu,31-Dec-2020 00:00:00 GMT
  var cdate = new Date;
  var expirydate=new Date();
  expirydate.setTime(expirydate.getTime()+(365*3*60*60*24*1000))
  var write = expirydate.toGMTString();

  return write;
}

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1;
}

var commentLayer="comments";
var ssshoutFreq = 5000;
var ssshoutHasFocusOuter = true;
var myLoopTimeout;
var whisperOften = "1.1.1.1:2"; //defaults to admin user's ip and id
var cs = 2438974;
var ssshoutServer = "https://atomjump.com/api";  //https://atomjump.com/api  normally
var sameDomain = "atomjump.com";		//string in url to signify this is the same domain (for Safari cross-domain check)
var emailPlugin = "/plugins/shortmail/index.php";
var myUrl = window.location.href;
var emailCheck;
var cssFeedback = "";
var cssStrap = "";

function initAtomJumpFeedback(params)
{
	commentLayer = params.uniqueFeedbackId;
	whisperOften = params.myMachineUser;
	if(params.server){
	  ssshoutServer = params.server;
 }
 if(params.cssFeedback) {
   cssFeedback = params.cssFeedback;
 }
 if(params.cssBootstrap) {
   cssStrap = params.cssBootstrap;
 }

}

function updateEmail()
{
	//Check if any custom user/passwords which have been entered in this session
	var custom = "";
	if((typeof customUser !== 'undefined') && (typeof customPass !== 'undefined')) {
		custom = "&u=" + encodeURIComponent(customUser) + "&p=" + encodeURIComponent(customPass) + "&w=" + encodeURIComponent(customWhisper) + "&fe=" + encodeURIComponent(customFeed) + "&fr=" + customFreq + "&mail_id=" + customMailId;
	}

	//Run a refresh on the server side
	 jQuery.ajax({
		url: ssshoutServer + emailPlugin + "?callback=?",
		data: "refresh=" + commentLayer + custom,
		crossDomain: true,
		dataType: "jsonp"
	}).done(function(response) {
		//Refreshed
	});

}

function openPopup(_this, forumId)
{

		//Bring up a popup window (if Safari desktop only)
		//to ensure that we have the security permissions to set the session
		//from within the iframe. But only do this the first time (and
		//save this knowledge in a local cookie)
		//From then onwards, we just open all the way
		var isMacLike = navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) ? true:false;
		var is_safari = navigator.userAgent.indexOf("Safari") > -1;
		if(myUrl.indexOf(sameDomain) == -1) {
			if((is_safari) && (isMacLike == true)) {
				var firstView = getCookie("safari-first-view");
				if(!firstView) {
						var myWindow = window.open(ssshoutServer + "/init-sessions.php", "", "width=1,height=1");
						document.cookie = 'safari-first-view=false; path=/; expires=' + cookieOffset() + ';';
				}
			}
		}

		if(forumId) {
			//This is first option - we had it passed into the function
			commentLayer = forumId;

		}

		if(jQuery(_this).attr('id')) {
			//First base the forum name on an id
			commentLayer = jQuery(_this).attr('id');
		}

		if(jQuery(_this).data('uniquefeedbackid')) {
			//If we have a unique feedback id for this link in the data properties, rest the globals.
			commentLayer = jQuery(_this).data('uniquefeedbackid');
			whisperOften = jQuery(_this).data('mymachineuser');

			if(jQuery(_this).data('mailrefresh')) {
				updateEmail();

				emailCheck = setInterval("updateEmail();", 60000);

			}

		}

		//Dynamically readjust window to current screen height
		var screenWidth = jQuery(window).width();
		var screenHeight = jQuery(window).height();
		jQuery('#comment-popup-container').width(Math.floor(screenWidth) + "px");
		jQuery('#comment-popup-container').height(Math.floor(screenHeight) + "px");

		jQuery("#comment-in-here").html('');

		jQuery('#comment-popup-container').fadeIn(400,function(){

			var wid = (jQuery("#comment-in-here").width() - 5);		//5 is to ensure scroll bar always accounted for
			var hei = (jQuery("#comment-popup-text-container").height() - 10);

			jQuery("#comment-in-here").html('<iframe id="comment-iframe" src="' + ssshoutServer + '/search-secure.php?width=' + wid + '&height=' + hei + '&uniqueFeedbackId=' + commentLayer + '&myMachineUser=' + whisperOften + '&cssFeedback=' + encodeURIComponent(cssFeedback) + '&cssBootstrap=' + encodeURIComponent(cssStrap) + '&server=' + encodeURIComponent(ssshoutServer) + '&clientremoteurl=' + encodeURIComponent(myUrl) + '" frameBorder="0" scrolling="no" width="' + wid + '" height="' + hei + '" onload="jQuery(\'#comment-loading\').hide();" allowfullscreen>');

		});

}

//Run automatically
if(typeof ajFeedback !== 'undefined') {
	initAtomJumpFeedback(ajFeedback);
}

jQuery(document).ready(function() {
			var screenWidth = jQuery(window).width();
			var screenHeight = jQuery(window).height();
			var setLang = getCookie("lang");
			if(setLang) {
			    lang = setLang;
			}

			//If IE10 or above, or any other browser
			if(window.atob) {
				var uploadStr = '  ';
			} else {
				var uploadStr = '  ';
			}

			var emoticonsStr = '  ';

			jQuery("#comment-holder").html('
\

\

\
			 	  \

\
			 		 	\

\

\

\

\

\

\

\

\

\

\

\

\
				 			  Settings' + uploadStr + emoticonsStr + '      ' + lsmsg.msgs[lang].privateMessage + '\

\

\

\

');

				jQuery('a[href^="#comment-open-"]').click(function() {
					//First base the forum name on an href eg. #comment-open-forumname
					openPopup(this, this.href.split('#comment-open-')[1]);
				});

				jQuery('.comment-open').click(function() {
					//A more traditional class link click
					openPopup(this, null);

				});

				jQuery('#comment-close-popup').click(function() {
					//blank out the iframe, kicking in the onbeforeupdate event
					var iframe = document.getElementById('comment-iframe');
					iframe.parentNode.removeChild(iframe);

					if(emailCheck) {			//if we have a timer on the email
						clearTimeout(emailCheck);

					}

					jQuery("#comment-popup-container").fadeOut(400, function() {

						//Tell iframe to stop searching
						var ifr = document.getElementById('comment-iframe');
						if(ifr) {
							var receiver =  ifr.contentWindow;
							if(receiver) {
								receiver.postMessage('stop', ssshoutServer);
							}
						}

						jQuery("#comment-in-here").html('');

						jQuery("#comment-popup-container").hide();
						jQuery('#comment-holder').focus();
						jQuery('#comment-loading').show();
					});
					ssshoutHasFocusOuter = false;	//stop seekin new search terms;
					window.focus();

				});

				jQuery('#comment-options-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('toggle', ssshoutServer);

				});

				jQuery('#comment-upload-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('upload', ssshoutServer);

				});

				jQuery('#comment-emoji-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('emojis', ssshoutServer);

				});

				jQuery('#chat-input-block').append('<input' + ' type="hidden" ' + 'name="cs" ' + ' value="'+ cs + '">');

		});

function whisper(whisper_to, targetName)
{
	whisperOften = whisper_to;		//set global
	jQuery('#private-button').html(lsmsg.msgs[lang].sendTo + " " + targetName);

}

cs += 9585328;

cs += 124856;

cs += 9484320;

<commit_msg>works in wordpress<commit_after>//Language & messages configuration
//Note: also see /config/messages.json for further messages configuration
var lsmsg = {
    "defaultLanguage" : "en",
    "msgs": {
        "en":{
              privateMessage: 'Private',
              settings: 'Settings',
              uploadImagesTitle: 'Upload images or video.',
              uploadImagesTitleSorry: 'Sorry image uploads are only supported on IE10+, or any other browser.',
              sendTo: 'Send to',
              emoticonsTitle: 'Emoticons'
        },
        "es":{
              privateMessage: 'Privado',
              settings: 'Settings',
              uploadImagesTitle: 'Sube imágenes o vídeo.',
              uploadImagesTitleSorry: 'La subida de imágenes Lo siento, sólo se admiten en IE10+, o cualquier otro navegador.',
              sendTo: 'Enviar a',
              emoticonsTitle: 'Emoticonos'
        }
    }
}
var lang = lsmsg.defaultLanguage;

function myTrim(x)
{
	return x.replace(/^\s+|\s+$/gm,'');
}

function getCookie(cname)
{
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i<ca.length; i++)
	{
		var c = myTrim(ca[i]);// ie8 didn't support .trim();
		if (c.indexOf(name)==0) return c.substring(name.length,c.length);
	}
	return "";
}

function cookieOffset()
{
  //Should output: Thu,31-Dec-2020 00:00:00 GMT
  var cdate = new Date;
  var expirydate=new Date();
  expirydate.setTime(expirydate.getTime()+(365*3*60*60*24*1000))
  var write = expirydate.toGMTString();

  return write;
}

function isMacintosh() {
  return navigator.platform.indexOf('Mac') > -1;
}

var commentLayer="comments";
var ssshoutFreq = 5000;
var ssshoutHasFocusOuter = true;
var myLoopTimeout;
var whisperOften = "1.1.1.1:2"; //defaults to admin user's ip and id
var cs = 2438974;
var ssshoutServer = "https://atomjump.com/api";  //https://atomjump.com/api  normally
var sameDomain = "atomjump.com";		//string in url to signify this is the same domain (for Safari cross-domain check)
var emailPlugin = "/plugins/shortmail/index.php";
var myUrl = window.location.href;
var emailCheck;
var cssFeedback = "";
var cssStrap = "";

function initAtomJumpFeedback(params)
{
	commentLayer = params.uniqueFeedbackId;
	whisperOften = params.myMachineUser;
	if(params.server){
	  ssshoutServer = params.server;
 }
 if(params.cssFeedback) {
   cssFeedback = params.cssFeedback;
 }
 if(params.cssBootstrap) {
   cssStrap = params.cssBootstrap;
 }

}

function updateEmail()
{
	//Check if any custom user/passwords which have been entered in this session
	var custom = "";
	if((typeof customUser !== 'undefined') && (typeof customPass !== 'undefined')) {
		custom = "&u=" + encodeURIComponent(customUser) + "&p=" + encodeURIComponent(customPass) + "&w=" + encodeURIComponent(customWhisper) + "&fe=" + encodeURIComponent(customFeed) + "&fr=" + customFreq + "&mail_id=" + customMailId;
	}

	//Run a refresh on the server side
	 jQuery.ajax({
		url: ssshoutServer + emailPlugin + "?callback=?",
		data: "refresh=" + commentLayer + custom,
		crossDomain: true,
		dataType: "jsonp"
	}).done(function(response) {
		//Refreshed
	});

}

function openPopup(_this, forumId)
{

		//Bring up a popup window (if Safari desktop only)
		//to ensure that we have the security permissions to set the session
		//from within the iframe. But only do this the first time (and
		//save this knowledge in a local cookie)
		//From then onwards, we just open all the way
		var isMacLike = navigator.platform.match(/(Mac|iPhone|iPod|iPad)/i) ? true:false;
		var is_safari = navigator.userAgent.indexOf("Safari") > -1;
		if(myUrl.indexOf(sameDomain) == -1) {
			if((is_safari) && (isMacLike == true)) {
				var firstView = getCookie("safari-first-view");
				if(!firstView) {
						var myWindow = window.open(ssshoutServer + "/init-sessions.php", "", "width=1,height=1");
						document.cookie = 'safari-first-view=false; path=/; expires=' + cookieOffset() + ';';
				}
			}
		}

		if(forumId) {
			//This is first option - we had it passed into the function
			commentLayer = forumId;

		}

		if(jQuery(_this).attr('id')) {
			//First base the forum name on an id
			commentLayer = jQuery(_this).attr('id');
		}

		if(jQuery(_this).data('uniquefeedbackid')) {
			//If we have a unique feedback id for this link in the data properties, rest the globals.
			commentLayer = jQuery(_this).data('uniquefeedbackid');
			whisperOften = jQuery(_this).data('mymachineuser');

			if(jQuery(_this).data('mailrefresh')) {
				updateEmail();

				emailCheck = setInterval("updateEmail();", 60000);

			}

		}

		//Dynamically readjust window to current screen height
		var screenWidth = jQuery(window).width();
		var screenHeight = jQuery(window).height();
		jQuery('#comment-popup-container').width(Math.floor(screenWidth) + "px");
		jQuery('#comment-popup-container').height(Math.floor(screenHeight) + "px");

		jQuery("#comment-in-here").html('');

		jQuery('#comment-popup-container').fadeIn(400,function(){

			var wid = (jQuery("#comment-in-here").width() - 5);		//5 is to ensure scroll bar always accounted for
			var hei = (jQuery("#comment-popup-text-container").height() - 10);

			jQuery("#comment-in-here").html('<iframe id="comment-iframe" src="' + ssshoutServer + '/search-secure.php?width=' + wid + '&height=' + hei + '&uniqueFeedbackId=' + commentLayer + '&myMachineUser=' + whisperOften + '&cssFeedback=' + encodeURIComponent(cssFeedback) + '&cssBootstrap=' + encodeURIComponent(cssStrap) + '&server=' + encodeURIComponent(ssshoutServer) + '&clientremoteurl=' + encodeURIComponent(myUrl) + '" frameBorder="0" scrolling="no" width="' + wid + '" height="' + hei + '" onload="jQuery(\'#comment-loading\').hide();" allowfullscreen>');

		});

}

//Run automatically
if(typeof ajFeedback !== 'undefined') {
	initAtomJumpFeedback(ajFeedback);
}

jQuery(document).ready(function() {
			var screenWidth = jQuery(window).width();
			var screenHeight = jQuery(window).height();
			var setLang = getCookie("lang");
			if(setLang) {
			    lang = setLang;
			}

			//If IE10 or above, or any other browser
			if(window.atob) {
				var uploadStr = '  ';
			} else {
				var uploadStr = '  ';
			}

			var emoticonsStr = '  ';

			jQuery("#comment-holder").html('
\

\

\
			 	  \

\
			 		 	\

\

\

\

\

\

\

\

\

\

\

\

\
				 			  ' + lsmsg.msgs[lang].settings + '' + uploadStr + emoticonsStr + '      ' + lsmsg.msgs[lang].privateMessage + '\

\

\

\

');

				jQuery('a[href^="#comment-open-"]').click(function() {
					//First base the forum name on an href eg. #comment-open-forumname
					openPopup(this, this.href.split('#comment-open-')[1]);
				});

				jQuery('.comment-open').click(function() {
					//A more traditional class link click
					openPopup(this, null);

				});

				jQuery('#comment-close-popup').click(function() {
					//blank out the iframe, kicking in the onbeforeupdate event
					var iframe = document.getElementById('comment-iframe');
					iframe.parentNode.removeChild(iframe);

					if(emailCheck) {			//if we have a timer on the email
						clearTimeout(emailCheck);

					}

					jQuery("#comment-popup-container").fadeOut(400, function() {

						//Tell iframe to stop searching
						var ifr = document.getElementById('comment-iframe');
						if(ifr) {
							var receiver =  ifr.contentWindow;
							if(receiver) {
								receiver.postMessage('stop', ssshoutServer);
							}
						}

						jQuery("#comment-in-here").html('');

						jQuery("#comment-popup-container").hide();
						jQuery('#comment-holder').focus();
						jQuery('#comment-loading').show();
					});
					ssshoutHasFocusOuter = false;	//stop seekin new search terms;
					window.focus();

				});

				jQuery('#comment-options-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('toggle', ssshoutServer);

				});

				jQuery('#comment-upload-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('upload', ssshoutServer);

				});

				jQuery('#comment-emoji-popup').click(function() {
					//Tell iframe to switch content
					var receiver =  document.getElementById('comment-iframe').contentWindow;
					receiver.postMessage('emojis', ssshoutServer);

				});

				jQuery('#chat-input-block').append('<input' + ' type="hidden" ' + 'name="cs" ' + ' value="'+ cs + '">');

		});

function whisper(whisper_to, targetName)
{
	whisperOften = whisper_to;		//set global
	jQuery('#private-button').html(lsmsg.msgs[lang].sendTo + " " + targetName);

}

cs += 9585328;

cs += 124856;

cs += 9484320;

<|endoftext|>