<commit_before>(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('testRky', ['$scope', function($scope){
      $scope.title = "testRky";
      $scope.d3Data = [
        {capteur: "Rky_L", score:10},
        {capteur: "Rky_L", score: 87}
      ];
    }]);

}());

// --------
// recuperation des valeur depuis MongoDB
(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('httpRky', ['$scope', '$http', function($scope, $http){
      $scope.title = "httpRky ... in progress";
      $scope.date = "2016/11/01";
      var url1 = "/api/v1/list/scale";
      var urlBase ="/api/v1/search?name=Rky_P&source=*&after=";
      var url = urlBase + $scope.date;
      var data = [];

      $http.get(url)
        .then(function(response){
        angular.forEach(response.data,function(value){
          data.push({ capteur: value.heure, score: value.value });
        });
      });

      $scope.d3Data = data;

      $scope.clickButton = function() {
          url = urlBase + $scope.date;
          console.log(url);
          $scope.$digest();
        }

  }]);

 }());<commit_msg>function<commit_after>(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('testRky', ['$scope', function($scope){
      $scope.title = "testRky";
      $scope.d3Data = [
        {capteur: "Rky_L", score:10},
        {capteur: "Rky_L", score: 87}
      ];
    }]);

}());

// --------
// recuperation des valeur depuis MongoDB
(function () {
  'use strict';

  angular.module('RkyApp.controllers')
    .controller('httpRky', ['$scope', '$http', function($scope, $http){
      $scope.title = "httpRky ... in progress";
      $scope.date = "2016/11/01";
      var url1 = "/api/v1/list/scale";
      var urlBase ="/api/v1/search?name=Rky_P&source=*&after=";
      var url = urlBase + $scope.date;
      var data = [];

      function getData () {
        $http.get(url)
        .then(function(response){
        angular.forEach(response.data,function(value){
          data.push({ capteur: value.heure, score: value.value });
         });
       });
      }

      $scope.d3Data = data;

      $scope.clickButton = function() {
          url = urlBase + $scope.date;
          console.log(url);
          getData();
        }

  }]);

 }());<|endoftext|>


<commit_before>import moment from 'moment'
import { logger } from '../../logger'

let dateFormat = ''
let axisFormat = ''
let excludes = []
let title = ''
let sections = []
let tasks = []
let currentSection = ''

export const clear = function () {
  sections = []
  tasks = []
  currentSection = ''
  title = ''
  taskCnt = 0
  lastTask = undefined
  lastTaskID = undefined
  rawTasks = []
}

export const setAxisFormat = function (txt) {
  axisFormat = txt
}

export const getAxisFormat = function () {
  return axisFormat
}

export const setDateFormat = function (txt) {
  dateFormat = txt
}

export const setExcludes = function (txt) {
  excludes = txt.split(' ')
}

export const setTitle = function (txt) {
  title = txt
}

export const getTitle = function () {
  return title
}

export const addSection = function (txt) {
  currentSection = txt
  sections.push(txt)
}

export const getTasks = function () {
  let allItemsPricessed = compileTasks()
  const maxDepth = 10
  let iterationCount = 0
  while (!allItemsPricessed && (iterationCount < maxDepth)) {
    allItemsPricessed = compileTasks()
    iterationCount++
  }

  tasks = rawTasks

  return tasks
}

const getNextValidDate = function (date, dateFormat, excludes) {
  const excludeWeekends = excludes.indexOf('weekend') >= 0 || excludes.indexOf('weekends') >= 0;
  const trimmedDateFormat = dateFormat.trim()
  let mDate = moment.isMoment(date) ? date : (moment.isDate(date) ? moment(date) : moment(date, dateFormat, true));
  while ((excludeWeekends && mDate.isoWeekday() >= 6) || (excludes.indexOf(mDate.format(trimmedDateFormat)) >= 0)) {
    mDate = mDate.add(1, 'd')
  }
  return mDate.toDate();
}

const getStartDate = function (prevTime, dateFormat, excludes, str) {
  str = str.trim()

  // Test for after
  const re = /^after\s+([\d\w-]+)/
  const afterStatement = re.exec(str.trim())

  if (afterStatement !== null) {
    const task = findTaskById(afterStatement[1])

    if (typeof task === 'undefined') {
      const dt = new Date()
      dt.setHours(0, 0, 0, 0)
      //return getNextValidDate(dt, dateFormat, excludes)
      return dt
    }
    //return getNextValidDate(task.endTime, dateFormat, excludes)
    return task.endTime
  }

  // Check for actual date set
  let mDate = moment(str, dateFormat.trim(), true);
  if (mDate.isValid()) {
    return getNextValidDate(mDate, dateFormat, excludes)
  } else {
    logger.debug('Invalid date:' + str)
    logger.debug('With date format:' + dateFormat.trim())
  }

  // Default date - now
  return getNextValidDate(new Date(), dateFormat, excludes)
}

const getEndDate = function (prevTime, dateFormat, excludes, str) {
  str = str.trim()

  // Check for actual date
  let mDate = moment(str, dateFormat.trim(), true);
  if (mDate.isValid()) {
    //return getNextValidDate(mDate, dateFormat, excludes)
    return mDate.toDate()
  }

  const d = moment(prevTime)
  // Check for length
  const re = /^([\d]+)([wdhms])/
  const durationStatement = re.exec(str.trim())

  if (durationStatement !== null) {
    switch (durationStatement[2]) {
      case 's':
        d.add(durationStatement[1], 'seconds')
        break
      case 'm':
        d.add(durationStatement[1], 'minutes')
        break
      case 'h':
        d.add(durationStatement[1], 'hours')
        break
      case 'd':
        d.add(durationStatement[1], 'days')
        break
      case 'w':
        d.add(durationStatement[1], 'weeks')
        break
    }
  }
  // Default date - now
  return getNextValidDate(d, dateFormat, excludes)
}

let taskCnt = 0
const parseId = function (idStr) {
  if (typeof idStr === 'undefined') {
    taskCnt = taskCnt + 1
    return 'task' + taskCnt
  }
  return idStr
}
// id, startDate, endDate
// id, startDate, length
// id, after x, endDate
// id, after x, length
// startDate, endDate
// startDate, length
// after x, endDate
// after x, length
// endDate
// length

const compileData = function (prevTask, dataStr) {
  let ds

  if (dataStr.substr(0, 1) === ':') {
    ds = dataStr.substr(1, dataStr.length)
  } else {
    ds = dataStr
  }

  const data = ds.split(',')

  const task = {}

  // Get tags like active, done cand crit
  let matchFound = true
  while (matchFound) {
    matchFound = false
    if (data[0].match(/^\s*active\s*$/)) {
      task.active = true
      data.shift(1)
      matchFound = true
    }
    if (data[0].match(/^\s*done\s*$/)) {
      task.done = true
      data.shift(1)
      matchFound = true
    }
    if (data[0].match(/^\s*crit\s*$/)) {
      task.crit = true
      data.shift(1)
      matchFound = true
    }
  }
  for (let i = 0; i < data.length; i++) {
    data[i] = data[i].trim()
  }

  switch (data.length) {
    case 1:
      task.id = parseId()
      task.startTime = prevTask.endTime
      task.endTime = getEndDate(task.startTime, dateFormat, excludes, data[0])
      break
    case 2:
      task.id = parseId()
      task.startTime = getStartDate(undefined, dateFormat, excludes, data[0])
      task.endTime = getEndDate(task.startTime, dateFormat, excludes, data[1])
      break
    case 3:
      task.id = parseId(data[0])
      task.startTime = getStartDate(undefined, dateFormat, excludes, data[1])
      task.endTime = getEndDate(task.startTime, dateFormat, excludes, data[2])
      break
    default:
  }

  return task
}

const parseData = function (prevTaskId, dataStr) {
  let ds
  if (dataStr.substr(0, 1) === ':') {
    ds = dataStr.substr(1, dataStr.length)
  } else {
    ds = dataStr
  }

  const data = ds.split(',')

  const task = {}

  // Get tags like active, done cand crit
  let matchFound = true
  while (matchFound) {
    matchFound = false
    if (data[0].match(/^\s*active\s*$/)) {
      task.active = true
      data.shift(1)
      matchFound = true
    }
    if (data[0].match(/^\s*done\s*$/)) {
      task.done = true
      data.shift(1)
      matchFound = true
    }
    if (data[0].match(/^\s*crit\s*$/)) {
      task.crit = true
      data.shift(1)
      matchFound = true
    }
  }
  for (let i = 0; i < data.length; i++) {
    data[i] = data[i].trim()
  }

  switch (data.length) {
    case 1:
      task.id = parseId()
      task.startTime = { type: 'prevTaskEnd', id: prevTaskId }
      task.endTime = { data: data[0] }
      break
    case 2:
      task.id = parseId()
      task.startTime = { type: 'getStartDate', startData: data[0] }
      task.endTime = { data: data[1] }
      break
    case 3:
      task.id = parseId(data[0])
      task.startTime = { type: 'getStartDate', startData: data[1] }
      task.endTime = { data: data[2] }
      break
    default:
  }

  return task
}

let lastTask
let lastTaskID
let rawTasks = []
const taskDb = {}
export const addTask = function (descr, data) {
  const rawTask = {
    section: currentSection,
    type: currentSection,
    processed: false,
    raw: { data: data },
    task: descr
  }
  const taskInfo = parseData(lastTaskID, data)
  rawTask.raw.startTime = taskInfo.startTime
  rawTask.raw.endTime = taskInfo.endTime
  rawTask.id = taskInfo.id
  rawTask.prevTaskId = lastTaskID
  rawTask.active = taskInfo.active
  rawTask.done = taskInfo.done
  rawTask.crit = taskInfo.crit

  const pos = rawTasks.push(rawTask)

  lastTaskID = rawTask.id
  // Store cross ref
  taskDb[rawTask.id] = pos - 1
}

export const findTaskById = function (id) {
  const pos = taskDb[id]
  return rawTasks[pos]
}

export const addTaskOrg = function (descr, data) {
  const newTask = {
    section: currentSection,
    type: currentSection,
    description: descr,
    task: descr
  }
  const taskInfo = compileData(lastTask, data)
  newTask.startTime = taskInfo.startTime
  newTask.endTime = taskInfo.endTime
  newTask.id = taskInfo.id
  newTask.active = taskInfo.active
  newTask.done = taskInfo.done
  newTask.crit = taskInfo.crit
  lastTask = newTask
  tasks.push(newTask)
}

