<commit_before>// ephemeral.js
// scene where glitchy controls thrive
var QUARTER_CIRCLE_RADIANS = 1.57079633; // Math.PI / 2
var SCENE_HEIGHT = 1000;

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

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

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

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

  deviceControls = new THREE.DeviceOrientationControls( camera );

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

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

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

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

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

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

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

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

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

  startBalloons();
  makeHUD();
}

function animate() {

  requestAnimationFrame( animate );

  deviceControls.update();

  TWEEN.update();

  renderer.render( scene, camera );

}

function startBalloons () {
  setInterval(function() {

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

    } else {
      resetBalloon();
    }

  }, 500);
}

var lastBalloonReset = 0;
var balloons = [];

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

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

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

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

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

  balloons.push(mesh);

  scene.add(mesh);

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

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

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

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

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

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

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

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

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

  tween.easing(easing);

  tween.start();
}

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

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

    return result;
}

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

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

  event.preventDefault();

  console.log(event.keyCode);

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

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

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

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

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

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

var move = {
  forward: false,
  back: false,
  left: false,
  right: false
};

function onKeyDown (event) {
  switch(event.keyCode) {
    case 38: //Up
    move.forward = true;
    break;

    case 40: //Down
    move.back = true;
    break;

    case 39: //Right
    move.right = true;
    break;

    case 37: // left
    move.left = truel
    break;
  }
}

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

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

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

  var huds = [];

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

  var offset = 20;

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

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

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

  // huds.lookAt(camera.position);

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

init();
animate();
addKeyHandler();
<commit_msg>added movement controls<commit_after>// ephemeral.js
// scene where glitchy controls thrive
var QUARTER_CIRCLE_RADIANS = 1.57079633; // Math.PI / 2
var SCENE_HEIGHT = 1000;

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

var clock;

var lastBalloonReset = 0,
    balloons = [];

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

  clock = new THREE.Clock();

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

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

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

  camera.position.set( 0, 10, 0 );
  // camera.lookAt(scene.position);

  deviceControls = new THREE.DeviceOrientationControls( camera );

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

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

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

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

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

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

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

  startBalloons();
  makeHUD();
}

function animate() {

  requestAnimationFrame( animate );

  deviceControls.update();

  movementUpdate();

  TWEEN.update();

  renderer.render( scene, camera );

}

function startBalloons () {
  setInterval(function() {

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

    } else {
      resetBalloon();
    }

  }, 500);
}

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

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

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

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

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

  balloons.push(mesh);

  scene.add(mesh);

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

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

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

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

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

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

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

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

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

  tween.easing(easing);

  tween.start();
}

var move = {
  forward: false,
  back: false,
  left: false,
  right: false
};

function movementUpdate () {
  var delta = clock.getDelta(); // seconds.
	var moveDistance = 200 * delta; // 200 pixels / second
	var rotateAngle = Math.PI / 2 * delta;   // pi/2 radians (90 degrees) / second

  if (move.forward) {
    camera.translateZ( -moveDistance );
  }

  if (move.back) {
    camera.translateZ( moveDistance );
  }

  if (move.left) {
    camera.translateX( -moveDistance );
  }

  if (move.right) {
    camera.translateX( moveDistance );
  }

  if (move.up) {
    camera.translateY( moveDistance );
  }

  if (move.down) {
    camera.translateY( -moveDistance );
  }

}

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

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

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

  var huds = [];

  for (var i = 0; i < 6; i++) {
    huds[i] = new THREE.Mesh( geometry, material );
    huds[i].position.y =  100;
    scene.add(huds[i]);

  }

  var offset = 250;

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

  // huds[2].position.y =  100;
  // huds[3].position.y =  100;

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

  // huds.lookAt(camera.position);

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

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


<commit_before>'use strict';

var factoryModule = angular.module('uchiwa.factories', []);

factoryModule.factory('audit', function ($http, $rootScope) {
  return {
    log: function (payload) {
      if (!$rootScope.auth) {
        return;
      }
      return $http.post('audit', payload);
    }
  };
});

factoryModule.factory('authInterceptor', function ($cookieStore, $q, $location, userService) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      var user = $cookieStore.get('uchiwa_auth');
      var token = null;
      if (angular.isDefined(user)) {
        token = user.Token || null;
      }
      if (token) {
        config.headers.Authorization = 'Bearer ' + token;
      }
      return config;
    },
    responseError: function (rejection) {
      if (rejection.status === 401) {
        // handle the case where the user is not authenticated
        if ($location.path() !== '/login') {
          userService.logout();
          $location.path('login');
        }
      }
      return $q.reject(rejection);
    }
  };
});