const compileTasks = function () {
  const compileTask = function (pos) {
    const task = rawTasks[pos]
    let startTime = ''
    switch (rawTasks[pos].raw.startTime.type) {
      case 'prevTaskEnd':
        const prevTask = findTaskById(task.prevTaskId)
        task.startTime = prevTask.endTime
        break
      case 'getStartDate':
        startTime = getStartDate(undefined, dateFormat, excludes, rawTasks[pos].raw.startTime.startData)
        if (startTime) {
          rawTasks[pos].startTime = startTime
        }
        break
    }

    if (rawTasks[pos].startTime) {
      rawTasks[pos].endTime = getEndDate(rawTasks[pos].startTime, dateFormat, excludes, rawTasks[pos].raw.endTime.data)
      if (rawTasks[pos].endTime) {
        rawTasks[pos].processed = true
      }
    }

    return rawTasks[pos].processed
  }

  let allProcessed = true
  for (let i = 0; i < rawTasks.length; i++) {
    compileTask(i)

    allProcessed = allProcessed && rawTasks[i].processed
  }
  return allProcessed
}

export default {
  clear,
  setDateFormat,
  setAxisFormat,
  getAxisFormat,
  setTitle,
  getTitle,
  addSection,
  getTasks,
  addTask,
  findTaskById,
  addTaskOrg,
  setExcludes
}
<commit_msg>Standard<commit_after>import moment from 'moment'
import { logger } from '../../logger'

let dateFormat = ''
let axisFormat = ''
let excludes = []
let title = ''
let sections = []
let tasks = []
let currentSection = ''

export const clear = function () {
  sections = []
  tasks = []
  currentSection = ''
  title = ''
  taskCnt = 0
  lastTask = undefined
  lastTaskID = undefined
  rawTasks = []
}

export const setAxisFormat = function (txt) {
  axisFormat = txt
}

export const getAxisFormat = function () {
  return axisFormat
}

export const setDateFormat = function (txt) {
  dateFormat = txt
}

export const setExcludes = function (txt) {
  excludes = txt.split(' ')
}

export const setTitle = function (txt) {
  title = txt
}

export const getTitle = function () {
  return title
}

export const addSection = function (txt) {
  currentSection = txt
  sections.push(txt)
}

export const getTasks = function () {
  let allItemsPricessed = compileTasks()
  const maxDepth = 10
  let iterationCount = 0
  while (!allItemsPricessed && (iterationCount < maxDepth)) {
    allItemsPricessed = compileTasks()
    iterationCount++
  }

  tasks = rawTasks

  return tasks
}

const getNextValidDate = function (date, dateFormat, excludes) {
  const excludeWeekends = excludes.indexOf('weekend') >= 0 || excludes.indexOf('weekends') >= 0
  const trimmedDateFormat = dateFormat.trim()
  let mDate = moment.isMoment(date) ? date : (moment.isDate(date) ? moment(date) : moment(date, dateFormat, true))

  const isInvalidDate = function (d) {
    return (excludeWeekends && d.isoWeekday() >= 6) || (excludes.indexOf(d.format(trimmedDateFormat)) >= 0)
  }

  while (isInvalidDate(mDate)) {
    mDate = mDate.add(1, 'd')
  }

  return mDate.toDate()
}

const getStartDate = function (prevTime, dateFormat, excludes, str) {
  str = str.trim()

  // Test for after
  const re = /^after\s+([\d\w-]+)/
  const afterStatement = re.exec(str.trim())

  if (afterStatement !== null) {
    const task = findTaskById(afterStatement[1])

    if (typeof task === 'undefined') {
      const dt = new Date()
      dt.setHours(0, 0, 0, 0)
      // return getNextValidDate(dt, dateFormat, excludes)
      return dt
    }
    // return getNextValidDate(task.endTime, dateFormat, excludes)
    return task.endTime
  }

  // Check for actual date set
  let mDate = moment(str, dateFormat.trim(), true)
  if (mDate.isValid()) {
    return getNextValidDate(mDate, dateFormat, excludes)
  } else {
    logger.debug('Invalid date:' + str)
    logger.debug('With date format:' + dateFormat.trim())
  }

  // Default date - now
  return getNextValidDate(new Date(), dateFormat, excludes)
}

const getEndDate = function (prevTime, dateFormat, excludes, str) {
  str = str.trim()

  // Check for actual date
  let mDate = moment(str, dateFormat.trim(), true)
  if (mDate.isValid()) {
    // return getNextValidDate(mDate, dateFormat, excludes)
    return mDate.toDate()
  }

  const d = moment(prevTime)
  // Check for length
  const re = /^([\d]+)([wdhms])/
  const durationStatement = re.exec(str.trim())

  if (durationStatement !== null) {
    switch (durationStatement[2]) {
      case 's':
        d.add(durationStatement[1], 'seconds')
        break
      case 'm':
        d.add(durationStatement[1], 'minutes')
        break
      case 'h':
        d.add(durationStatement[1], 'hours')
        break
      case 'd':
        d.add(durationStatement[1], 'days')
        break
      case 'w':
        d.add(durationStatement[1], 'weeks')
        break
    }
  }
  // Default date - now
  return getNextValidDate(d, dateFormat, excludes)
}

let taskCnt = 0
const parseId = function (idStr) {
  if (typeof idStr === 'undefined') {
    taskCnt = taskCnt + 1
    return 'task' + taskCnt
  }
  return idStr
}
// id, startDate, endDate
// id, startDate, length
// id, after x, endDate
// id, after x, length
// startDate, endDate
// startDate, length
// after x, endDate
// after x, length
// endDate
// length

const compileData = function (prevTask, dataStr) {
  let ds

  if (dataStr.substr(0, 1) === ':') {
    ds = dataStr.substr(1, dataStr.length)
  } else {
    ds = dataStr
  }

  const data = ds.split(',')

  const task = {}

  // Get tags like active, done cand crit
  let matchFound = true
  while (matchFound) {
    matchFound = false
    if (data[0].match(/^\s*active\s*$/)) {
      task.active = true
      data.shift(1)
      matchFound = true
    }
    if (data[0].match(/^\s*done\s*$/)) {
      task.done = true
      data.shift(1)
      matchFound = true
    }
    if (data[0].match(/^\s*crit\s*$/)) {
      task.crit = true
      data.shift(1)
      matchFound = true
    }
  }
  for (let i = 0; i < data.length; i++) {
    data[i] = data[i].trim()
  }

  switch (data.length) {
    case 1:
      task.id = parseId()
      task.startTime = prevTask.endTime
      task.endTime = getEndDate(task.startTime, dateFormat, excludes, data[0])
      break
    case 2:
      task.id = parseId()
      task.startTime = getStartDate(undefined, dateFormat, excludes, data[0])
      task.endTime = getEndDate(task.startTime, dateFormat, excludes, data[1])
      break
    case 3:
      task.id = parseId(data[0])
      task.startTime = getStartDate(undefined, dateFormat, excludes, data[1])
      task.endTime = getEndDate(task.startTime, dateFormat, excludes, data[2])
      break
    default:
  }

  return task
}

const parseData = function (prevTaskId, dataStr) {
  let ds
  if (dataStr.substr(0, 1) === ':') {
    ds = dataStr.substr(1, dataStr.length)
  } else {
    ds = dataStr
  }

  const data = ds.split(',')

  const task = {}

  // Get tags like active, done cand crit
  let matchFound = true
  while (matchFound) {
    matchFound = false
    if (data[0].match(/^\s*active\s*$/)) {
      task.active = true
      data.shift(1)
      matchFound = true
    }
    if (data[0].match(/^\s*done\s*$/)) {
      task.done = true
      data.shift(1)
      matchFound = true
    }
    if (data[0].match(/^\s*crit\s*$/)) {
      task.crit = true
      data.shift(1)
      matchFound = true
    }
  }
  for (let i = 0; i < data.length; i++) {
    data[i] = data[i].trim()
  }

  switch (data.length) {
    case 1:
      task.id = parseId()
      task.startTime = { type: 'prevTaskEnd', id: prevTaskId }
      task.endTime = { data: data[0] }
      break
    case 2:
      task.id = parseId()
      task.startTime = { type: 'getStartDate', startData: data[0] }
      task.endTime = { data: data[1] }
      break
    case 3:
      task.id = parseId(data[0])
      task.startTime = { type: 'getStartDate', startData: data[1] }
      task.endTime = { data: data[2] }
      break
    default:
  }

  return task
}

let lastTask
let lastTaskID
let rawTasks = []
const taskDb = {}
export const addTask = function (descr, data) {
  const rawTask = {
    section: currentSection,
    type: currentSection,
    processed: false,
    raw: { data: data },
    task: descr
  }
  const taskInfo = parseData(lastTaskID, data)
  rawTask.raw.startTime = taskInfo.startTime
  rawTask.raw.endTime = taskInfo.endTime
  rawTask.id = taskInfo.id
  rawTask.prevTaskId = lastTaskID
  rawTask.active = taskInfo.active
  rawTask.done = taskInfo.done
  rawTask.crit = taskInfo.crit

  const pos = rawTasks.push(rawTask)

  lastTaskID = rawTask.id
  // Store cross ref
  taskDb[rawTask.id] = pos - 1
}

export const findTaskById = function (id) {
  const pos = taskDb[id]
  return rawTasks[pos]
}

export const addTaskOrg = function (descr, data) {
  const newTask = {
    section: currentSection,
    type: currentSection,
    description: descr,
    task: descr
  }
  const taskInfo = compileData(lastTask, data)
  newTask.startTime = taskInfo.startTime
  newTask.endTime = taskInfo.endTime
  newTask.id = taskInfo.id
  newTask.active = taskInfo.active
  newTask.done = taskInfo.done
  newTask.crit = taskInfo.crit
  lastTask = newTask
  tasks.push(newTask)
}

const compileTasks = function () {
  const compileTask = function (pos) {
    const task = rawTasks[pos]
    let startTime = ''
    switch (rawTasks[pos].raw.startTime.type) {
      case 'prevTaskEnd':
        const prevTask = findTaskById(task.prevTaskId)
        task.startTime = prevTask.endTime
        break
      case 'getStartDate':
        startTime = getStartDate(undefined, dateFormat, excludes, rawTasks[pos].raw.startTime.startData)
        if (startTime) {
          rawTasks[pos].startTime = startTime
        }
        break
    }

    if (rawTasks[pos].startTime) {
      rawTasks[pos].endTime = getEndDate(rawTasks[pos].startTime, dateFormat, excludes, rawTasks[pos].raw.endTime.data)
      if (rawTasks[pos].endTime) {
        rawTasks[pos].processed = true
      }
    }

    return rawTasks[pos].processed
  }

  let allProcessed = true
  for (let i = 0; i < rawTasks.length; i++) {
    compileTask(i)

    allProcessed = allProcessed && rawTasks[i].processed
  }
  return allProcessed
}

export default {
  clear,
  setDateFormat,
  setAxisFormat,
  getAxisFormat,
  setTitle,
  getTitle,
  addSection,
  getTasks,
  addTask,
  findTaskById,
  addTaskOrg,
  setExcludes
}
<|endoftext|>


<commit_before>;(function(lander){
    console.log('Moon Lander Visualisation');

    var display = document.getElementById('display');
    var horizon = new Array(display.width);
    horizon[0] = 50;
    for (var index = 1; index < display.width; index++){
        horizon[index] = horizon[index - 1] + 2 * (Math.random() - 0.5);
    }

    var model = {
        "lander": {
            "x": 37, "y": 251,
            "vx": 1, "vy": 0,
            "orientation": Math.PI/4, "angular-velocity": 0.05,
            "radius": 10,
            "fuel": 100,
            "thrusting": true,
            "crashed": false
        },
        "horizon": horizon
    };

    var view = new lander.View(model, display);
    function tick(){
        model.lander.x += model.lander.vx;
        if (model.lander.x > display.width) {
            model.lander.x -= display.width;
        }
        view.update();
        requestAnimationFrame(tick);
    };
    tick();
})(lander);
<commit_msg>Use landed option in app.js<commit_after>;(function(lander){
    console.log('Moon Lander Visualisation');

    var display = document.getElementById('display');
    var horizon = new Array(display.width);
    horizon[0] = 50;
    for (var index = 1; index < display.width; index++){
        horizon[index] = horizon[index - 1] + 2 * (Math.random() - 0.5);
    }

    var model = {
        "lander": {
            "x": 37, "y": 251,
            "vx": 1, "vy": 0,
            "orientation": Math.PI/4, "angular-velocity": 0.05,
            "radius": 10,
            "fuel": 100,
            "thrusting": true,
            "crashed": false,
            "landed": false
        },
        "horizon": horizon
    };

    var view = new lander.View(model, display);
    function tick(){
        model.lander.x += model.lander.vx;
        if (model.lander.x > display.width) {
            model.lander.x -= display.width;
        }
        view.update();
        requestAnimationFrame(tick);
    };
    tick();
})(lander);
<|endoftext|>


<commit_before>var ref = new Firebase("https://pricetracker2015.firebaseio.com/");
var baseUrl = 'http://localhost:3000/'
// var baseUrl = 'https://[OUR APP HERE].herokuapp.com/'

var fbData;
var userData;

$(document).ready(function(){
  begin();
  // add Mary's js code
  hardLanding();
  submitSearch();
});

// +++++++++++++++++++++++++ function definitions only +++++++++++++++++++++++++

// ============== Ajax-Begin ==============
var begin = function(){
  $('.button').on('click', function(e){
    e.preventDefault();
    fbAuth().then(function(authData){
      ajaxLogin(authData);
    });
  });
};

var fbAuth = function(){
  var promise = new Promise(function(resolve, reject){
    ref.authWithOAuthPopup("facebook", function(error, authData) {
      if (error) {
        alert("login failed!");
        reject(error);
      } else {
        resolve(authData);
      };
    });
  })
  return promise;
};

var ajaxLogin = function(authData){
  userId = authData.facebook.id;
  userName = authData.facebook.displayName;
  var ajaxData = {
    user: {
      oauth_id:userId,
      oauth_name:userName
    }
  };

  $.ajax({
    url: baseUrl + "users",
    crossDomain: true,
    type:"post",
    data: ajaxData
  }).done(function(response) {
    userData = userId;
  }).fail(function() {
    alert("Login Failed");
  });
};
// ============== Ajax-End ==============