/**
* Sensu Data
*/
factoryModule.factory('Sensu', function(backendService, conf, $interval) {
  var sensu = {aggregates: [], checks: [], client: {}, clients: [], events: [], stashes: [], subscriptions: []};

  return {
    getAggregates: function() {
      return sensu.aggregates;
    },
    getChecks: function() {
      return sensu.checks;
    },
    getClient: function() {
      return sensu.client;
    },
    getClients: function() {
      return sensu.clients;
    },
    getEvents: function() {
      return sensu.events;
    },
    getStashes: function() {
      return sensu.stashes;
    },
    getSubscriptions: function() {
      return sensu.subscriptions;
    },
    stop: function(timer) {
      $interval.cancel(timer);
    },
    updateAggregates: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getAggregates()
          .success(function (data) {
            sensu.aggregates = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateChecks: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getChecks()
          .success(function (data) {
            sensu.checks = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateClient: function(client, dc) {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getClient(client, dc)
          .success(function (data) {
            sensu.client = data;
          })
          .error(function(error) {
            sensu.client = null;
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateClients: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getClients()
          .success(function (data) {
            sensu.clients = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateEvents: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getEvents()
          .success(function (data) {
            sensu.events = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateStashes: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getStashes()
          .success(function (data) {
            sensu.stashes = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateSubscriptions: function() {
      backendService.getSubscriptions()
        .success(function (data) {
          sensu.subscriptions = data;
        })
        .error(function(error) {
          console.error(JSON.stringify(error));
        });
    }
  };
});

/**
* Page title
*/
factoryModule.factory('titleFactory', function() {
  var title = 'Uchiwa';
  return {
    get: function() { return title + ' | Uchiwa'; },
    set: function(newTitle) { title = newTitle; }
  };
});

/**
* Underscore.js
*/
factoryModule.factory('underscore', function () {
  if (angular.isUndefined(window._)) {
    console.log('underscore.js is required');
  } else {
    return window._;
  }
});
<commit_msg>Redirection to the login page should remove all query strings<commit_after>'use strict';

var factoryModule = angular.module('uchiwa.factories', []);

factoryModule.factory('audit', function ($http, $rootScope) {
  return {
    log: function (payload) {
      if (!$rootScope.auth) {
        return;
      }
      return $http.post('audit', payload);
    }
  };
});

factoryModule.factory('authInterceptor', function ($cookieStore, $q, $location, userService) {
  return {
    request: function (config) {
      config.headers = config.headers || {};
      var user = $cookieStore.get('uchiwa_auth');
      var token = null;
      if (angular.isDefined(user)) {
        token = user.Token || null;
      }
      if (token) {
        config.headers.Authorization = 'Bearer ' + token;
      }
      return config;
    },
    responseError: function (rejection) {
      if (rejection.status === 401) {
        // handle the case where the user is not authenticated
        if ($location.path() !== '/login') {
          userService.logout();
          $location.path('/login');
          $location.url($location.path());
        }
      }
      return $q.reject(rejection);
    }
  };
});

/**
* Sensu Data
*/
factoryModule.factory('Sensu', function(backendService, conf, $interval) {
  var sensu = {aggregates: [], checks: [], client: {}, clients: [], events: [], stashes: [], subscriptions: []};

  return {
    getAggregates: function() {
      return sensu.aggregates;
    },
    getChecks: function() {
      return sensu.checks;
    },
    getClient: function() {
      return sensu.client;
    },
    getClients: function() {
      return sensu.clients;
    },
    getEvents: function() {
      return sensu.events;
    },
    getStashes: function() {
      return sensu.stashes;
    },
    getSubscriptions: function() {
      return sensu.subscriptions;
    },
    stop: function(timer) {
      $interval.cancel(timer);
    },
    updateAggregates: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getAggregates()
          .success(function (data) {
            sensu.aggregates = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateChecks: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getChecks()
          .success(function (data) {
            sensu.checks = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateClient: function(client, dc) {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getClient(client, dc)
          .success(function (data) {
            sensu.client = data;
          })
          .error(function(error) {
            sensu.client = null;
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateClients: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getClients()
          .success(function (data) {
            sensu.clients = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateEvents: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getEvents()
          .success(function (data) {
            sensu.events = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateStashes: function() {
      var update = function() {
        backendService.getHealth();
        backendService.getMetrics();
        backendService.getStashes()
          .success(function (data) {
            sensu.stashes = data;
          })
          .error(function(error) {
            console.error(JSON.stringify(error));
          });
      };
      update();
      return $interval(update, conf.refresh);
    },
    updateSubscriptions: function() {
      backendService.getSubscriptions()
        .success(function (data) {
          sensu.subscriptions = data;
        })
        .error(function(error) {
          console.error(JSON.stringify(error));
        });
    }
  };
});

/**
* Page title
*/
factoryModule.factory('titleFactory', function() {
  var title = 'Uchiwa';
  return {
    get: function() { return title + ' | Uchiwa'; },
    set: function(newTitle) { title = newTitle; }
  };
});

/**
* Underscore.js
*/
factoryModule.factory('underscore', function () {
  if (angular.isUndefined(window._)) {
    console.log('underscore.js is required');
  } else {
    return window._;
  }
});
<|endoftext|>


<commit_before>function update_currentPath(newPath) {
  var rootname = newPath.split('/')[1];
  if (state.currentPath) {
      state.lastCurrentPath[rootname]=newPath;
  }
  state.currentPath = newPath;
  console.log(newPath.split('/').length);
  if (rootname === state.username) {
     showUpload();
  }
  else if (newPath.split('/').length > 2) {
     showUpload();
  }
  else {
     hideUpload();
  }
  update_path_nav();
  update_table();
}

function update_path_nav() {
  var pathFragments = state.currentPath.split("/");
  var aggregatedPath = "";
  var pathNav = $('#pathNav');
  pathNav.html('');
  for(var i = 1; i < pathFragments.length; i++) {
    aggregatedPath += "/" + pathFragments[i];
    var li = $('
').attr('data-path',aggregatedPath).text(pathFragments[i]);
    pathNav.append(li);
  }
  pathNav.children().click(function() {
    var path = $(this).attr("data-path");
    update_currentPath(path);
  });
}

function onPathNavClick(event) {
  var li = $(event.target).closest("li[data-path]",this);
  if (li.length==0) return; //did not click in a li item
  var path = li.attr("data-path");
  update_currentPath(path);
}

function onFileTableClick(event) {
  // TODO: check if it is a file or a directory
  var t = $(event.target);
  while (!t.is(this)) {
    if (t.is("tr")) break;
    if (t.is("table")) return;
    if (t.hasClass('delbtn')){
      return delItem(t.attr('data-path'));
    }
    if (t.hasClass('shareItem')) {
      return shareItem(t.attr('data-path'), t.attr('data-group'));
    }
    if (t.hasClass('dropdown')){
      return;
    }
    t = t.parent();
  }
  if (!t.parent().is("tbody")) {
    return;
  }
  if (t.children().length == 1) return;
  var currentDataIndex = t.find("div[data-index]").attr("data-index");
  if (elementIsDocument(currentListData[currentDataIndex].type)) {
    download(currentListData[currentDataIndex].path);
  } else {
    update_currentPath(currentListData[currentDataIndex].path);
  }
}

function download(path) {
  inpherapi_auth_get("/download", {fileName: path}, function(data, status, request){
    console.log(request);
    var blob = new Blob([data], {type: "txt"});
    saveAs(blob, "file.txt");
  })
}

function shareItem(path, group) {
  $('#createShareModal').modal("show");
  $('#createShareSubmit').on("click", function(){
    var shareName = $('#createShareName').val();
    inpherapiShareElement(path, group, shareName);
  })
}

function inpherapiShareElement(path, group, shareName) {
  var queryParam = {
    "groupName" : group,
    "filePath" : path,
    "shareName" : shareName,
  };
  inpherapi_auth_post("/shareElement", queryParam, function(data, status) {
    if (status === "success") {
      alert("success");
    }
  });
}

$(function () {
  // Load the table content
  state.currentPath = '/' + sessionStorage.getItem('username');
  state.username = sessionStorage.getItem('username');
  update_path_nav();
  init_table();
  $('#pathNav').click(onPathNavClick);
  $('#files').click(onFileTableClick);
});

function init_table() {
  $("#files").DataTable({'searching':false});
  update_table();
}

function update_table() {
  inpherapi_list(state.currentPath, function(data, status) {
    if (status !== "success") {
      alert("errror " + status);
    }
    currentListData = data.list;
    var table = $('#files').dataTable();
    table.fnClearTable();
    if (data.list.length > 0) {
      var tableData = [];
      for (var i = 0; i < data.list.length; i++) {
        tableData.push(inpherapi_list_res_to_row(data.list[i], i));
      }
      table.fnAddData(tableData);
    }
  });
}

/**
* This function returns the outerHTML jQuert element which is not connected to the DOM
* (Unpredictable behaviour if the element is in the DOM)
*/
function outerHTML(element) {
  var try1 = element[0].outerHTML;
  if (try1) return try1;
  return element.wrapAll('
').parent().html();
}

function inpherapi_list_res_to_row(a, i) {
  var delbtn = $('<button type="button" class="btn btn-danger btn-circle delbtn"></button>');
  delbtn.attr('data-path', a.path);
  return [
    outerHTML(fsElementIconAndNameHtml(a.type, a.path, i)),
    a.size,
    a.groups,
    outerHTML($("
").append(delbtn).append(createShareElementButton(a.path)))
  ];
}

function fsElementIconAndNameHtml(elementType, path, i) {
  var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  var reps = $('

');
  return reps.attr('data-index',i).prepend(fsElementTypeHtmlIcon(elementType)).append(document.createTextNode(name));
}

function elementIsDocument(elementType) {
  return elementType === "DOCUMENT";
}

function fsElementTypeHtmlIcon(elementType) {
  var reps=$('').addClass('fa');
  if (elementIsDocument(elementType)) {
    return reps.addClass('fa-file-text');
  } else {
    return reps.addClass('fa-folder');
  }
}

function createShareElementButton(path) {
  var dropdown = $("
").attr("class", "dropdown");
  var button = $("<button>").attr("class", "btn btn-primary btn-circle").attr("type", "button").attr("data-toggle", "dropdown");
  button.append('')
  dropdown.append(button);
  var listHtml = $("
");
  var listGroups = inpherListGroups();
  for(var i = 0; i < listGroups.length; i++) {
    var li = $("
").append(listGroups[i]);
    li.attr("data-group", listGroups[i]).attr("data-path", path);
    listHtml.append(li);
  }
  dropdown.append(listHtml);
  return dropdown;
}

function inpherListGroups() {
  return state.sharingGroupList;
}

function inpherapi_list(path, callback) {
  inpherapi_auth_get("/listDir", {dir: path}, callback);
}

function delItem(path) {
  return inpherapi_auth_delete('/delete', {path: path, recursive: true},update_table);
}

// ------------------------------------------------
// Upload shit below
function sendFileToServer(formData,status) {
  var options = {
    type: "POST",
    contentType:false,
    processData: false,
    cache: false,
    data: formData,
  };
  options.xhr = function() {
    var xhrobj = $.ajaxSettings.xhr();
    if (xhrobj.upload) {
      xhrobj.upload.addEventListener('progress', function(event) {
        var percent = 0;
        var position = event.loaded || event.position;
        var total = event.total;
        if (event.lengthComputable) {
          percent = Math.ceil(position / total * 100);
        }
        //Set progress
        status.setProgress(percent);
      }, false);
    }
    return xhrobj;
  };
  return inpherapi_auth_ajax('/upload', next1, options);
  function next1(data) {
    status.setProgress(100);
    $("#status1").append("File upload Done
");
    update_table(state.currentPath);
  }
}

var rowCount=0;
function createStatusbar(obj)
{
  rowCount++;
  var row="odd";
  if(rowCount %2 ==0) row ="even";
  this.statusbar = $("

");
  this.filename = $("

").appendTo(this.statusbar);
  this.size = $("

").appendTo(this.statusbar);
  this.progressBar = $("

").appendTo(this.statusbar);
  this.abort = $("
Abort
").appendTo(this.statusbar);
  obj.after(this.statusbar);

  this.setFileNameSize = function(name,size) {
    var sizeStr="";
    var sizeKB = size/1024;
    var sizeMB = sizeKB/1024;
    if(sizeMB > 1) {
      sizeStr = sizeMB.toFixed(2)+" MB";
    } else {
      sizeStr = sizeKB.toFixed(2)+" KB";
    }
    this.filename.text(name);
    this.size.text(sizeStr);
  };
  this.setProgress = function(progress) {
    var progressBarWidth =progress*this.progressBar.width()/ 100;
    this.progressBar.find('div').animate({ width: progressBarWidth }, 10).text(progress + "% ");
    if(parseInt(progress) >= 100)
    {
      this.abort.hide();
    }
  };
  this.setAbort = function(jqxhr) {
    var sb = this.statusbar;
    this.abort.click(function() {
      jqxhr.abort();
      sb.hide();
    });
  };
}

function handleFileUpload(files,obj) {
  for (var i = 0; i < files.length; i++) {
    var fd = new FormData();
    fd.append('content', files[i]);
    fd.append('name', state.currentPath + '/' + files[i].name);

    var status = new createStatusbar(obj); //Using this we can set progress.
    status.setFileNameSize(files[i].name,files[i].size);
    sendFileToServer(fd,status);
  }
}

function handleMkdir(event) {
  if (event.isDefaultPrevented()) {
    // TODO: failure
  } else {
    event.stopPropagation();
    event.preventDefault();
    var dirname = $("#mkdirname").val();
    inpherapi_auth_post('/mkdir', { dir: state.currentPath + "/"  + dirname }, update_table);
  }
}

$(function() {
  $("#mkdir-form").validator().submit(handleMkdir);

  var obj = $("#dragandrophandler");
  obj.on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
    obj.css('border', '2px solid #0B85A1');
  });
  obj.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  obj.on('drop', function (e) {
    obj.css('border', '2px dotted #0B85A1');
    e.preventDefault();
    var files = e.originalEvent.dataTransfer.files;

    //We need to send dropped files to Server
    handleFileUpload(files,obj);
  });
  var doc = $(document);
  doc.on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
    obj.css('border', '2px dotted #0B85A1');
  });
  doc.on('drop', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });

});
// ------------------------------------------------
// Upload shit above
// ------------------------------------------------
<commit_msg>Removed redoundant click action event handler on PathNav<commit_after>function update_currentPath(newPath) {
  var rootname = newPath.split('/')[1];
  if (state.currentPath) {
      state.lastCurrentPath[rootname]=newPath;
  }
  state.currentPath = newPath;
  console.log(newPath.split('/').length);
  if (rootname === state.username) {
     showUpload();
  }
  else if (newPath.split('/').length > 2) {
     showUpload();
  }
  else {
     hideUpload();
  }
  update_path_nav();
  update_table();
}

function update_path_nav() {
  var pathFragments = state.currentPath.split("/");
  var aggregatedPath = "";
  var pathNav = $('#pathNav');
  pathNav.html('');
  for(var i = 1; i < pathFragments.length; i++) {
    aggregatedPath += "/" + pathFragments[i];
    var li = $('
').attr('data-path',aggregatedPath).text(pathFragments[i]);
    pathNav.append(li);
  }
}

function onPathNavClick(event) {
  var li = $(event.target).closest("li[data-path]",this);
  if (li.length==0) return; //did not click in a li item
  var path = li.attr("data-path");
  update_currentPath(path);
}

function onFileTableClick(event) {
  // TODO: check if it is a file or a directory
  var t = $(event.target);
  while (!t.is(this)) {
    if (t.is("tr")) break;
    if (t.is("table")) return;
    if (t.hasClass('delbtn')){
      return delItem(t.attr('data-path'));
    }
    if (t.hasClass('shareItem')) {
      return shareItem(t.attr('data-path'), t.attr('data-group'));
    }
    if (t.hasClass('dropdown')){
      return;
    }
    t = t.parent();
  }
  if (!t.parent().is("tbody")) {
    return;
  }
  if (t.children().length == 1) return;
  var currentDataIndex = t.find("div[data-index]").attr("data-index");
  if (elementIsDocument(currentListData[currentDataIndex].type)) {
    download(currentListData[currentDataIndex].path);
  } else {
    update_currentPath(currentListData[currentDataIndex].path);
  }
}

function download(path) {
  inpherapi_auth_get("/download", {fileName: path}, function(data, status, request){
    console.log(request);
    var blob = new Blob([data], {type: "txt"});
    saveAs(blob, "file.txt");
  })
}

function shareItem(path, group) {
  $('#createShareModal').modal("show");
  $('#createShareSubmit').on("click", function(){
    var shareName = $('#createShareName').val();
    inpherapiShareElement(path, group, shareName);
  })
}

function inpherapiShareElement(path, group, shareName) {
  var queryParam = {
    "groupName" : group,
    "filePath" : path,
    "shareName" : shareName,
  };
  inpherapi_auth_post("/shareElement", queryParam, function(data, status) {
    if (status === "success") {
      alert("success");
    }
  });
}

$(function () {
  // Load the table content
  state.currentPath = '/' + sessionStorage.getItem('username');
  state.username = sessionStorage.getItem('username');
  update_path_nav();
  init_table();
  $('#pathNav').click(onPathNavClick);
  $('#files').click(onFileTableClick);
});

function init_table() {
  $("#files").DataTable({'searching':false});
  update_table();
}

function update_table() {
  inpherapi_list(state.currentPath, function(data, status) {
    if (status !== "success") {
      alert("errror " + status);
    }
    currentListData = data.list;
    var table = $('#files').dataTable();
    table.fnClearTable();
    if (data.list.length > 0) {
      var tableData = [];
      for (var i = 0; i < data.list.length; i++) {
        tableData.push(inpherapi_list_res_to_row(data.list[i], i));
      }
      table.fnAddData(tableData);
    }
  });
}

/**
* This function returns the outerHTML jQuert element which is not connected to the DOM
* (Unpredictable behaviour if the element is in the DOM)
*/
function outerHTML(element) {
  var try1 = element[0].outerHTML;
  if (try1) return try1;
  return element.wrapAll('
').parent().html();
}

function inpherapi_list_res_to_row(a, i) {
  var delbtn = $('<button type="button" class="btn btn-danger btn-circle delbtn"></button>');
  delbtn.attr('data-path', a.path);
  return [
    outerHTML(fsElementIconAndNameHtml(a.type, a.path, i)),
    a.size,
    a.groups,
    outerHTML($("
").append(delbtn).append(createShareElementButton(a.path)))
  ];
}

function fsElementIconAndNameHtml(elementType, path, i) {
  var name = path.substring(path.lastIndexOf("/") + 1, path.length);
  var reps = $('

');
  return reps.attr('data-index',i).prepend(fsElementTypeHtmlIcon(elementType)).append(document.createTextNode(name));
}

function elementIsDocument(elementType) {
  return elementType === "DOCUMENT";
}

function fsElementTypeHtmlIcon(elementType) {
  var reps=$('').addClass('fa');
  if (elementIsDocument(elementType)) {
    return reps.addClass('fa-file-text');
  } else {
    return reps.addClass('fa-folder');
  }
}

function createShareElementButton(path) {
  var dropdown = $("
").attr("class", "dropdown");
  var button = $("<button>").attr("class", "btn btn-primary btn-circle").attr("type", "button").attr("data-toggle", "dropdown");
  button.append('')
  dropdown.append(button);
  var listHtml = $("
");
  var listGroups = inpherListGroups();
  for(var i = 0; i < listGroups.length; i++) {
    var li = $("
").append(listGroups[i]);
    li.attr("data-group", listGroups[i]).attr("data-path", path);
    listHtml.append(li);
  }
  dropdown.append(listHtml);
  return dropdown;
}

function inpherListGroups() {
  return state.sharingGroupList;
}

function inpherapi_list(path, callback) {
  inpherapi_auth_get("/listDir", {dir: path}, callback);
}

function delItem(path) {
  return inpherapi_auth_delete('/delete', {path: path, recursive: true},update_table);
}

// ------------------------------------------------
// Upload shit below
function sendFileToServer(formData,status) {
  var options = {
    type: "POST",
    contentType:false,
    processData: false,
    cache: false,
    data: formData,
  };
  options.xhr = function() {
    var xhrobj = $.ajaxSettings.xhr();
    if (xhrobj.upload) {
      xhrobj.upload.addEventListener('progress', function(event) {
        var percent = 0;
        var position = event.loaded || event.position;
        var total = event.total;
        if (event.lengthComputable) {
          percent = Math.ceil(position / total * 100);
        }
        //Set progress
        status.setProgress(percent);
      }, false);
    }
    return xhrobj;
  };
  return inpherapi_auth_ajax('/upload', next1, options);
  function next1(data) {
    status.setProgress(100);
    $("#status1").append("File upload Done
");
    update_table(state.currentPath);
  }
}

var rowCount=0;
function createStatusbar(obj)
{
  rowCount++;
  var row="odd";
  if(rowCount %2 ==0) row ="even";
  this.statusbar = $("

");
  this.filename = $("

").appendTo(this.statusbar);
  this.size = $("

").appendTo(this.statusbar);
  this.progressBar = $("

").appendTo(this.statusbar);
  this.abort = $("
Abort
").appendTo(this.statusbar);
  obj.after(this.statusbar);

  this.setFileNameSize = function(name,size) {
    var sizeStr="";
    var sizeKB = size/1024;
    var sizeMB = sizeKB/1024;
    if(sizeMB > 1) {
      sizeStr = sizeMB.toFixed(2)+" MB";
    } else {
      sizeStr = sizeKB.toFixed(2)+" KB";
    }
    this.filename.text(name);
    this.size.text(sizeStr);
  };
  this.setProgress = function(progress) {
    var progressBarWidth =progress*this.progressBar.width()/ 100;
    this.progressBar.find('div').animate({ width: progressBarWidth }, 10).text(progress + "% ");
    if(parseInt(progress) >= 100)
    {
      this.abort.hide();
    }
  };
  this.setAbort = function(jqxhr) {
    var sb = this.statusbar;
    this.abort.click(function() {
      jqxhr.abort();
      sb.hide();
    });
  };
}

function handleFileUpload(files,obj) {
  for (var i = 0; i < files.length; i++) {
    var fd = new FormData();
    fd.append('content', files[i]);
    fd.append('name', state.currentPath + '/' + files[i].name);

    var status = new createStatusbar(obj); //Using this we can set progress.
    status.setFileNameSize(files[i].name,files[i].size);
    sendFileToServer(fd,status);
  }
}

function handleMkdir(event) {
  if (event.isDefaultPrevented()) {
    // TODO: failure
  } else {
    event.stopPropagation();
    event.preventDefault();
    var dirname = $("#mkdirname").val();
    inpherapi_auth_post('/mkdir', { dir: state.currentPath + "/"  + dirname }, update_table);
  }
}

$(function() {
  $("#mkdir-form").validator().submit(handleMkdir);

  var obj = $("#dragandrophandler");
  obj.on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
    obj.css('border', '2px solid #0B85A1');
  });
  obj.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  obj.on('drop', function (e) {
    obj.css('border', '2px dotted #0B85A1');
    e.preventDefault();
    var files = e.originalEvent.dataTransfer.files;

    //We need to send dropped files to Server
    handleFileUpload(files,obj);
  });
  var doc = $(document);
  doc.on('dragenter', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });
  doc.on('dragover', function (e) {
    e.stopPropagation();
    e.preventDefault();
    obj.css('border', '2px dotted #0B85A1');
  });
  doc.on('drop', function (e) {
    e.stopPropagation();
    e.preventDefault();
  });

});
// ------------------------------------------------
// Upload shit above
// ------------------------------------------------
<|endoftext|>


<commit_before>
window.editor = {};

//TODO, let users pick their nicknames or get it from a cookie or something.
var clientID = Math.floor((Math.random() * 10000000));

(function($, ShowDown, CodeMirror) {
	"use strict";

	$(function() {

		if (!document.getElementById('entry-markdown'))
			return;

		//var delay;
		var converter = new ShowDown.converter();
		window.editor = CodeMirror.fromTextArea(document.getElementById('entry-markdown'), {
			mode: 'markdown',
			tabMode: 'indent',
			lineWrapping: true
		});
		// window.timestamps = CodeMirror.fromTextArea(document.getElementById('entry-timestamp'), {
		// 	mode: 'markdown',
		// 	tabMode: 'indent',
		// 	lineWrapping: true
		// });

		// Really not the best way to do things as it includes Markdown formatting along with words
		function updateWordCount() {
			var wordCount = document.getElementsByClassName('entry-word-count')[0],
				editorValue = window.editor.getValue();

			if (editorValue.length) {
				wordCount.innerHTML = editorValue.match(/\S+/g).length + ' words';
			}
		}

		function updateImagePlaceholders(content) {
			var imgPlaceholders = $(document.getElementsByClassName('rendered-markdown')[0]).find('p').filter(function() {
				return (/^(?:\{<(.*?)>\})?!(?:\[([^\n\]]*)\])(?:\(([^\n\]]*)\))?$/gim).test($(this).text());
			});

			$(imgPlaceholders).each(function( index ) {

				var elemindex = index,
					self = $(this),
					altText = self.text();

				(function(){

					self.dropzone({
						url: "/article/imgupload",
						success: function( file, response ){
							var holderP = $(file.previewElement).closest("p"),

								// Update the image path in markdown
								imgHolderMardown = $(".CodeMirror-code").find('pre').filter(function() {
							    	return (/^(?:\{<(.*?)>\})?!(?:\[([^\n\]]*)\])(?:\(([^\n\]]*)\))?$/gim).test(self.text()) && (self.find("span").length === 0);
								}),

								// Get markdown
								editorOrigVal = window.editor.getValue(),
								nth = 0,
								newMarkdown = editorOrigVal.replace(/^(?:\{<(.*?)>\})?!(?:\[([^\n\]]*)\])(:\(([^\n\]]*)\))?$/gim, function (match, i, original){
									nth++;
									return (nth === (elemindex+1)) ? (match + "(" + response.path +")") : match;
								});
								window.editor.setValue( newMarkdown );

							// Set image instead of placeholder
							holderP.removeClass("dropzone").html('<img src="'+ response.path +'"/>');
						}
					}).addClass("dropzone");
				}());
			})
		}

		function updatePreview() {
			var preview = document.getElementsByClassName('rendered-markdown')[0];
			preview.innerHTML = converter.makeHtml(window.editor.getValue());

			updateImagePlaceholders(preview.innerHTML);
			updateWordCount();
		}

		$(document).ready(function() {
			$('.entry-markdown header, .entry-preview header').click(function(e) {
				$('.entry-markdown, .entry-preview').removeClass('active');
				$(e.target).closest('section').addClass('active');
			});

			window.editor.on ("change", function () {
				updatePreview();
			});

			updatePreview();

			// Sync scrolling
			function syncScroll(e) {
				// vars
				var $codeViewport = $(e.target),
					$previewViewport = $('.entry-preview-content'),
					$codeContent = $('.CodeMirror-sizer'),
					$previewContent = $('.rendered-markdown'),

					// calc position
					codeHeight = $codeContent.height() - $codeViewport.height(),
					previewHeight = $previewContent.height() - $previewViewport.height(),
					ratio = previewHeight / codeHeight,
					previewPostition = $codeViewport.scrollTop() * ratio;

				// apply new scroll
				$previewViewport.scrollTop(previewPostition);
			}

			// TODO: Debounce
			$('.CodeMirror-scroll').on('scroll', syncScroll);

			// Shadow on Markdown if scrolled
			$('.CodeMirror-scroll').scroll(function() {
				if ($('.CodeMirror-scroll').scrollTop() > 10) {
					$('.entry-markdown').addClass('scrolling');
				} else {
					$('.entry-markdown').removeClass('scrolling');
				}
			});
			// Shadow on Preview if scrolled
			$('.entry-preview-content').scroll(function() {
				if ($('.entry-preview-content').scrollTop() > 10) {
					$('.entry-preview').addClass('scrolling');
				} else {
					$('.entry-preview').removeClass('scrolling');
				}
			});

		});
	});
}(jQuery, Showdown, CodeMirror));

$('#format-bold').click (function () {
	Format.bold ();
});

$('#format-italic').click (function () {
	Format.italic ();
});

$('#format-code').click (function () {
	Format.code ();
});

//
// Takes care of text formatting via the use of the button toolbar located on the page
//
var Format = Format || {};

Format.replace = function (replacement) {
	position_cursor = typeof position_cursor === "undefined" ? false : true;
	window.editor.replaceSelection (replacement);
}

Format.bold = function () {
	Format.replace (Format.wrapper ('**'));
}

Format.italic = function () {
	Format.replace (Format.wrapper ('_'));
}

Format.code = function () {
	Format.replace (Format.mlWrapper ('`', '```'));
}

Format.wrapper = function (characters) {
	if (window.editor.somethingSelected ()) {
		var selection = window.editor.getSelection ('\n');

		//wrap lines individually.
		if (/\n/.test(selection)) {
			console.log(selection);
			return selection.split("\n").map(Format.wrapText(characters)).join("\n");
		}

		//if there's not multiple lines, just deal with the one.
		else {
			return Format.wrapText(characters)(selection);
		}
	}
	else {
		var index = window.editor.indexFromPos (window.editor.getCursor ());
		window.editor.replaceSelection (characters + characters);
		window.editor.setCursor (window.editor.posFromIndex (index + 2));
	}
}

Format.wrapText = function (characters) {
	return function (selection) {
		if (/^\s*$/.test(selection)) {
			return selection;
		}
		else { console.log("'", selection, "'"); }
		//Regex that picks apart the different pieces of the format.
		var re = new RegExp("(.*)" + escapeRegExp(characters) + "(.*)" +
				escapeRegExp(characters) + "(.*)");
		//test if the format is already applied:
		if (re.test(selection)) {
			return re.exec(selection).slice(1, 4).join("");
		} else {
			return (characters + selection + characters);
		}
	}
}

Format.mlWrapper = function (characters, mlCharacters) {
	if (window.editor.somethingSelected()) {
		var selection = window.editor.getSelection('\n');
		if (/\n/.test(selection)) {
			var re = new RegExp("([\\s\\S]*)" + escapeRegExp(mlCharacters) + "\\n([\\s\\S]*)\\n" +
				escapeRegExp(mlCharacters) + "([\\s\\S]*)");
			if (re.test(selection)) {
				return re.exec(selection).slice(1, 4).join("");
			}
			else {
				return mlCharacters + "\n" + selection + "\n" + mlCharacters;
			}
		}
		else {
			return Format.wrapper (characters);
		}
	}}

/*
 * Ripped out of a stack overvlow thread
 * See http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
 * Escapes all the necessary special chars for regex
 */
function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

//
// Opens socket, establishes connection to pad based on url location hash
//
var pad_id = location.hash;
if (pad_id == '') {
	// Using default hash
	pad_id = "The Dark Side";
}

var socket = new BCSocket (null, { reconnect: true });
var share  = new window.sharejs.Connection (socket);
var pad    = share.get ('users', pad_id);

pad.subscribe ();

pad.whenReady (function () {
  	if (!pad.type) pad.create ('text');
	if (pad.type && pad.type.name === 'text') {
		pad.attachCodeMirror (window.editor);
  	}
});

//
// Chat functionality
//
function addMessage(message) {
	console.log(message);
	var classes = "chat-message";

	if (message.client == clientID) {
		classes += " bubble-mine animated bounceIn";
	} else {
		classes += " bubble-other animated bounceIn";
	}

	chatdiv = $('<div>').addClass(classes).text(message.message);
	$('.chat-pane').append(chatdiv);
}

var chat = io(window.location.host + '/chat', function() { chat.emit('subscribe', pad_id)});
chat.emit('subscribe', pad_id);
chat.on('message', addMessage);

$('#chat-message').keypress (function (event) {
    if (event.keyCode == 13) {
		message = $('#chat-message').val();
		message = {pad_id: pad_id, client: clientID, message: message};

		chat.emit ('message', message);
		addMessage (message);

		$('#chat-message').val ('');
		return false;
    }
});
<commit_msg>Cleanup on ghostdown.js<commit_after>
window.editor = {};

//TODO, let users pick their nicknames or get it from a cookie or something.
var clientID = Math.floor((Math.random() * 10000000));

(function($, ShowDown, CodeMirror) {
	"use strict";

	$(function() {

		if (!document.getElementById('entry-markdown'))
			return;

		//var delay;
		var converter = new ShowDown.converter();
		window.editor = CodeMirror.fromTextArea(document.getElementById('entry-markdown'), {
			mode: 'markdown',
			tabMode: 'indent',
			lineWrapping: true
		});
		// window.timestamps = CodeMirror.fromTextArea(document.getElementById('entry-timestamp'), {
		// 	mode: 'markdown',
		// 	tabMode: 'indent',
		// 	lineWrapping: true
		// });

		// Really not the best way to do things as it includes Markdown formatting along with words
		function updateWordCount() {
			var wordCount = document.getElementsByClassName('entry-word-count')[0],
				editorValue = window.editor.getValue();

			if (editorValue.length) {
				wordCount.innerHTML = editorValue.match(/\S+/g).length + ' words';
			}
		}

		function updateImagePlaceholders(content) {
			var imgPlaceholders = $(document.getElementsByClassName('rendered-markdown')[0]).find('p').filter(function() {
				return (/^(?:\{<(.*?)>\})?!(?:\[([^\n\]]*)\])(?:\(([^\n\]]*)\))?$/gim).test($(this).text());
			});

			$(imgPlaceholders).each(function( index ) {

				var elemindex = index,
					self = $(this),
					altText = self.text();

				(function(){

					self.dropzone({
						url: "/article/imgupload",
						success: function( file, response ){
							var holderP = $(file.previewElement).closest("p"),

								// Update the image path in markdown
								imgHolderMardown = $(".CodeMirror-code").find('pre').filter(function() {
							    	return (/^(?:\{<(.*?)>\})?!(?:\[([^\n\]]*)\])(?:\(([^\n\]]*)\))?$/gim).test(self.text()) && (self.find("span").length === 0);
								}),

								// Get markdown
								editorOrigVal = window.editor.getValue(),
								nth = 0,
								newMarkdown = editorOrigVal.replace(/^(?:\{<(.*?)>\})?!(?:\[([^\n\]]*)\])(:\(([^\n\]]*)\))?$/gim, function (match, i, original){
									nth++;
									return (nth === (elemindex+1)) ? (match + "(" + response.path +")") : match;
								});
								window.editor.setValue( newMarkdown );

							// Set image instead of placeholder
							holderP.removeClass("dropzone").html('<img src="'+ response.path +'"/>');
						}
					}).addClass("dropzone");
				}());
			})
		}

		function updatePreview() {
			var preview = document.getElementsByClassName('rendered-markdown')[0];
			preview.innerHTML = converter.makeHtml(window.editor.getValue());

			updateImagePlaceholders(preview.innerHTML);
			updateWordCount();
		}

		$(document).ready(function() {
			$('.entry-markdown header, .entry-preview header').click(function(e) {
				$('.entry-markdown, .entry-preview').removeClass('active');
				$(e.target).closest('section').addClass('active');
			});

			window.editor.on ("change", function () {
				updatePreview();
			});

			updatePreview();

			// Sync scrolling
			function syncScroll(e) {
				// vars
				var $codeViewport = $(e.target),
					$previewViewport = $('.entry-preview-content'),
					$codeContent = $('.CodeMirror-sizer'),
					$previewContent = $('.rendered-markdown'),

					// calc position
					codeHeight = $codeContent.height() - $codeViewport.height(),
					previewHeight = $previewContent.height() - $previewViewport.height(),
					ratio = previewHeight / codeHeight,
					previewPostition = $codeViewport.scrollTop() * ratio;

				// apply new scroll
				$previewViewport.scrollTop(previewPostition);
			}

			// TODO: Debounce
			$('.CodeMirror-scroll').on('scroll', syncScroll);

			// Shadow on Markdown if scrolled
			$('.CodeMirror-scroll').scroll(function() {
				if ($('.CodeMirror-scroll').scrollTop() > 10) {
					$('.entry-markdown').addClass('scrolling');
				} else {
					$('.entry-markdown').removeClass('scrolling');
				}
			});
			// Shadow on Preview if scrolled
			$('.entry-preview-content').scroll(function() {
				if ($('.entry-preview-content').scrollTop() > 10) {
					$('.entry-preview').addClass('scrolling');
				} else {
					$('.entry-preview').removeClass('scrolling');
				}
			});

		});
	});
}(jQuery, Showdown, CodeMirror));

$('#format-bold').click (function () {
	Format.bold ();
});

$('#format-italic').click (function () {
	Format.italic ();
});

$('#format-code').click (function () {
	Format.code ();
});

//
// Takes care of text formatting via the use of the button toolbar located on the page
//
var Format = Format || {};

Format.replace = function (replacement) {
	position_cursor = typeof position_cursor === "undefined" ? false : true;
	window.editor.replaceSelection (replacement);
}

Format.bold = function () {
	Format.replace (Format.wrapper ('**'));
}

Format.italic = function () {
	Format.replace (Format.wrapper ('_'));
}

Format.code = function () {
	Format.replace (Format.mlWrapper ('`', '```'));
}

/*
 * wraps the selection in the characters specified.
 * also handles the multi-line case, wrapping each individual line in said
 * characters.
 */
Format.wrapper = function (characters) {
	if (window.editor.somethingSelected ()) {
		var selection = window.editor.getSelection ('\n');

		//wrap lines individually.
		if (/\n/.test(selection)) {
			return selection.split("\n").map(Format.wrapText(characters)).join("\n");
		}

		//if there's not multiple lines, just deal with the one.
		else {
			return Format.wrapText(characters)(selection);
		}
	}
	else {
		var index = window.editor.indexFromPos (window.editor.getCursor ());
		window.editor.replaceSelection (characters + characters);
		window.editor.setCursor (window.editor.posFromIndex (index + 2));
	}
}

/*
 * Returns a function that wraps the text in the characters specified.
 */
Format.wrapText = function (characters) {
	return function (selection) {
		if (/^\s*$/.test(selection)) {
			return selection;
		}
		else { console.log("'", selection, "'"); }
		//Regex that picks apart the different pieces of the format.
		var re = new RegExp("(.*)" + escapeRegExp(characters) + "(.*)" +
				escapeRegExp(characters) + "(.*)");
		//test if the format is already applied:
		if (re.test(selection)) {
			return re.exec(selection).slice(1, 4).join("");
		} else {
			return (characters + selection + characters);
		}
	}
}

/*
 * Multiline wrapper. Inserts mlCharacters on new lines at beginning and end of
 * the selection, or just characters at the beginnign and end of the line if
 * only one line is selected.
 */
Format.mlWrapper = function (characters, mlCharacters) {
	if (window.editor.somethingSelected()) {
		var selection = window.editor.getSelection('\n');
		if (/\n/.test(selection)) {
			var re = new RegExp("([\\s\\S]*)" + escapeRegExp(mlCharacters) + "\\n([\\s\\S]*)\\n" +
				escapeRegExp(mlCharacters) + "([\\s\\S]*)");
			if (re.test(selection)) {
				return re.exec(selection).slice(1, 4).join("");
			}
			else {
				return mlCharacters + "\n" + selection + "\n" + mlCharacters;
			}
		}
		else {
			return Format.wrapper (characters);
		}
	}
}

/*
 * Ripped out of a stack overvlow thread
 * See http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex
 * Escapes all the necessary special chars for regex
 */
function escapeRegExp(str) {
  return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}

//
// Opens socket, establishes connection to pad based on url location hash
//
var pad_id = location.hash;
if (pad_id == '') {
	// Using default hash
	pad_id = "The Dark Side";
}

var socket = new BCSocket (null, { reconnect: true });
var share  = new window.sharejs.Connection (socket);
var pad    = share.get ('users', pad_id);

pad.subscribe ();

pad.whenReady (function () {
  	if (!pad.type) pad.create ('text');
	if (pad.type && pad.type.name === 'text') {
		pad.attachCodeMirror (window.editor);
  	}
});

//
// Chat functionality
//
function addMessage(message) {
	console.log(message);
	var classes = "chat-message";

	if (message.client == clientID) {
		classes += " bubble-mine animated bounceIn";
	} else {
		classes += " bubble-other animated bounceIn";
	}

	chatdiv = $('<div>').addClass(classes).text(message.message);
	$('.chat-pane').append(chatdiv);
}

var chat = io(window.location.host + '/chat', function() { chat.emit('subscribe', pad_id)});
chat.emit('subscribe', pad_id);
chat.on('message', addMessage);

$('#chat-message').keypress (function (event) {
    if (event.keyCode == 13) {
		message = $('#chat-message').val();
		message = {pad_id: pad_id, client: clientID, message: message};

		chat.emit ('message', message);
		addMessage (message);

		$('#chat-message').val ('');
		return false;
    }
});
<|endoftext|>


<commit_before>var map;

var markers = [];
var iterator = 0;

var neighborhoods = [
  new google.maps.LatLng(37.38245144310285, 126.66660189628601), //기숙사 앞
  new google.maps.LatLng(37.381377267809434, 126.6685438156128),  //송도 셔틀
  new google.maps.LatLng(37.38756635245252, 126.66251420974731),  //송도 지하철역
  new google.maps.LatLng(37.3841735015448, 126.66866183280945) // 약대 귀양지
];

function initialize() {
  var mapOptions = {
    zoom: 16,
    center: new google.maps.LatLng(37.38519648783452, 126.66671991348267),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  /*google.maps.event.addListener(map, 'click', function(e) {
    placeMarker(e.latLng, map);
  });
  */
  drop();
}

google.maps.event.addDomListener(window, 'load', initialize);

function placeMarker(position, map) {
  var marker = new google.maps.Marker({
    position: position,
    map: map
  });
  console.log(position);
  map.panTo(position);
}

function drop() {
  for (var i = 0; i < neighborhoods.length; i++) {
    setTimeout(function() {
      addMarker();
    }, i * 200);
  }
}

function addMarker() {
  var marker = new google.maps.Marker({
    position: neighborhoods[iterator],
    map: map,
    draggable: false,
    animation: google.maps.Animation.DROP
  });
  google.maps.event.addListener(marker, 'click', function(e) {
    toggleBounce(marker);
  });
  markers.push(marker);

  iterator++;
}

function toggleBounce(marker) {

  if (marker.getAnimation() != null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}<commit_msg>googlemap.js에 geolocation 정보 받아 오는거 추가<commit_after>var map;

var markers = [];
var iterator = 0;

var neighborhoods = [
  new google.maps.LatLng(37.38245144310285, 126.66660189628601), //기숙사 앞
  new google.maps.LatLng(37.381377267809434, 126.6685438156128),  //송도 셔틀
  new google.maps.LatLng(37.38756635245252, 126.66251420974731),  //송도 지하철역
  new google.maps.LatLng(37.3841735015448, 126.66866183280945) // 약대 귀양지
];

function initialize() {

  if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
          alert('it works');
      }, function(error) {
          alert('Error occurred. Error code: ' + error.code);
      },{timeout:50000});
  }else{
      alert('no geolocation support');
  }

  var mapOptions = {
    zoom: 16,
    center: new google.maps.LatLng(37.38519648783452, 126.66671991348267),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById('map-canvas'),
      mapOptions);

  /*google.maps.event.addListener(map, 'click', function(e) {
    placeMarker(e.latLng, map);
  });
  */
  drop();
}

google.maps.event.addDomListener(window, 'load', initialize);

function placeMarker(position, map) {
  var marker = new google.maps.Marker({
    position: position,
    map: map
  });
  console.log(position);
  map.panTo(position);
}

function drop() {
  for (var i = 0; i < neighborhoods.length; i++) {
    setTimeout(function() {
      addMarker();
    }, i * 200);
  }
}

function addMarker() {
  var marker = new google.maps.Marker({
    position: neighborhoods[iterator],
    map: map,
    draggable: false,
    animation: google.maps.Animation.DROP
  });
  google.maps.event.addListener(marker, 'click', function(e) {
    toggleBounce(marker);
  });
  markers.push(marker);

  iterator++;
}

function toggleBounce(marker) {

  if (marker.getAnimation() != null) {
    marker.setAnimation(null);
  } else {
    marker.setAnimation(google.maps.Animation.BOUNCE);
  }
}<|endoftext|>


<commit_before>const svg = d3.select('svg');
let activeFacet = 'domain';
const colourRangeMax = 8000;

const colorScale = d3.scaleLinear().domain([1,colourRangeMax])
  .interpolate(d3.interpolateHcl)
  .range([d3.rgb("#f00"), d3.rgb('#0f0')]);

function changeFacet(facet) {
  activeFacet = facet;
  updateData(data);
  $('#facet-menu .item').removeClass('active');
  $('#facet-menu .item.' + facet).addClass('active');
}

function colourByFilter(d) {
  if (activeFacet == 'original') {
    $('.ad-grid').addClass('coloured');
    return 'rgba(0,0,0,0)'

  } else if (activeFacet == 'cost') {
    $('.ad-grid').removeClass('coloured');
    width = d.coords.split(",")[2] - d.coords.split(",")[0];
    height = d.coords.split(",")[3] - d.coords.split(",")[1];
    size = width * height;
    return colorScale(size);

  } else if (activeFacet == 'registration') {
    $('.ad-grid').removeClass('coloured');
    if (d.title.toLowerCase().startsWith('reserved for')) {
      return colorScale(colourRangeMax - 2000);
    }
    if (d.title == 'Pending Order') {
      return colorScale(colourRangeMax - 5000);
    } else if (d.title == 'Link Suspended') {
      return colorScale(0);
    } else {
      return colorScale(colourRangeMax);
    }

  } else if (activeFacet == 'domain') {
    $('.ad-grid').removeClass('coloured');
    if (d.response.squatter == true) {
      return colorScale(colourRangeMax - 5000);
    } else if (d.response.redirected) {
      return colorScale(colourRangeMax - 3000);
    } else if (d.response.status == 200) {
      return colorScale(colourRangeMax);
    } else if (d.response.status >= 400) {
      return colorScale(1000);
    } else if (d.response.error) {
      return colorScale(0);
    } else {
      return colorScale(0);
    }

  } else {
    return '#000'
  }
}

function updateData(data) {

  rect = svg.selectAll("rect")
    .data(data, function(d, i ) { return i; });

  rect.exit()
    .remove();

  rect.enter()
    .append('rect')
    .merge(rect)
      .on('dblclick', function(d) {
        document.location = d.href;
      })
      .on('mouseover', function(d) {
        width = d.coords.split(",")[2] - d.coords.split(",")[0];
        height = d.coords.split(",")[3] - d.coords.split(",")[1];
        size = width * height;
        $('.tooltip').attr('style', "left: " + d.coords.split(",")[0] + "; top:" + d.coords.split(",")[1]);
        $('.tooltip .header').text(d.title);
        $('.tooltip .meta').text("$" + size);
        $('.tooltip .description a').text(d.href);
        $('.tooltip .description a').attr('href', d.href);
      })
      .attr('x', function(d) { return d.coords.split(",")[0]; })
      .attr('x', function(d) { return d.coords.split(",")[0]; })
      .attr('width', function(d) { return d.coords.split(",")[2] - d.coords.split(",")[0]; })
      .attr('y', function(d) { return d.coords.split(",")[1]; })
      .attr('height', function(d) { return d.coords.split(",")[3] - d.coords.split(",")[1]; })
      .attr('stroke-width', 1)
      .attr('stroke', 'rgba(0,0,0,0.3')
      .transition()
      .duration(1000)
      .attr('fill', colourByFilter);
}

d3.json("data/data.json", function(d) {
  data = d;
  updateData(d);
});

$('document').ready(function(){
  $('.ad-grid').on('mouseover', function() {
    $('.tooltip').addClass('active');
  })
  $('.ad-grid').on('mouseout', function() {
    $('.tooltip').removeClass('active');
  })
});
<commit_msg>Use .html() so we can get around html encoding issues with title's<commit_after>const svg = d3.select('svg');
let activeFacet = 'domain';
const colourRangeMax = 8000;

const colorScale = d3.scaleLinear().domain([1,colourRangeMax])
  .interpolate(d3.interpolateHcl)
  .range([d3.rgb("#f00"), d3.rgb('#0f0')]);

function changeFacet(facet) {
  activeFacet = facet;
  updateData(data);
  $('#facet-menu .item').removeClass('active');
  $('#facet-menu .item.' + facet).addClass('active');
}

function colourByFilter(d) {
  if (activeFacet == 'original') {
    $('.ad-grid').addClass('coloured');
    return 'rgba(0,0,0,0)'

  } else if (activeFacet == 'cost') {
    $('.ad-grid').removeClass('coloured');
    width = d.coords.split(",")[2] - d.coords.split(",")[0];
    height = d.coords.split(",")[3] - d.coords.split(",")[1];
    size = width * height;
    return colorScale(size);

  } else if (activeFacet == 'registration') {
    $('.ad-grid').removeClass('coloured');
    if (d.title.toLowerCase().startsWith('reserved for')) {
      return colorScale(colourRangeMax - 2000);
    }
    if (d.title == 'Pending Order') {
      return colorScale(colourRangeMax - 5000);
    } else if (d.title == 'Link Suspended') {
      return colorScale(0);
    } else {
      return colorScale(colourRangeMax);
    }

  } else if (activeFacet == 'domain') {
    $('.ad-grid').removeClass('coloured');
    if (d.response.squatter == true) {
      return colorScale(colourRangeMax - 5000);
    } else if (d.response.redirected) {
      return colorScale(colourRangeMax - 3000);
    } else if (d.response.status == 200) {
      return colorScale(colourRangeMax);
    } else if (d.response.status >= 400) {
      return colorScale(1000);
    } else if (d.response.error) {
      return colorScale(0);
    } else {
      return colorScale(0);
    }

  } else {
    return '#000'
  }
}

function updateData(data) {

  rect = svg.selectAll("rect")
    .data(data, function(d, i ) { return i; });

  rect.exit()
    .remove();

  rect.enter()
    .append('rect')
    .merge(rect)
      .on('dblclick', function(d) {
        document.location = d.href;
      })
      .on('mouseover', function(d) {
        width = d.coords.split(",")[2] - d.coords.split(",")[0];
        height = d.coords.split(",")[3] - d.coords.split(",")[1];
        size = width * height;
        $('.tooltip').attr('style', "left: " + d.coords.split(",")[0] + "; top:" + d.coords.split(",")[1]);
        $('.tooltip .header').html(d.title);
        $('.tooltip .meta').text("$" + size);
        $('.tooltip .description a').text(d.href);
        $('.tooltip .description a').attr('href', d.href);
      })
      .attr('x', function(d) { return d.coords.split(",")[0]; })
      .attr('x', function(d) { return d.coords.split(",")[0]; })
      .attr('width', function(d) { return d.coords.split(",")[2] - d.coords.split(",")[0]; })
      .attr('y', function(d) { return d.coords.split(",")[1]; })
      .attr('height', function(d) { return d.coords.split(",")[3] - d.coords.split(",")[1]; })
      .attr('stroke-width', 1)
      .attr('stroke', 'rgba(0,0,0,0.3')
      .transition()
      .duration(1000)
      .attr('fill', colourByFilter);
}

d3.json("data/data.json", function(d) {
  data = d;
  updateData(d);
});

$('document').ready(function(){
  $('.ad-grid').on('mouseover', function() {
    $('.tooltip').addClass('active');
  })
  $('.ad-grid').on('mouseout', function() {
    $('.tooltip').removeClass('active');
  })
});
<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
});

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

Number.prototype.toWords = function() {
    function tw(s,n){var ns=s.slice(0,3),nw=[["","one","two","three","four","five","six","seven","eight","nine"],["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],["","thousand","million","billion","trillion"]];
        return (ns.length<1)?"":tw(s.slice(3),n+1)+((ns.length>1)?(((ns.length==3&&ns[2]!="0")?nw[0][ns[2]]+" hundred ":"")+((ns[1]=="1")?nw[1][ns[0]]+" ":((ns[1]!="0")?nw[2][ns[1]]+" ":"")+(ns[0]!="0"?nw[0][ns[0]]+" ":""))):(ns[0]!="0"?nw[0][ns[0]]+" ":""))+(parseInt(ns,10)!=0?nw[3][n]+(n>0?" ":""):"");}
    return tw(this.toString().split("").reverse().join(""),0);
}

// Song request form handlers
$("#songName,#songSong").on('input propertychange',function(){$("#songSubmit").prop("disabled",($('#songName').val()==''||$('#songSong').val()=='')?true:false);});
$("#songForm").submit(function(event){
    event.preventDefault();
    $("#songSubmit").prop('disabled',true);
    $.post($(this).prop('action'),$(this).serialize(),function(data){
            var res = $.parseJSON(data);
            if(res.status=="SUCCESS")
                $("#songResult").text("SUCCESS - Thanks for requesting the song: '"+res.row[2]+"'").addClass("text-success").removeClass("text-danger");
            else
                $("#songResult").text(res.status+" - "+res.message).addClass("text-danger").removeClass("text-success");
        },'text').fail(function(){$("#songResult").text("Safari doesn't allow us to verify requests but hopefully we got it.").addClass("text-warning").removeClass("text-success");});
    $("#songSong").val('');
});

// RSVP request form handlers
$("#searchName").on('input propertychange',function(){$("#searchSubmit").prop("disabled",($('#searchName').val()=='')?true:false);});
$("#searchForm").submit(function(event){
    event.preventDefault();
    $("#searchSubmit").prop('disabled',true);
    $.post($(this).prop('action'),$(this).serialize(),function(data){
			var res = $.parseJSON(data);
			if(res.status=="SUCCESS") {
				$("#searchStatus").text("SUCCESS - Found "+res.results.length+" matches").addClass("text-success").removeClass("text-danger");
				console.log(res.results);
				$("#rsvpName").empty();
				for(x in res.results) {
					$("#rsvpName").append($("<option>").text(res.results[x].name).val(res.results[x].name));
				}
				$("#rsvpForm").removeClass("hidden");
			} else
				$("#searchStatus").text(res.status+" - "+res.message).addClass("text-danger").removeClass("text-success");
		},'text').fail(function(){
			$("#searchStatus").text("The RSVP feature isn't working right now, please call or email.").addClass("text-danger").removeClass("text-success");
		});
});
$("#rsvpName").change(function(){$("#rsvpSubmit").prop('disabled',false);});
$("#rsvpForm").submit(function(event){
    event.preventDefault();
    $("#rsvpSubmit").prop('disabled',true);
	var formData = $(this).serialize();
    $.post($(this).prop('action'),formData,function(data){
			var res = $.parseJSON(data);
			if(res.status=="SUCCESS") {
				console.log(res.result);
				$("#rsvpStatus").text("SUCCESS - Thanks for RSVP'ing").addClass("text-success").removeClass("text-danger");

			} else
				$("#rsvpStatus").text(res.status+" - "+res.message).addClass("text-danger").removeClass("text-success");
		},'text').fail(function(){
			$("#rsvpStatus").text("The RSVP feature isn't working right now, please call or email.").addClass("text-danger").removeClass("text-success");
		});
});

/*
// Google Maps Scripts
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);

function init() {
    // Basic options for a simple Google Map
    // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
    var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 15,

        // The latitude and longitude to center the map (always required)
        center: new google.maps.LatLng(40.6700, -73.9400), // New York

        // Disables the default Google Maps UI components
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: false,

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        styles: [{
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "landscape",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 29
            }, {
                "weight": 0.2
            }]
        }, {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 18
            }]
        }, {
            "featureType": "road.local",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "featureType": "poi",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 21
            }]
        }, {
            "elementType": "labels.text.stroke",
            "stylers": [{
                "visibility": "on"
            }, {
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "elementType": "labels.text.fill",
            "stylers": [{
                "saturation": 36
            }, {
                "color": "#000000"
            }, {
                "lightness": 40
            }]
        }, {
            "elementType": "labels.icon",
            "stylers": [{
                "visibility": "off"
            }]
        }, {
            "featureType": "transit",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 19
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }, {
                "weight": 1.2
            }]
        }]
    };

    // Get the HTML DOM element that will contain your map
    // We are using a div with id="map" seen below in the <body>
    var mapElement = document.getElementById('map');

    // Create the Google Map using out element and options defined above
    var map = new google.maps.Map(mapElement, mapOptions);

    // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon
    var image = 'img/map-marker.png';
    var myLatLng = new google.maps.LatLng(40.6700, -73.9400);
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image
    });
} */
<commit_msg>Changed to JSONP for song requests<commit_after>/*!
 * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
});

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

Number.prototype.toWords = function() {
    function tw(s,n){var ns=s.slice(0,3),nw=[["","one","two","three","four","five","six","seven","eight","nine"],["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],["","thousand","million","billion","trillion"]];
        return (ns.length<1)?"":tw(s.slice(3),n+1)+((ns.length>1)?(((ns.length==3&&ns[2]!="0")?nw[0][ns[2]]+" hundred ":"")+((ns[1]=="1")?nw[1][ns[0]]+" ":((ns[1]!="0")?nw[2][ns[1]]+" ":"")+(ns[0]!="0"?nw[0][ns[0]]+" ":""))):(ns[0]!="0"?nw[0][ns[0]]+" ":""))+(parseInt(ns,10)!=0?nw[3][n]+(n>0?" ":""):"");}
    return tw(this.toString().split("").reverse().join(""),0);
}

// Song request form handlers
$("#songName,#songSong").on('input propertychange',function(){$("#songSubmit").prop("disabled",($('#songName').val()==''||$('#songSong').val()=='')?true:false);});
$("#songForm").submit(function(event){
    event.preventDefault();
    $("#songSubmit").prop('disabled',true);
//    $.post($(this).prop('action'),$(this).serialize(),function(data){
	  $.getJSON($(this).prop('action') + "?callback=?", $(this).serialize(), function(data){
            if(data.status=="SUCCESS")
                $("#songResult").text("SUCCESS - Thanks for requesting the song: '"+data.row[2]+"'").addClass("text-success").removeClass("text-danger");
            else
                $("#songResult").text(data.status+" - "+data.message).addClass("text-danger").removeClass("text-success");
        },'text').fail(function(){$("#songResult").text("Safari doesn't allow us to verify requests but hopefully we got it.").addClass("text-warning").removeClass("text-success");});
    $("#songSong").val('');
});

// RSVP request form handlers
$("#searchName").on('input propertychange',function(){$("#searchSubmit").prop("disabled",($('#searchName').val()=='')?true:false);});
$("#searchForm").submit(function(event){
    event.preventDefault();
    $("#searchSubmit").prop('disabled',true);
    $.post($(this).prop('action'),$(this).serialize(),function(data){
		  console.log("url: " + $(this).prop('action') + "&callback=?");
			var res = $.parseJSON(data);
			if(res.status=="SUCCESS") {
				$("#searchStatus").text("SUCCESS - Found "+res.results.length+" matches").addClass("text-success").removeClass("text-danger");
				console.log(res.results);
				$("#rsvpName").empty();
				for(x in res.results) {
					$("#rsvpName").append($("<option>").text(res.results[x].name).val(res.results[x].name));
				}
				$("#rsvpForm").removeClass("hidden");
			} else
				$("#searchStatus").text(res.status+" - "+res.message).addClass("text-danger").removeClass("text-success");
		},'text').fail(function(){
			$("#searchStatus").text("The RSVP feature isn't working right now, please call or email.").addClass("text-danger").removeClass("text-success");
		});
});
$("#rsvpName").change(function(){$("#rsvpSubmit").prop('disabled',false);});
$("#rsvpForm").submit(function(event){
    event.preventDefault();
    $("#rsvpSubmit").prop('disabled',true);
	var formData = $(this).serialize();
    $.post($(this).prop('action'),formData,function(data){
			var res = $.parseJSON(data);
			if(res.status=="SUCCESS") {
				console.log(res.result);
				$("#rsvpStatus").text("SUCCESS - Thanks for RSVP'ing").addClass("text-success").removeClass("text-danger");

			} else
				$("#rsvpStatus").text(res.status+" - "+res.message).addClass("text-danger").removeClass("text-success");
		},'text').fail(function(){
			$("#rsvpStatus").text("The RSVP feature isn't working right now, please call or email.").addClass("text-danger").removeClass("text-success");
		});
});

/*
// Google Maps Scripts
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);

function init() {
    // Basic options for a simple Google Map
    // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
    var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 15,

        // The latitude and longitude to center the map (always required)
        center: new google.maps.LatLng(40.6700, -73.9400), // New York

        // Disables the default Google Maps UI components
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: false,

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        styles: [{
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "landscape",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 29
            }, {
                "weight": 0.2
            }]
        }, {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 18
            }]
        }, {
            "featureType": "road.local",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "featureType": "poi",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 21
            }]
        }, {
            "elementType": "labels.text.stroke",
            "stylers": [{
                "visibility": "on"
            }, {
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "elementType": "labels.text.fill",
            "stylers": [{
                "saturation": 36
            }, {
                "color": "#000000"
            }, {
                "lightness": 40
            }]
        }, {
            "elementType": "labels.icon",
            "stylers": [{
                "visibility": "off"
            }]
        }, {
            "featureType": "transit",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 19
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }, {
                "weight": 1.2
            }]
        }]
    };

    // Get the HTML DOM element that will contain your map
    // We are using a div with id="map" seen below in the <body>
    var mapElement = document.getElementById('map');

    // Create the Google Map using out element and options defined above
    var map = new google.maps.Map(mapElement, mapOptions);

    // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon
    var image = 'img/map-marker.png';
    var myLatLng = new google.maps.LatLng(40.6700, -73.9400);
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image
    });
} */
<|endoftext|>


<commit_before>/*!
 * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
});

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

// Google Maps Scripts
// When the window has finished loading create our google map below
google.maps.event.addDomListener(window, 'load', init);

function init() {
    // Basic options for a simple Google Map
    // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
    var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 15,

        // The latitude and longitude to center the map (always required)
        center: new google.maps.LatLng(40.6700, -73.9400), // New York

        // Disables the default Google Maps UI components
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: false,

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        styles: [{
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "landscape",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 29
            }, {
                "weight": 0.2
            }]
        }, {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 18
            }]
        }, {
            "featureType": "road.local",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "featureType": "poi",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 21
            }]
        }, {
            "elementType": "labels.text.stroke",
            "stylers": [{
                "visibility": "on"
            }, {
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "elementType": "labels.text.fill",
            "stylers": [{
                "saturation": 36
            }, {
                "color": "#000000"
            }, {
                "lightness": 40
            }]
        }, {
            "elementType": "labels.icon",
            "stylers": [{
                "visibility": "off"
            }]
        }, {
            "featureType": "transit",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 19
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }, {
                "weight": 1.2
            }]
        }]
    };

    // Get the HTML DOM element that will contain your map
    // We are using a div with id="map" seen below in the <body>
    var mapElement = document.getElementById('map');

    // Create the Google Map using out element and options defined above
    var map = new google.maps.Map(mapElement, mapOptions);

    // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon
    var image = 'img/map-marker.png';
    var myLatLng = new google.maps.LatLng(40.6700, -73.9400);
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image
    });
}
<commit_msg>Bugfix: Disabled Google Maps load-up in grayscale.js<commit_after>/*!
 * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com)
 * Code licensed under the Apache License v2.0.
 * For details, see http://www.apache.org/licenses/LICENSE-2.0.
 */

// jQuery to collapse the navbar on scroll
$(window).scroll(function() {
    if ($(".navbar").offset().top > 50) {
        $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
        $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
});

// jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
    $('a.page-scroll').bind('click', function(event) {
        var $anchor = $(this);
        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 1500, 'easeInOutExpo');
        event.preventDefault();
    });
});

// Closes the Responsive Menu on Menu Item Click
$('.navbar-collapse ul li a').click(function() {
    $('.navbar-toggle:visible').click();
});

// Google Maps Scripts
// When the window has finished loading create our google map below
/* google.maps.event.addDomListener(window, 'load', init); */

function init() {
    // Basic options for a simple Google Map
    // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions
    var mapOptions = {
        // How zoomed in you want the map to start at (always required)
        zoom: 15,

        // The latitude and longitude to center the map (always required)
        center: new google.maps.LatLng(40.6700, -73.9400), // New York

        // Disables the default Google Maps UI components
        disableDefaultUI: true,
        scrollwheel: false,
        draggable: false,

        // How you would like to style the map.
        // This is where you would paste any style found on Snazzy Maps.
        styles: [{
            "featureType": "water",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "landscape",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }]
        }, {
            "featureType": "road.highway",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 29
            }, {
                "weight": 0.2
            }]
        }, {
            "featureType": "road.arterial",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 18
            }]
        }, {
            "featureType": "road.local",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "featureType": "poi",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 21
            }]
        }, {
            "elementType": "labels.text.stroke",
            "stylers": [{
                "visibility": "on"
            }, {
                "color": "#000000"
            }, {
                "lightness": 16
            }]
        }, {
            "elementType": "labels.text.fill",
            "stylers": [{
                "saturation": 36
            }, {
                "color": "#000000"
            }, {
                "lightness": 40
            }]
        }, {
            "elementType": "labels.icon",
            "stylers": [{
                "visibility": "off"
            }]
        }, {
            "featureType": "transit",
            "elementType": "geometry",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 19
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.fill",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 20
            }]
        }, {
            "featureType": "administrative",
            "elementType": "geometry.stroke",
            "stylers": [{
                "color": "#000000"
            }, {
                "lightness": 17
            }, {
                "weight": 1.2
            }]
        }]
    };

    // Get the HTML DOM element that will contain your map
    // We are using a div with id="map" seen below in the <body>
    var mapElement = document.getElementById('map');

    // Create the Google Map using out element and options defined above
    var map = new google.maps.Map(mapElement, mapOptions);

    // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon
    var image = 'img/map-marker.png';
    var myLatLng = new google.maps.LatLng(40.6700, -73.9400);
    var beachMarker = new google.maps.Marker({
        position: myLatLng,
        map: map,
        icon: image
    });
}
<|endoftext|>