var hardLanding = function(){
  $('.button').on('click', function(event){
    event.preventDefault();

  $('.hardLanding').remove();
  $(".search-product-form").css("display", "block");

  var request = $.ajax({
    url:"http://localhost:3000/products/newest_products",
    crossDomain: true,
    type:"GET"
   });

    request.done(function(data){
      var products = data["products"]

      for(i = 0; i < products.length; i++){
        $(".softLanding").append("
" + "" + "
")
      };
    });
  });
};

var submitSearch = function(){
  $("#product-search").on('submit', function(event){
    event.preventDefault();

   var request = $.ajax({
    url:"http://localhost:3000/products/results",
    data: $(this).serialize(),
    crossDomain: true,
    type:"GET"
   });

   request.done(function(data){
    debugger
    console.log("successssssss");
    $(".softLanding").remove();
    var products = data["products"]

    for(i = 0; i < products.length; i++){
      $(".search-results").prepend("
" + "" + "
")
    };

   });

   request.fail(function(data){
    console.log("fail");
   });
  });
};

<commit_msg>bug smashing<commit_after>var ref = new Firebase("https://pricetracker2015.firebaseio.com/");
var baseUrl = 'http://localhost:3000/'
// var baseUrl = 'https://[OUR APP HERE].herokuapp.com/'

var fbData;
var userData;

$(document).ready(function(){
  begin();
  // add Mary's js code
  submitSearch();
});

// +++++++++++++++++++++++++ function definitions only +++++++++++++++++++++++++

// ============== Ajax-Begin ==============
var begin = function(){
  $('.button').on('click', function(e){
    e.preventDefault();
    fbAuth().then(function(authData){
      ajaxLogin(authData);
    });
  });
};

var fbAuth = function(){
  var promise = new Promise(function(resolve, reject){
    ref.authWithOAuthPopup("facebook", function(error, authData) {
      if (error) {
        alert("login failed!");
        reject(error);
      } else {
        resolve(authData);
      };
    });
  })
  return promise;
};

var ajaxLogin = function(authData){
  userId = authData.facebook.id;
  userName = authData.facebook.displayName;
  var ajaxData = {
    user: {
      oauth_id:userId,
      oauth_name:userName
    }
  };

  $.ajax({
    url: baseUrl + "users",
    crossDomain: true,
    type:"post",
    data: ajaxData
  }).done(function(response) {
    userData = userId;
    loadHome();
  }).fail(function() {
    alert("Login Failed");
  });
};
// ============== Ajax-End ==============

var loadHome = function(){

  $('.hardLanding').remove();
  $(".search-product-form").css("display", "block");

  var request = $.ajax({
    url:"http://localhost:3000/products/newest_products",
    crossDomain: true,
    type:"GET"
   });

    request.done(function(data){
      var products = data["products"]

      for(i = 0; i < products.length; i++){
        $(".softLanding").append("
" + "" + "
")
      };
    });
};

var submitSearch = function(){
  $("#product-search").on('submit', function(event){
    event.preventDefault();

   var request = $.ajax({
    url:"http://localhost:3000/products/results",
    data: $(this).serialize(),
    crossDomain: true,
    type:"GET"
   });

   request.done(function(data){
    debugger
    console.log("successssssss");
    $(".softLanding").remove();
    var products = data["products"]

    for(i = 0; i < products.length; i++){
      $(".search-results").prepend("
" + "" + "
")
    };

   });

   request.fail(function(data){
    console.log("fail");
   });
  });
};

<|endoftext|>


<commit_before>//RedditApp Module
var redditApp = angular.module('redditApp', ['ngRoute']);

redditApp.controller('mainController', ['$scope', '$http', '$rootElement', '$timeout',  function($scope, $http, $rootElement, $timeout){

    $scope.next = null;
    $scope.count = 0;
    $scope.page = 1;

    $scope.redditify = function(){
        $scope.sr;
        $scope.success = false;
    	$http.get('http://www.reddit.com/r/' + $scope.sr + '.json?count=' + $scope.count + '&limit=25' + $scope.next)

        .success(function (data){

	        $scope.success = true;
	        $scope.subreddits = [];
        	$scope.next = null;

	        for(var i = 0; i < data.data.children.length; i++)
	       	{
                //Hide placeholder div
                //Show page nav.
                	if(data.data.children.length > 0)
                	{
	                    $('.previouspage, .nextpage').removeClass('hidden');
	                    $('#placeholderdiv').addClass('hidden');
                	}

	                //Dealing with .gifs
	        	var str =  data.data.children[i].data.url;
	                var rest = str.substring(0, str.lastIndexOf("/") + 1);
			var last = str.substring(str.lastIndexOf("/") + 1, str.length);

	                var split = last.split(".");
	                var fileformat = split[1];

                //Check if .gifv format. Not supporting that.
                    	if(fileformat == "gifv")
                        	data.data.children[i].data.url = "http://" + data.data.children[i].data.domain + "/" + split[0] + ".gif";
                    	if(fileformat == "jpg" || fileformat == "png" || fileformat == "bmp" || fileformat =="tif")
                    	{
				$scope.subreddits.push(data.data.children[i].data);
                    	}

                         $scope.after = data.data.after;
                         $scope.before = data.data.before;
                         $scope.subreddit = data.data.children[i].data.subreddit;
            }
        });

     }

}]);

//Directive for showing the info qtip.
redditApp.directive('ngHover', function() {
  return {
    link: function(scope, element) {
	    element.qtip
	    ({
	        position: {
	        my: 'bottom center', // Position it where the click was...
	        at: 'top center',
	        target: element,
	        adjust: { mouse: false } // ...but don't follow the mouse
	        },
	        style: { classes: 'qtip-youtube' },
	       content:
	        {
	       	     text: scope.subreddit.title
		}

	   })

     	element.on('click', function(){

        $('.modal-body', '.modal-title').empty();
        $('#myModal p a').remove();
        $('.modal-title').append('' + scope.subreddit.title + '');
        $('.modal-body').append('');

        $('#myModal').modal('show');

    setTimeout( function () {
        $('#myModal').data('bs.modal').handleUpdate();
    } , 800 );

   });

    }
  }
});
//Directive ends

//Next Page
redditApp.directive('nextPage', function(){
     return {
          link: function(scope, element) {
               element.on('click', function() {
	            scope.next = "&after=" + scope.after;
	            scope.count = scope.count + 25;

	            scope.redditify();
               });

           }

     }

});

//Previous Page
redditApp.directive('previousPage', function(){

    return {
         link: function(scope, element){
            element.on('click', function(){
            scope.next = "&before=" + scope.before;
            scope.count = scope.count - 25;

            scope.redditify();

            });

         }

    }

});
<commit_msg>Update app.js<commit_after>//RedditApp Module
var redditApp = angular.module('redditApp', ['ngRoute']);

redditApp.controller('mainController', ['$scope', '$http', '$rootElement', '$timeout',  function($scope, $http, $rootElement, $timeout){

    $scope.next = null;
    $scope.count = 0;
    $scope.page = 1;

    $scope.redditify = function(){
        $scope.sr;
        $scope.success = false;
    	$http.get('http://www.reddit.com/r/' + $scope.sr + '.json?count=' + $scope.count + '&limit=25' + $scope.next)

        .success(function (data){

	        $scope.success = true;
	        $scope.subreddits = [];
        	$scope.next = null;

	        for(var i = 0; i < data.data.children.length; i++)
	       	{
                //Hide placeholder div
                //Show page nav.
                	if(data.data.children.length > 0)
                	{
	                    $('.previouspage, .nextpage').removeClass('hidden');
	                    $('#placeholderdiv').addClass('hidden');
                	}

	                //Dealing with .gifs
	        	var str =  data.data.children[i].data.url;
	                var rest = str.substring(0, str.lastIndexOf("/") + 1);
			var last = str.substring(str.lastIndexOf("/") + 1, str.length);

	                var split = last.split(".");
	                var fileformat = split[1];

                //Check if .gifv format. Not supporting that.
                    	if(fileformat == "gifv")
                        	data.data.children[i].data.url = "http://" + data.data.children[i].data.domain + "/" + split[0] + ".gif";
                    	if(fileformat == "jpg" || fileformat == "png" || fileformat == "bmp" || fileformat =="tif")
                    	{
				$scope.subreddits.push(data.data.children[i].data);
                    	}

                         $scope.after = data.data.after;
                         $scope.before = data.data.before;
                         $scope.subreddit = data.data.children[i].data.subreddit;
            }
        });

     }

}]);

//Directive for showing the info qtip.
redditApp.directive('ngHover', function() {
  return {
    link: function(scope, element) {
	    element.qtip
	    ({
	        position: {
	        my: 'bottom center', // Position it where the click was...
	        at: 'top center',
	        target: element,
	        adjust: { mouse: false } // ...but don't follow the mouse
	        },
	        style: { classes: 'qtip-youtube' },
	       content:
	        {
	       	     text: scope.subreddit.title
		}

	   })

     	element.on('click', function(){

        $('.modal-body').empty();
        $('.modal-title').empty();
        $('#myModal p a').remove();
        $('.modal-title').append('' + scope.subreddit.title + '');
        $('.modal-body').append('');

        $('#myModal').modal('show');

    setTimeout( function () {
        $('#myModal').data('bs.modal').handleUpdate();
    } , 800 );

   });

    }
  }
});
//Directive ends

//Next Page
redditApp.directive('nextPage', function(){
     return {
          link: function(scope, element) {
               element.on('click', function() {
	            scope.next = "&after=" + scope.after;
	            scope.count = scope.count + 25;

	            scope.redditify();
               });

           }

     }

});

//Previous Page
redditApp.directive('previousPage', function(){

    return {
         link: function(scope, element){
            element.on('click', function(){
            scope.next = "&before=" + scope.before;
            scope.count = scope.count - 25;

            scope.redditify();

            });

         }

    }

});
<|endoftext|>


<commit_before>// variables to hold values...
var player_base_move = 30;
var allEnemies = [];
var allGems = [];
var score = 0;
var lives = 3;
var pngWidth = 56; //total width of png: 101
var pngHeight = 56; // total height of png : 171
const WINNING_SCORE = 4; // arbitrary WIN condition

/////////////////////////////////////////////////////////////////////////////
// Gems
var Gem = function(gem_x, gem_y) {
    this.x = gem_x;
    this.y = gem_y;
    //image sprite
    this.sprite = 'images/Gem Blue.png';
};

Gem.prototype.update = function(gem_x, gem_y) {
    this.x = gem_x;
    this.y = gem_y;
};

Gem.prototype.reset = function() {
    var place_x = Math.floor(Math.random() * 450 + 30);
    var place_y = Math.floor(Math.random() * 250 + 30);
    //console.log("Gem reset, now x:" + place_x + " y:" + place_y + "!");
    this.update(place_x, place_y);
};
// Draw the enemy on the screen, required method for game
Gem.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// place the gems
for (var gem = 0; gem < 3; gem++) {
    var place_x = Math.floor(Math.random() * 300 + 30);
    var place_y = Math.floor(Math.random() * 300 + 30);
    var newGem = new Gem(place_x, place_y);
    //console.log(newGem);
    allGems.push(newGem);
}
console.log(allGems);

// if we restart the game, all gems have to be replaced on teh board
function resetAllGems() {
    for (var gem = 0; gem < 3; gem++) {
        allGems[gem].y = Math.floor(Math.random() * 300 + 30);
        allGems[gem].x = Math.floor(Math.random() * 300 + 30);
    }
};

/////////////////////////////////////////////////////////////////
// Enemies our player must avoid
var Enemy = function(enemy_x, enemy_y, startSpeed) {
    // Variables applied to each of our instances go here,
    // we've provided one for you to get started
    this.x = enemy_x;
    this.y = enemy_y;
    this.speed = startSpeed;
    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    this.sprite = 'images/enemy-bug.png';
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    this.x = this.x + this.speed * dt;
    if (this.x > 505) {
        this.speed = this.reset();
    }
    // invoke collision detection
    this.findCollision();
    this.gemCollision();
};

Enemy.prototype.reset = function(speed) {
    this.x = -100;
    var speed = Math.floor(Math.random() * 140 + 40);
    //console.log("Bug reset, new speed is " + speed + "!");
    return speed;
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// method to handle collisions!
Enemy.prototype.findCollision = function() {

    if (player.x < this.x + pngWidth &&
        player.x + pngWidth > this.x &&
        player.y < this.y + pngHeight &&
        player.y + pngHeight > this.y) {
        //collision?
        console.log("Enemy Collision!!!1!");
        lives--;
        document.getElementById("lives").value = lives;
        if (lives < 1) {
            parkEnemies();
            score = 0;
            lives = 0;
            gameMessage("
Sorry, you're out of lives!
Start over?
");
            hideStart();
            hideRestart();
            showReplay();
        } else {
            player.reset(lives + " lives left, continue?");
        }
    }

};

// method to handle collisions!
Enemy.prototype.gemCollision = function() {

    // there are multiple gems!
    for (var gem = 0; gem < allGems.length; gem++) {
        if (allGems[gem].x < this.x + pngWidth &&
            allGems[gem].x + pngWidth > this.x &&
            allGems[gem].y < this.y + pngHeight &&
            allGems[gem].y + pngHeight > this.y) {
            //collision?
            //console.log("Gem Collision!!!1!");
            allGems[gem].reset();
        }
    }
};

// Now write your own player class ////////////////////////////////////////////
// This class requires an update(), render() and
// a handleInput() method.
// Now write your own player class
var Player = function() {
    this.x = 200;
    this.y = 410;
    // NOTE: default player is a girl!
    this.sprite = 'images/char-pink-girl.png';
};

Player.prototype.update = function() {
    //check to see if we've scored a gem.
    this.gemCollision();
    //NOTE: incrementing the score inside here means that it updates multiple times!
};

// event is win or lose, restart the player back to start square
//  and, send on the game message.
Player.prototype.reset = function(msg) {
    this.x = 200;
    this.y = 410;
    console.log("Player starts over!");

    gameMessage(msg);
    // get enemies into position to start over
    parkEnemies();

}

Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

Player.prototype.handleInput = function(event) {
    this.ctlKey = event;
    //console.log(this.ctlKey);

    if (this.ctlKey === 'left' && this.x > 0) {
        this.x -= player_base_move;
    } else if (this.ctlKey === 'right' && this.x < 410) {
        this.x = this.x + player_base_move;
    } else if (this.ctlKey === 'up' && this.y > 18) {
        this.y = this.y - player_base_move;
    } else if (this.ctlKey === 'down' && this.y < 410) {
        this.y = this.y + player_base_move;
    }

    if (player.y === -10) {
        adjustScore();
        var leftToGo = WINNING_SCORE - score;
        if (score >= WINNING_SCORE || leftToGo === 0) {
            restartGame();
        } else {
            player.reset("You WON this round!
Only " + leftToGo + " points to go!");
        }
    }
    //console.log(this.ctlKey + ": I am at x" + this.x + ", y" + this.y);
};

// method to handle collisions!
Player.prototype.gemCollision = function() {

    // there are multiple gems!
    for (var gem = 0; gem < allGems.length; gem++) {
        if (allGems[gem].x < this.x + pngWidth &&
            allGems[gem].x + pngWidth > this.x &&
            allGems[gem].y < this.y + pngHeight &&
            allGems[gem].y + pngHeight > this.y) {
            //collision?
            console.log("Player Gem Collision!!!1!");
            // move the gem offscreen where it won't count anymore
            allGems[gem].y = 1000;
            // increment the score
            adjustScore();
            // test if we've gotten to WIN...
            if (score >= WINNING_SCORE) {
                restartGame();
            }
        }
    }

};

////////////////////////////////////////////////////////////////////////////
// Game functions
////////////////////////////////////////////////////////////////////////////

// decided I wanted predictable paths for bugs, hence the array.
var paths = [65, 145, 226];

for (var path = 0; path < paths.length; path++) {
    //var speed = Math.floor(Math.random() * 140 + 40);
    //var startingLine = Math.floor(Math.random() * 300 + 100);
    // now we START all enemies offscreen, and let the player 'restart' them
    // when they are ready to actually START
    var newEnemy = new Enemy(-200, paths[path], 0);
    //console.log(newEnemy);
    allEnemies.push(newEnemy);
}
console.log(allEnemies);

// all bugs start off at 0 speed offscreen, only get moving when we tell them to
function startEnemies() {
    // add activity to offscreen enemies
    for (var enemy = 0; enemy < allEnemies.length; enemy++) {
        var speed = Math.floor(Math.random() * 140 + 40);
        var startingLine = Math.floor(Math.random() * 300 + 100);
        allEnemies[enemy].x = -startingLine;
        allEnemies[enemy].speed = speed;
    };
    console.log("Restarted enemies!");
    console.log(allEnemies);
}

function parkEnemies() {
    // hide them offscreen until player is ready to restart
    for (var enemy = 0; enemy < allEnemies.length; enemy++) {
        allEnemies[enemy].x = -200;
        allEnemies[enemy].speed = 0;
    };
}

//this is all it takes to start the player object.
var player = new Player();

// This listens for key presses and sends the keys to your
// Player.handleInput() method.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };
    player.handleInput(allowedKeys[e.keyCode]);
});

// increment the score
function adjustScore() {
    score++;
    document.getElementById("score").value = score;
};

///////////////////////////////////////////////////////////////////////////////
// Game Messaging

// take the success/failure/whatever message and send it on to the headline div
function gameMessage(msg) {
    document.getElementById("headline").style.display = "block";
    document.getElementById("headline").innerHTML = msg;
    document.getElementById("game").style.display = "none";
}

// 'Start' button to begin game binding
document.getElementById("start").addEventListener("click", function() {
    showStart();
    hideRestart();
    document.getElementById("game").style.display = "inline";
    document.getElementById("headline").style.display = "none";
    startEnemies();
});

// Next turn button binding
document.getElementById("restart").addEventListener("click", function() {
    showReplay();
    document.getElementById("game").style.display = "inline";
    document.getElementById("headline").style.display = "none";
    startEnemies();
});

// Start over button binding
document.getElementById("replay").addEventListener("click", function() {
    restartGame();
});

// Choose Avatar Button
document.getElementById("chooseAvatar").addEventListener("click", function() {
    console.log("Calling avatar function");
    chooseAvatar();
});

// ABOUT button...
document.getElementById("about").addEventListener("click", function() {
    document.getElementById("aboutThisGame").style.display = "block";
});
// close ABOUT button...
document.getElementById("closeAbout").addEventListener("click", function() {
    document.getElementById("aboutThisGame").style.display = "none";
});

// make the restart a function so that we can call it from player.reset too.
function restartGame() {
    console.log("Resetting game over, score: " + score + " / lives: " + lives);
    if (lives === 0) {
        document.getElementById("headline").style.display = "none";
        document.getElementById("game").style.display = "inline";
    } else {
        document.getElementById("headline").style.display = "block";
        // get current player icon (it can have been changeed) and display it with
        //  won msg
        var sprite = player.sprite;
        var playerPic = "";
        document.getElementById("headline").innerHTML = playerPic +
            "
Terrific! You WON!
 Play Again?
";
        document.getElementById("game").style.display = "none";
    }
    hideReplay();
    hideRestart();
    showStart();
    player.x = 200;
    player.y = 410;
    score = 0;
    document.getElementById("score").value = score;
    console.log("score reset to " + score);
    lives = 3;
    document.getElementById("lives").value = lives;
    //startEnemies();
    resetAllGems();

};

// what the Choose Player Avatar button DOES
//
function chooseAvatar() {
    document.getElementById("avatar").style.display = "block";
    document.getElementById("gameArea").style.display = "none";
    document.getElementById("menu").style.display = "none";
}

function hideRestart() {
    document.getElementById("restart").style.display = "none";
}

function showRestart() {
    document.getElementById("restart").style.display = "inline";
}

function showReplay() {
    document.getElementById("replay").style.display = "inline";
}

function hideReplay() {
    document.getElementById("replay").style.display = "none";
}

function showStart() {
    document.getElementById("start").style.display = "inline";
}

function hideStart() {
    document.getElementById("start").style.display = "none";
}

/////////////////////////////////////////////////////////////////////////////
// Avatars-specific
// first, narrow down the buttons that get the click event added -- only
// the "characters" buttons

var allButtons = document.getElementsByTagName("button");
var characterButtons = [];
for (var btn = 0; btn < allButtons.length; btn++) {
    if (allButtons[btn].parentNode.id === "characters") {
        characterButtons.push(allButtons[btn]);
    }
}
console.log(characterButtons);

// now take that set of character buttons and assign click actions to them
// but we'll have to make it a CLOSURE FUNCTION

// actual action called by callback
function changeCharacter(playerIcon) {
    player.sprite = "images/char-" + playerIcon + ".png";
    //And when we've changed the image, put the screen back the way it was...
    document.getElementById("avatar").style.display = "none";
    document.getElementById("menu").style.display = "inline";
    document.getElementById("gameArea").style.display = "block";
}

// callback to send on the data to the sprite change
function makeChangeCallback(playerIcon) {
    return function() {
        changeCharacter(playerIcon);
    };
}

// function to go through the character buttons, set up the value to be passed
// on to the callback, and instantiate the onclick eventlistener.
function setupPlayerIcon() {

    for (var btn = 0; btn < characterButtons.length; btn++) {
        var playerIcon = characterButtons[btn].id;
        console.log("Setting up onclick for " + playerIcon);
        characterButtons[btn].onclick = makeChangeCallback(playerIcon);
    }
}

// and run the function now!
setupPlayerIcon();<commit_msg>Removed unncessary semicolons per review.<commit_after>// variables to hold values...
var player_base_move = 30;
var allEnemies = [];
var allGems = [];
var score = 0;
var lives = 3;
var pngWidth = 56; //total width of png: 101
var pngHeight = 56; // total height of png : 171
const WINNING_SCORE = 4; // arbitrary WIN condition

/////////////////////////////////////////////////////////////////////////////
// Gems
var Gem = function(gem_x, gem_y) {
    this.x = gem_x;
    this.y = gem_y;
    //image sprite
    this.sprite = 'images/Gem Blue.png';
};

Gem.prototype.update = function(gem_x, gem_y) {
    this.x = gem_x;
    this.y = gem_y;
};

Gem.prototype.reset = function() {
    var place_x = Math.floor(Math.random() * 450 + 30);
    var place_y = Math.floor(Math.random() * 250 + 30);
    //console.log("Gem reset, now x:" + place_x + " y:" + place_y + "!");
    this.update(place_x, place_y);
};
// Draw the enemy on the screen, required method for game
Gem.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// place the gems
for (var gem = 0; gem < 3; gem++) {
    var place_x = Math.floor(Math.random() * 300 + 30);
    var place_y = Math.floor(Math.random() * 300 + 30);
    var newGem = new Gem(place_x, place_y);
    //console.log(newGem);
    allGems.push(newGem);
}
console.log(allGems);

// if we restart the game, all gems have to be replaced on teh board
function resetAllGems() {
    for (var gem = 0; gem < 3; gem++) {
        allGems[gem].y = Math.floor(Math.random() * 300 + 30);
        allGems[gem].x = Math.floor(Math.random() * 300 + 30);
    }
}

/////////////////////////////////////////////////////////////////
// Enemies our player must avoid
var Enemy = function(enemy_x, enemy_y, startSpeed) {
    // Variables applied to each of our instances go here,
    // we've provided one for you to get started
    this.x = enemy_x;
    this.y = enemy_y;
    this.speed = startSpeed;
    // The image/sprite for our enemies, this uses
    // a helper we've provided to easily load images
    this.sprite = 'images/enemy-bug.png';
};

// Update the enemy's position, required method for game
// Parameter: dt, a time delta between ticks
Enemy.prototype.update = function(dt) {
    this.x = this.x + this.speed * dt;
    if (this.x > 505) {
        this.speed = this.reset();
    }
    // invoke collision detection
    this.findCollision();
    this.gemCollision();
};

Enemy.prototype.reset = function(speed) {
    this.x = -100;
    var speed = Math.floor(Math.random() * 140 + 40);
    //console.log("Bug reset, new speed is " + speed + "!");
    return speed;
};

// Draw the enemy on the screen, required method for game
Enemy.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

// method to handle collisions!
Enemy.prototype.findCollision = function() {

    if (player.x < this.x + pngWidth &&
        player.x + pngWidth > this.x &&
        player.y < this.y + pngHeight &&
        player.y + pngHeight > this.y) {
        //collision?
        console.log("Enemy Collision!!!1!");
        lives--;
        document.getElementById("lives").value = lives;
        if (lives < 1) {
            parkEnemies();
            score = 0;
            lives = 0;
            gameMessage("
Sorry, you're out of lives!
Start over?
");
            hideStart();
            hideRestart();
            showReplay();
        } else {
            player.reset(lives + " lives left, continue?");
        }
    }

};

// method to handle collisions!
Enemy.prototype.gemCollision = function() {

    // there are multiple gems!
    for (var gem = 0; gem < allGems.length; gem++) {
        if (allGems[gem].x < this.x + pngWidth &&
            allGems[gem].x + pngWidth > this.x &&
            allGems[gem].y < this.y + pngHeight &&
            allGems[gem].y + pngHeight > this.y) {
            //collision?
            //console.log("Gem Collision!!!1!");
            allGems[gem].reset();
        }
    }
};

// Now write your own player class ////////////////////////////////////////////
// This class requires an update(), render() and
// a handleInput() method.
// Now write your own player class
var Player = function() {
    this.x = 200;
    this.y = 410;
    // NOTE: default player is a girl!
    this.sprite = 'images/char-pink-girl.png';
};

Player.prototype.update = function() {
    //check to see if we've scored a gem.
    this.gemCollision();
    //NOTE: incrementing the score inside here means that it updates multiple times!
};

// event is win or lose, restart the player back to start square
//  and, send on the game message.
Player.prototype.reset = function(msg) {
    this.x = 200;
    this.y = 410;
    console.log("Player starts over!");

    gameMessage(msg);
    // get enemies into position to start over
    parkEnemies();

}

Player.prototype.render = function() {
    ctx.drawImage(Resources.get(this.sprite), this.x, this.y);
};

Player.prototype.handleInput = function(event) {
    this.ctlKey = event;
    //console.log(this.ctlKey);

    if (this.ctlKey === 'left' && this.x > 0) {
        this.x -= player_base_move;
    } else if (this.ctlKey === 'right' && this.x < 410) {
        this.x = this.x + player_base_move;
    } else if (this.ctlKey === 'up' && this.y > 18) {
        this.y = this.y - player_base_move;
    } else if (this.ctlKey === 'down' && this.y < 410) {
        this.y = this.y + player_base_move;
    }

    if (player.y === -10) {
        adjustScore();
        var leftToGo = WINNING_SCORE - score;
        if (score >= WINNING_SCORE || leftToGo === 0) {
            restartGame();
        } else {
            player.reset("You WON this round!
Only " + leftToGo + " points to go!");
        }
    }
    //console.log(this.ctlKey + ": I am at x" + this.x + ", y" + this.y);
};

// method to handle collisions!
Player.prototype.gemCollision = function() {

    // there are multiple gems!
    for (var gem = 0; gem < allGems.length; gem++) {
        if (allGems[gem].x < this.x + pngWidth &&
            allGems[gem].x + pngWidth > this.x &&
            allGems[gem].y < this.y + pngHeight &&
            allGems[gem].y + pngHeight > this.y) {
            //collision?
            console.log("Player Gem Collision!!!1!");
            // move the gem offscreen where it won't count anymore
            allGems[gem].y = 1000;
            // increment the score
            adjustScore();
            // test if we've gotten to WIN...
            if (score >= WINNING_SCORE) {
                restartGame();
            }
        }
    }

};

////////////////////////////////////////////////////////////////////////////
// Game functions
////////////////////////////////////////////////////////////////////////////

// decided I wanted predictable paths for bugs, hence the array.
var paths = [65, 145, 226];

for (var path = 0; path < paths.length; path++) {
    //var speed = Math.floor(Math.random() * 140 + 40);
    //var startingLine = Math.floor(Math.random() * 300 + 100);
    // now we START all enemies offscreen, and let the player 'restart' them
    // when they are ready to actually START
    var newEnemy = new Enemy(-200, paths[path], 0);
    //console.log(newEnemy);
    allEnemies.push(newEnemy);
}
console.log(allEnemies);

// all bugs start off at 0 speed offscreen, only get moving when we tell them to
function startEnemies() {
    // add activity to offscreen enemies
    for (var enemy = 0; enemy < allEnemies.length; enemy++) {
        var speed = Math.floor(Math.random() * 140 + 40);
        var startingLine = Math.floor(Math.random() * 300 + 100);
        allEnemies[enemy].x = -startingLine;
        allEnemies[enemy].speed = speed;
    }
    console.log("Restarted enemies!");
    console.log(allEnemies);
}

function parkEnemies() {
    // hide them offscreen until player is ready to restart
    for (var enemy = 0; enemy < allEnemies.length; enemy++) {
        allEnemies[enemy].x = -200;
        allEnemies[enemy].speed = 0;
    }
}

//this is all it takes to start the player object.
var player = new Player();

// This listens for key presses and sends the keys to your
// Player.handleInput() method.
document.addEventListener('keyup', function(e) {
    var allowedKeys = {
        37: 'left',
        38: 'up',
        39: 'right',
        40: 'down'
    };
    player.handleInput(allowedKeys[e.keyCode]);
});

// increment the score
function adjustScore() {
    score++;
    document.getElementById("score").value = score;
}

///////////////////////////////////////////////////////////////////////////////
// Game Messaging

// take the success/failure/whatever message and send it on to the headline div
function gameMessage(msg) {
    document.getElementById("headline").style.display = "block";
    document.getElementById("headline").innerHTML = msg;
    document.getElementById("game").style.display = "none";
}

// 'Start' button to begin game binding
document.getElementById("start").addEventListener("click", function() {
    showStart();
    hideRestart();
    document.getElementById("game").style.display = "inline";
    document.getElementById("headline").style.display = "none";
    startEnemies();
});

// Next turn button binding
document.getElementById("restart").addEventListener("click", function() {
    showReplay();
    document.getElementById("game").style.display = "inline";
    document.getElementById("headline").style.display = "none";
    startEnemies();
});

// Start over button binding
document.getElementById("replay").addEventListener("click", function() {
    restartGame();
});

// Choose Avatar Button
document.getElementById("chooseAvatar").addEventListener("click", function() {
    console.log("Calling avatar function");
    chooseAvatar();
});

// ABOUT button...
document.getElementById("about").addEventListener("click", function() {
    document.getElementById("aboutThisGame").style.display = "block";
});
// close ABOUT button...
document.getElementById("closeAbout").addEventListener("click", function() {
    document.getElementById("aboutThisGame").style.display = "none";
});

// make the restart a function so that we can call it from player.reset too.
function restartGame() {
    console.log("Resetting game over, score: " + score + " / lives: " + lives);
    if (lives === 0) {
        document.getElementById("headline").style.display = "none";
        document.getElementById("game").style.display = "inline";
    } else {
        document.getElementById("headline").style.display = "block";
        // get current player icon (it can have been changeed) and display it with
        //  won msg
        var sprite = player.sprite;
        var playerPic = "";
        document.getElementById("headline").innerHTML = playerPic +
            "
Terrific! You WON!
 Play Again?
";
        document.getElementById("game").style.display = "none";
    }
    hideReplay();
    hideRestart();
    showStart();
    player.x = 200;
    player.y = 410;
    score = 0;
    document.getElementById("score").value = score;
    console.log("score reset to " + score);
    lives = 3;
    document.getElementById("lives").value = lives;
    //startEnemies();
    resetAllGems();

}

// what the Choose Player Avatar button DOES
//
function chooseAvatar() {
    document.getElementById("avatar").style.display = "block";
    document.getElementById("gameArea").style.display = "none";
    document.getElementById("menu").style.display = "none";
}

function hideRestart() {
    document.getElementById("restart").style.display = "none";
}

function showRestart() {
    document.getElementById("restart").style.display = "inline";
}

function showReplay() {
    document.getElementById("replay").style.display = "inline";
}

function hideReplay() {
    document.getElementById("replay").style.display = "none";
}

function showStart() {
    document.getElementById("start").style.display = "inline";
}

function hideStart() {
    document.getElementById("start").style.display = "none";
}

/////////////////////////////////////////////////////////////////////////////
// Avatars-specific
// first, narrow down the buttons that get the click event added -- only
// the "characters" buttons

var allButtons = document.getElementsByTagName("button");
var characterButtons = [];
for (var btn = 0; btn < allButtons.length; btn++) {
    if (allButtons[btn].parentNode.id === "characters") {
        characterButtons.push(allButtons[btn]);
    }
}
console.log(characterButtons);

// now take that set of character buttons and assign click actions to them
// but we'll have to make it a CLOSURE FUNCTION

// actual action called by callback
function changeCharacter(playerIcon) {
    player.sprite = "images/char-" + playerIcon + ".png";
    //And when we've changed the image, put the screen back the way it was...
    document.getElementById("avatar").style.display = "none";
    document.getElementById("menu").style.display = "inline";
    document.getElementById("gameArea").style.display = "block";
}

// callback to send on the data to the sprite change
function makeChangeCallback(playerIcon) {
    return function() {
        changeCharacter(playerIcon);
    };
}

// function to go through the character buttons, set up the value to be passed
// on to the callback, and instantiate the onclick eventlistener.
function setupPlayerIcon() {

    for (var btn = 0; btn < characterButtons.length; btn++) {
        var playerIcon = characterButtons[btn].id;
        console.log("Setting up onclick for " + playerIcon);
        characterButtons[btn].onclick = makeChangeCallback(playerIcon);
    }
}

// and run the function now!
setupPlayerIcon();<|endoftext|>


<commit_before>(function($)
{
  var router = new $.mobile.Router( [
    {"#page-authorize": {handler: "pageAuthorize",
        events: "s", // do when we show the page
        argsre: true
    } },
    {"#home": {handler: "home",
  		  events: "s", // do when we show the page
  		  argsre: true
		} },

    {"#listing": {handler: "listing",
  	    events: "s", // do when we create the page
  	    argsre: true
    } },
    {"#registering-ruleset": {handler: "registeringRuleset",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#confirming-deletion": {handler: "confirmingDeletion",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#updating-url": {handler: "updatingUrl",
    		events: "s", // do when we show the page
    		argsre: true
		} },
    {"#page-picologging": {handler: "picologging",
		    events: "bs", // do when we show the page
		    argsre: true
    } },
    {"#page-installed-rulesets": {handler: "installed_rulesets",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#install-ruleset": {handler: "install_ruleset",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#confirm-uninstall-ruleset": {handler: "uninstall_ruleset",
				events: "bs", // do when we show the page
				argsre: true

    } }
    ],
      {
        pageAuthorize: function(type, match, ui, page) {
          console.log("manage fuse: authorize page");
          $.mobile.loading("hide");
        },

        home: function(type, match, ui, page) {
          console.log("home Handler");
          $.mobile.loading("hide");
        },

        listing: function(type, match, ui, page) {
          console.log("listing Handler");
          $("#manage-list" ).empty();

          Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
            console.log("attempting rough listview");
            //    var keys = rids_json.sort(sortBy("rid_index"));
            $.each(rids_json, paint_item);
            console.log("refreshing manage-list listview.");
            $('#manage-list').listview('refresh');
          });

        },

        registeringRuleset: function(type, match, ui, page) {
          //example
          //http://www.jquery4u.com?city=Gold Coast
          //console.log($.urlParam('city'));
          //output: Gold%20Coast
          //console.log(decodeURIComponent($.urlParam('city')));
          //output: Gold Coast

          console.log("registering Ruleset Handler");
          var frm = "#formRegisterNewRuleset";
            $(frm)[0].reset(); // clear the fields in the form
          $('#regester-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "registering ruleset...",
              textVisible: true
            });
            var registering_form_data = process_form(frm);
            console.log(">>>>>>>>> RID to register", registering_form_data);
            var appURL = registering_form_data.appURL;

            if(typeof appURL !== "undefined") {
              Devtools.RegisterRulesets(appURL, function(directives) {
                console.log("registered ", appURL, directives);
                $.mobile.changePage("#listing", {
                 transition: 'slide'
               });
              });
            }
          });

        },

        confirmingDeletion: function(type, match, ui, page) {
          console.log("confirming Deletion Handler");
        },

        updatingUrl: function(type, match, ui, page) {
          console.log("updating Url Handler");
          var rid = router.getParams(match[1])["rid"]; //not sure if this will still work
          console.log("RID to update URL of: ", rid);
          var frm = "#form-update-url";

          $(frm)[0].reset(); // clear the fields in the form
          $('#update-url-confirm-button').off('tap').on('tap', function(event)
          {
            $.mobile.loading("show", {
              text: "Updating URL...",
              textVisible: true
            });
            var update_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", update_form_data);
            var url = update_form_data.url;

            if(typeof url !== "undefined") {
              /*Devtools.installRulesets(rid, function(directives) {
                console.log("installed ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                  transition: 'slide' //all of this found in install_rulesets */
                Devtools.updateURL(rid, url, function(){
                  console.log("updating the function is running");
                  $.mobile.changePage("#listing", {
                    transition: 'slide'
                   });
                });

            }

          });

        },

        picologging: function(type, match, ui, page) {
          console.log("pico logging page");
          $.mobile.loading("hide");

          function populate_logpage() {
            Pico.logging.status(CloudOS.defaultECI, function(json){
              console.log("Logging status: ", json);
              if(json) {
               $("#logstatus").val("on").slider("refresh");
               $("#loglist" ).empty();
               Pico.logging.getLogs(CloudOS.defaultECI, function(logdata){
                 console.log("Retrieved logs");
                 $.each(logdata, function(i, logobj) {
                  var eid_re = RegExp("\\s+" + logobj.eid);
                  logobj.log_items = logobj.log_items.map(function(i){ return i.replace(eid_re, '');
                  });
                  $("#loglist" ).append(
                   snippets.logitem_template(logobj)
                   ).collapsibleset().collapsibleset( "refresh" );
                  $("#loglist").listview("refresh");
                 });
               });

              } else {
               $("#logstatus").val("off").slider("refresh");
              }
            });
          }

          populate_logpage();

        	    // triggers
              $("#logstatus").unbind("change").change(function(){
                var newstatus = $("#logstatus").val();
                if(newstatus === "on") {
                  Pico.logging.reset(CloudOS.defaultECI, {});
                  populate_logpage();
                } else {
                  Pico.logging.inactive(CloudOS.defaultECI, {});
                  $("#loglist" ).empty();
                }
              });
              $( "#logrefresh" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                populate_logpage();
              });
              $( "#logclear" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                Pico.logging.flush(CloudOS.defaultECI, {});
              });

          },

        installed_rulesets: function(type, match, ui, page) {
          console.log("ruleset installation page");
          $.mobile.loading("hide");

          function populate_installed_rulesets() {
            $("#installed-rulesets" ).empty();
            Devtools.showInstalledRulesets(function(ruleset_list){
             console.log("Retrieved installed rulesets");
             $.each(ruleset_list, function(k, ruleset) {
               ruleset["rid"] = k;
      			    ruleset["OK"] = k !== "a169x625.prod"; // don't allow deletion of CloudOS; this could be more robust
      			    $("#installed-rulesets" ).append(
                 snippets.installed_ruleset_template(ruleset)
                 ).collapsibleset().collapsibleset( "refresh" );
      			    $("#installed-rulesets").listview("refresh");
             });
           });
          };

          populate_installed_rulesets();

          },

        uninstall_ruleset: function(type, match, ui, page) {
           console.log("Showing uninstall ruleset page");
           $.mobile.loading("hide");
           var rid = router.getParams(match[1])["rid"];
           console.log("RID to uninstall: ", rid);
           $("#remove-ruleset" ).empty();
           $("#remove-ruleset").append(snippets.confirm_ruleset_remove({"rid": rid}));
           $("#remove-ruleset").listview().listview("refresh");
           $('#remove-ruleset-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Uninstalling ruleset...",
              textVisible: true
            });
            console.log("Uninstalling RID ", rid);
            if(typeof rid !== "undefined") {
              Devtools.uninstallRulesets(rid, function(directives) {
                console.log("uninstalled ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
           });
      	},

      	install_ruleset: function(type, match, ui, page) {
         console.log("Showing install ruleset page");
         $.mobile.loading("hide");
         var frm = "#form-install-ruleset";
      	    $(frm)[0].reset(); // clear the fields in the form
           $('#install-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Installing ruleset...",
              textVisible: true
            });
            var install_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", install_form_data);
            var rid = install_form_data.rid;

            if(typeof rid !== "undefined") {
              Devtools.installRulesets(rid, function(directives) {
                console.log("installed ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
          });
         }
        },

      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route:", type, ui, page );
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });

      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
          list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
          logitem_template: Handlebars.compile($("#logitem-template").html() || ""),
          installed_ruleset_template: Handlebars.compile($("#installed-ruleset-template").html() || ""),
	        confirm_ruleset_remove: Handlebars.compile($("#confirm-ruleset-remove-template").html() || "")
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

      function onPageLoad() {// Document.Ready
      	console.log("document ready");
        CloudOS.retrieveSession();
  	    // only put static stuff here...
  	    plant_authorize_button();

  	    $('.logout').off("tap").on("tap", function(event)
        {
  	      CloudOS.removeSession(true); // true for hard reset (log out of login server too)
  	      $.mobile.changePage('#page-authorize', {
            transition: 'slide'
  	      }); // this will go to the authorization page.
        });

        Handlebars.registerHelper('ifDivider', function(v1, options) {
         if(v1.match(/-----\*\*\*----/)) {
          return options.fn(this);
         }
          return options.inverse(this);
         });

        console.log("Choose page to show");

        try {
          var authd = CloudOS.authenticatedSession();
          if(authd) {
            console.log("Authorized");
            document.location.hash = "#home";
          } else {
            console.log("Asking for authorization");
            document.location.hash = "#page-authorize";
          }
        } catch (exception) {

        } finally {
          $.mobile.initializePage();
          $.mobile.loading("hide");
        }

      }

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
      $(document).bind("mobileinit", onMobileInit);
      $(document).ready(onPageLoad);
  })(jQuery);

  function clear_error_msg(frm) {// we dont have #error-msg ---------------
       $("#error-msg", frm).html("").hide();
  }
  function sortBy(prop){

    return function(a,b){

    //if a and b match regex /\w+\d+xd+\.\w+/
    // split on .
      // split on x
        //compare
      if( a[prop] < b[prop]){
        return 1;
      }else if( a[prop] > b[prop] ){
        return -1;
      }
      return 0;
    };
  };

  function paint_item(id, rids) {
    var status = "no status"; // place holder for description
    console.log("rid: "+ rids.rid);

    $('#manage-list').append(
      snippets.list_rulesets_template(
        {"rid": rids["rid"],
        "uri": rids["uri"]}
      )
    );
  };

  var sortByName = function (a, b) {
  	if (a.name > b.name) {
  	    return 1;
  	}
  	if (a.name < b.name) {
  	    return -1;
  	}
  	// a must be equal to b
  	return 0;
  };

    // process an array of objects from a form to be a proper object
  var process_form_results = function(raw_results) {
  	var results = {};
  	$.each(raw_results, function(i, v) {
  		var nym = v.name,
   	  val = v.value;
  		if (results[nym] && results[nym] instanceof Array) {
  		  results[nym].push(val);
  		} else if (results[nym]) {
  		  results[nym] = [results[nym], val];
  		} else {
  		  results[nym] = val;
  		}
  	});
  	return results;
  };

  var process_form = function(frm) {
	 var results = process_form_results($(frm).serializeArray());
	 return results;
  };

<commit_msg>dead code<commit_after>(function($)
{
  var router = new $.mobile.Router( [
    {"#page-authorize": {handler: "pageAuthorize",
        events: "s", // do when we show the page
        argsre: true
    } },
    {"#home": {handler: "home",
  		  events: "s", // do when we show the page
  		  argsre: true
		} },

    {"#listing": {handler: "listing",
  	    events: "s", // do when we create the page
  	    argsre: true
    } },
    {"#registering-ruleset": {handler: "registeringRuleset",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#confirming-deletion": {handler: "confirmingDeletion",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#updating-url": {handler: "updatingUrl",
    		events: "s", // do when we show the page
    		argsre: true
		} },
    {"#page-picologging": {handler: "picologging",
		    events: "bs", // do when we show the page
		    argsre: true
    } },
    {"#page-installed-rulesets": {handler: "installed_rulesets",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#install-ruleset": {handler: "install_ruleset",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#confirm-uninstall-ruleset": {handler: "uninstall_ruleset",
				events: "bs", // do when we show the page
				argsre: true

    } }
    ],
      {
        pageAuthorize: function(type, match, ui, page) {
          console.log("manage fuse: authorize page");
          $.mobile.loading("hide");
        },

        home: function(type, match, ui, page) {
          console.log("home Handler");
          $.mobile.loading("hide");
        },

        listing: function(type, match, ui, page) {
          console.log("listing Handler");
          $("#manage-list" ).empty();

          Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
            console.log("attempting rough listview");
            //    var keys = rids_json.sort(sortBy("rid_index"));
            $.each(rids_json, paint_item);
            console.log("refreshing manage-list listview.");
            $('#manage-list').listview('refresh');
          });

        },

        registeringRuleset: function(type, match, ui, page) {

          console.log("registering Ruleset Handler");
          var frm = "#formRegisterNewRuleset";
            $(frm)[0].reset(); // clear the fields in the form
          $('#regester-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "registering ruleset...",
              textVisible: true
            });
            var registering_form_data = process_form(frm);
            console.log(">>>>>>>>> RID to register", registering_form_data);
            var appURL = registering_form_data.appURL;

            if(typeof appURL !== "undefined") {
              Devtools.RegisterRulesets(appURL, function(directives) {
                console.log("registered ", appURL, directives);
                $.mobile.changePage("#listing", {
                 transition: 'slide'
               });
              });
            }
          });

        },

        confirmingDeletion: function(type, match, ui, page) {
          console.log("confirming Deletion Handler");
        },

        updatingUrl: function(type, match, ui, page) {
          console.log("updating Url Handler");
          var rid = router.getParams(match[1])["rid"]; //not sure if this will still work
          console.log("RID to update URL of: ", rid);
          var frm = "#form-update-url";

          $(frm)[0].reset(); // clear the fields in the form
          $('#update-url-confirm-button').off('tap').on('tap', function(event)
          {
            $.mobile.loading("show", {
              text: "Updating URL...",
              textVisible: true
            });
            var update_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", update_form_data);
            var url = update_form_data.url;

            if(typeof url !== "undefined") {
              /*Devtools.installRulesets(rid, function(directives) {
                console.log("installed ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                  transition: 'slide' //all of this found in install_rulesets */
                Devtools.updateURL(rid, url, function(){
                  console.log("updating the function is running");
                  $.mobile.changePage("#listing", {
                    transition: 'slide'
                   });
                });

            }

          });

        },

        picologging: function(type, match, ui, page) {
          console.log("pico logging page");
          $.mobile.loading("hide");

          function populate_logpage() {
            Pico.logging.status(CloudOS.defaultECI, function(json){
              console.log("Logging status: ", json);
              if(json) {
               $("#logstatus").val("on").slider("refresh");
               $("#loglist" ).empty();
               Pico.logging.getLogs(CloudOS.defaultECI, function(logdata){
                 console.log("Retrieved logs");
                 $.each(logdata, function(i, logobj) {
                  var eid_re = RegExp("\\s+" + logobj.eid);
                  logobj.log_items = logobj.log_items.map(function(i){ return i.replace(eid_re, '');
                  });
                  $("#loglist" ).append(
                   snippets.logitem_template(logobj)
                   ).collapsibleset().collapsibleset( "refresh" );
                  $("#loglist").listview("refresh");
                 });
               });

              } else {
               $("#logstatus").val("off").slider("refresh");
              }
            });
          }

          populate_logpage();

        	    // triggers
              $("#logstatus").unbind("change").change(function(){
                var newstatus = $("#logstatus").val();
                if(newstatus === "on") {
                  Pico.logging.reset(CloudOS.defaultECI, {});
                  populate_logpage();
                } else {
                  Pico.logging.inactive(CloudOS.defaultECI, {});
                  $("#loglist" ).empty();
                }
              });
              $( "#logrefresh" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                populate_logpage();
              });
              $( "#logclear" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                Pico.logging.flush(CloudOS.defaultECI, {});
              });

          },

        installed_rulesets: function(type, match, ui, page) {
          console.log("ruleset installation page");
          $.mobile.loading("hide");

          function populate_installed_rulesets() {
            $("#installed-rulesets" ).empty();
            Devtools.showInstalledRulesets(function(ruleset_list){
             console.log("Retrieved installed rulesets");
             $.each(ruleset_list, function(k, ruleset) {
               ruleset["rid"] = k;
      			    ruleset["OK"] = k !== "a169x625.prod"; // don't allow deletion of CloudOS; this could be more robust
      			    $("#installed-rulesets" ).append(
                 snippets.installed_ruleset_template(ruleset)
                 ).collapsibleset().collapsibleset( "refresh" );
      			    $("#installed-rulesets").listview("refresh");
             });
           });
          };

          populate_installed_rulesets();

          },

        uninstall_ruleset: function(type, match, ui, page) {
           console.log("Showing uninstall ruleset page");
           $.mobile.loading("hide");
           var rid = router.getParams(match[1])["rid"];
           console.log("RID to uninstall: ", rid);
           $("#remove-ruleset" ).empty();
           $("#remove-ruleset").append(snippets.confirm_ruleset_remove({"rid": rid}));
           $("#remove-ruleset").listview().listview("refresh");
           $('#remove-ruleset-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Uninstalling ruleset...",
              textVisible: true
            });
            console.log("Uninstalling RID ", rid);
            if(typeof rid !== "undefined") {
              Devtools.uninstallRulesets(rid, function(directives) {
                console.log("uninstalled ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
           });
      	},

      	install_ruleset: function(type, match, ui, page) {
         console.log("Showing install ruleset page");
         $.mobile.loading("hide");
         var frm = "#form-install-ruleset";
      	    $(frm)[0].reset(); // clear the fields in the form
           $('#install-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Installing ruleset...",
              textVisible: true
            });
            var install_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", install_form_data);
            var rid = install_form_data.rid;

            if(typeof rid !== "undefined") {
              Devtools.installRulesets(rid, function(directives) {
                console.log("installed ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
          });
         }
        },

      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route:", type, ui, page );
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });

      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
          list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
          logitem_template: Handlebars.compile($("#logitem-template").html() || ""),
          installed_ruleset_template: Handlebars.compile($("#installed-ruleset-template").html() || ""),
	        confirm_ruleset_remove: Handlebars.compile($("#confirm-ruleset-remove-template").html() || "")
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

      function onPageLoad() {// Document.Ready
      	console.log("document ready");
        CloudOS.retrieveSession();
  	    // only put static stuff here...
  	    plant_authorize_button();

  	    $('.logout').off("tap").on("tap", function(event)
        {
  	      CloudOS.removeSession(true); // true for hard reset (log out of login server too)
  	      $.mobile.changePage('#page-authorize', {
            transition: 'slide'
  	      }); // this will go to the authorization page.
        });

        Handlebars.registerHelper('ifDivider', function(v1, options) {
         if(v1.match(/-----\*\*\*----/)) {
          return options.fn(this);
         }
          return options.inverse(this);
         });

        console.log("Choose page to show");

        try {
          var authd = CloudOS.authenticatedSession();
          if(authd) {
            console.log("Authorized");
            document.location.hash = "#home";
          } else {
            console.log("Asking for authorization");
            document.location.hash = "#page-authorize";
          }
        } catch (exception) {

        } finally {
          $.mobile.initializePage();
          $.mobile.loading("hide");
        }

      }

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
      $(document).bind("mobileinit", onMobileInit);
      $(document).ready(onPageLoad);
  })(jQuery);

  function clear_error_msg(frm) {// we dont have #error-msg ---------------
       $("#error-msg", frm).html("").hide();
  }
  function sortBy(prop){

    return function(a,b){

    //if a and b match regex /\w+\d+xd+\.\w+/
    // split on .
      // split on x
        //compare
      if( a[prop] < b[prop]){
        return 1;
      }else if( a[prop] > b[prop] ){
        return -1;
      }
      return 0;
    };
  };

  function paint_item(id, rids) {
    var status = "no status"; // place holder for description
    console.log("rid: "+ rids.rid);

    $('#manage-list').append(
      snippets.list_rulesets_template(
        {"rid": rids["rid"],
        "uri": rids["uri"]}
      )
    );
  };

  var sortByName = function (a, b) {
  	if (a.name > b.name) {
  	    return 1;
  	}
  	if (a.name < b.name) {
  	    return -1;
  	}
  	// a must be equal to b
  	return 0;
  };

    // process an array of objects from a form to be a proper object
  var process_form_results = function(raw_results) {
  	var results = {};
  	$.each(raw_results, function(i, v) {
  		var nym = v.name,
   	  val = v.value;
  		if (results[nym] && results[nym] instanceof Array) {
  		  results[nym].push(val);
  		} else if (results[nym]) {
  		  results[nym] = [results[nym], val];
  		} else {
  		  results[nym] = val;
  		}
  	});
  	return results;
  };

  var process_form = function(frm) {
	 var results = process_form_results($(frm).serializeArray());
	 return results;
  };

<|endoftext|>


<commit_before>(function($) {

	"use strict";

	var options = {
		events_source: 'events.json.php',
		view: 'month',
		tmpl_path: 'tmpls/',
		tmpl_cache: false,
		day: '2013-03-12',
		onAfterEventsLoad: function(events) {
			if(!events) {
				return;
			}
			var list = $('#eventlist');
			list.html('');

			$.each(events, function(key, val) {
				$(document.createElement('li'))
					.html('' + val.title + '')
					.appendTo(list);
			});
		},
		onAfterViewLoad: function(view) {
			$('.page-header h3').text(this.getTitle());
			$('.btn-group button').removeClass('active');
			$('button[data-calendar-view="' + view + '"]').addClass('active');
		},
		classes: {
			months: {
				general: 'label'
			}
		}
	};

	var calendar = $('#calendar').calendar(options);

	$('.btn-group button[data-calendar-nav]').each(function() {
		var $this = $(this);
		$this.click(function() {
			calendar.navigate($this.data('calendar-nav'));
		});
	});

	$('.btn-group button[data-calendar-view]').each(function() {
		var $this = $(this);
		$this.click(function() {
			calendar.view($this.data('calendar-view'));
		});
	});

	$('#first_day').change(function(){
		var value = $(this).val();
		value = value.length ? parseInt(value) : null;
		calendar.setOptions({first_day: value});
		calendar.view();
	});

	$('#language').change(function(){
		calendar.setLanguage($(this).val());
		calendar.view();
	});

	$('#events-in-modal').change(function(){
		var val = $(this).is(':checked') ? $(this).val() : null;
		calendar.setOptions({modal: val});
	});
	$('#events-modal .modal-header, #events-modal .modal-footer').click(function(e){
		e.preventDefault();
		e.stopPropagation();
	});
}(jQuery));<commit_msg>Modal fix<commit_after>(function($) {

	"use strict";

	var options = {
		events_source: 'events.json.php',
		view: 'month',
		tmpl_path: 'tmpls/',
		tmpl_cache: false,
		day: '2013-03-12',
		onAfterEventsLoad: function(events) {
			if(!events) {
				return;
			}
			var list = $('#eventlist');
			list.html('');

			$.each(events, function(key, val) {
				$(document.createElement('li'))
					.html('' + val.title + '')
					.appendTo(list);
			});
		},
		onAfterViewLoad: function(view) {
			$('.page-header h3').text(this.getTitle());
			$('.btn-group button').removeClass('active');
			$('button[data-calendar-view="' + view + '"]').addClass('active');
		},
		classes: {
			months: {
				general: 'label'
			}
		}
	};

	var calendar = $('#calendar').calendar(options);

	$('.btn-group button[data-calendar-nav]').each(function() {
		var $this = $(this);
		$this.click(function() {
			calendar.navigate($this.data('calendar-nav'));
		});
	});

	$('.btn-group button[data-calendar-view]').each(function() {
		var $this = $(this);
		$this.click(function() {
			calendar.view($this.data('calendar-view'));
		});
	});

	$('#first_day').change(function(){
		var value = $(this).val();
		value = value.length ? parseInt(value) : null;
		calendar.setOptions({first_day: value});
		calendar.view();
	});

	$('#language').change(function(){
		calendar.setLanguage($(this).val());
		calendar.view();
	});

	$('#events-in-modal').change(function(){
		var val = $(this).is(':checked') ? $(this).val() : null;
		calendar.setOptions({modal: val});
	});
	$('#events-modal .modal-header, #events-modal .modal-footer').click(function(e){
		//e.preventDefault();
		//e.stopPropagation();
	});
}(jQuery));<|endoftext|>