<commit_before>var VError, async, mongoose, jsonSelect, nconf, courses, calendar, history, Schema, schema;

VError = require('verror');
async = require('async');
mongoose = require('mongoose');
jsonSelect = require('mongoose-json-select');
courses = require('dacos-courses-driver');
calendar = require('dacos-calendar-driver');
history = require('dacos-history-driver');
nconf = require('nconf');
Schema = mongoose.Schema;

schema = new Schema({
  'enrollment' : {
    'type'     : Schema.ObjectId,
    'ref'      : 'Enrollment',
    'required' : true
  },
  'discipline' : {
    'type'     : String,
    'required' : true
  },
  'offering'   : {
    'type'     : String,
    'required' : true
  },
  'status'     : {
    'type'    : String,
    'enum'    : [ 'new', 'approved', 'rejected', 'quit' ],
    'default' : 'new'
  },
  'comment'    : {
    'type' : String
  },
  'priority'   : {
    'type' : Number
  },
  'createdAt'  : {
    'type'    : Date,
    'default' : Date.now
  },
  'updatedAt'  : {
    'type' : Date
  }
}, {
  'collection' : 'requirements',
  'strict'     : true,
  'toJSON'     : {
    'virtuals' : true
  }
});

schema.index({
  'enrollment' : 1,
  'discipline' : 1,
  'offering'   : 1
}, {
  'unique' : true
});

schema.plugin(jsonSelect, {
  '_id'        : 0,
  'enrollment' : 1,
  'discipline' : 1,
  'offering'   : 1,
  'status'     : 1,
  'comment'    : 1,
  'priority'   : 1,
  'createdAt'  : 1,
  'updatedAt'  : 1
});

schema.pre('save', function setRequirementUpdatedAt(next) {
  'use strict';

  this.updatedAt = new Date();
  next();
});

schema.pre('save', function setPriorityScore(next) {
  'use strict';

  var priorityScore;

  this.populate('enrollment');
  this.populate(function () {
    getDisciplineInformation(this.enrollment, this.discipline, this.offering, function (blockType, isAhead, isReserved) {

      // Calculating priority score
      if (blockType === 'required') {
        // Obligatory discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 6;
          } else {
            priorityScore = 3;
          }
        } else {
          if (isReserved) {
            priorityScore = 9;
          } else {
            priorityScore = 7;
          }
        }
      } else if (blockType === 'optional') {
        // Optional discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 5;
          } else {
            priorityScore = 2;
          }
        } else {
          if (isReserved) {
            priorityScore = 8;
          } else {
            priorityScore = 4;
          }
        }
      } else if (blockType === 'extra') {
        // Extra-curricular discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 1;
          } else {
            priorityScore = 0;
          }
        } else {
          // TODO check why this is equal to the last conditional
          if (isReserved) {
            priorityScore = 1;
          } else {
            priorityScore = 0;
          }
        }
      }

      this.priority = priorityScore;
      //console.log(this.priority);

      next();
    }.bind(this));
  }.bind(this));
});

function getDisciplineInformation(enrollment, discipline, disciplineOffering, next) {
  'use strict';

  var blockType , isAhead, isReserved;

  blockType = 'optional';
  isAhead = false;
  isReserved = false;

  history.currentHistory(enrollment.user, function (error, currentHistory) {

    if (error) {
      error = new VError(error, 'Error when trying to get the history');
      return next(error);
    }

    if (!currentHistory) {
      return next(false);
    }

    courses.blocks(currentHistory.year, currentHistory.course + ' ' + currentHistory.modality, function (error, blocks) {
      if (error) {
        return next('');
      }

      async.some(blocks, function(block) {

        courses.requirement(currentHistory.year, currentHistory.course + ' ' + currentHistory.modality, block.code, this.discipline, function (error, requirement) {
          if (requirement) {
            var currentDate = new Date();

            var currentSemester;
            if (currentDate.getMonth() < 6) {
              currentSemester = 1;
            } else if(currentDate.getMonth() > 6) {
              currentSemester = 2;
            } else {
              currentSemester = currentDate.getDay() < 15 ? 1 : 2;
            }

            //TODO figure out how to get the offering reservation

            var userSemester = (currentDate.getFullYear() - currentHistory.year) * 2 + currentSemester;
            //var offeringReservations = disciplineOffering && disciplineOffering.reservations || [];

            blockType = block.type;
            //isAhead = offeringReservations.some(function (offeringReservation) { return offeringReservation === historyId; });
            isReserved = requirement && (userSemester < requirement.suggestedSemester);

            //requirement.code

            next(true);
          }
          else {
            next(false);
          }
        });
      }, function(result) {
        next(blockType, isAhead, isReserved);
      });
    });
  });
}

/**
 * Verifica se uma solicitação de aumento de limite de créditos deve ser aberta
 */
schema.pre('save', function openCreditRaiseRequestIfNecessary(next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'requirements': function (next) {
        var query;
        query = this.model('Requirement').find();
        query.where('enrollment').equals(this.enrollment._id);
        query.where('_id').ne(this._id);
        query.exec(next);
      }.bind(this),
      'modality'   : function (next) {
        async.waterfall([function (next) {
          history.currentHistory(this.enrollment.user, next);
        }.bind(this), function (currentHistory, next) {
          courses.modality(currentHistory.year, currentHistory.course + '-' + currentHistory.modality, next);
        }.bind(this)], next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    // sum the actual requirement together with all other requirements
    data.requirements.push(this);

    async.reduce(data.requirements, 0, function (sum, disciplineRequirement, next) {
      courses.discipline(disciplineRequirement.discipline, function (error, discipline) {
        next(error, discipline ? discipline.credits + sum : 0);
      }.bind(this));
    }.bind(this), function (error, credits) {
      if (error) {
        error = new VError(error, 'Error when trying to sum the credits');
        return next(error);
      }

      if (credits <= data.modality.creditLimit) {
        return next();
      }

      this.enrollment.creditRaiseRequest.credits = credits;
      this.enrollment.creditRaiseRequest.date = new Date();
      this.enrollment.creditRaiseRequest.status = 'pending';
      this.enrollment.save(next);
    }.bind(this));
  }.bind(this)], next);
});

schema.path('offering').validate(function validateIfDisciplineOfferingExists(value, next) {
  'use strict';

  courses.offering(this.discipline, this.offering, function foundDisciplineOffering(error, offering) {
    next(!error && !!offering);
  });
}, 'discipline offering not found');

schema.path('discipline').validate(function validateDisciplineRequirement(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'discipline': function (next) {
        courses.discipline(this.discipline, next);
      }.bind(this),
      'histories' : function (next) {
        history.histories(this.enrollment.user, next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.histories, function (userHistory) {
      if (data.discipline.requirements.length > 0) {
        data.discipline.requirements.forEach(function (disciplineRequirement) {
          history.discipline(this.enrollment.user, userHistory.year, disciplineRequirement.code, function (error, disciplineHistory) {
            next(!!error || (disciplineHistory && [1, 2, 3, 4, 7, 10, 11, 12, 13, 14, 15, 16, 20].lastIndexOf(disciplineHistory.status) > -1));
          }.bind(this));
        }.bind(this));
      }
      else {
        next();
      }
    }.bind(this), next);
  }.bind(this)], next);
}, 'discipline requirement not fulfilled');

schema.path('status').validate(function validateIfRequirementCanBeQuit(value, next) {
  'use strict';
  var todayDate, year;
  todayDate = new Date();
  year = todayDate.getFullYear();

  if (this.status === 'quit') {
    calendar.betweenEvents(todayDate, year, 'discipline-quit-starts', year, 'discipline-quit-ends', next);
  }
  else {
    next();
  }
}, 'outside of discipline quit period');

schema.path('discipline').validate(function validateDisciplineApproval(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'histories'  : function (next) {
        history.histories(this.enrollment.user, next);
      }.bind(this),
      'discipline' : function (next) {
        courses.discipline(this.discipline, next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.histories, function (userHistory, next) {
      history.discipline(this.enrollment.user, userHistory.year, data.discipline.code, function (error, disciplineHistory) {
        next(!!error || !(disciplineHistory && [1, 2, 3, 4, 7, 10, 11, 12, 13, 14, 15, 16, 20].lastIndexOf(disciplineHistory.status) > -1));
      }.bind(this));
    }.bind(this), next);
  }.bind(this)], next);
}, 'user was already approved on discipline');

schema.path('offering').validate(function validateIfRequirementHasTimeConflict(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'offering'    : function (next) {
        courses.offering(this.discipline, this.offering, next);
      }.bind(this),
      'requirements': function (next) {
        var query;

        query = this.model('Requirement').find();
        query.where('enrollment').equals(this.enrollment._id);
        query.where('_id').ne(this._id);
        query.where('discipline').ne(this.discipline);
        query.exec(next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.requirements, function (requirement, next) {
      courses.offering(requirement.discipline, requirement.offering, function foundDisciplineOffering(error, offeringConflict) {
        var conflict = data.offering.schedules.some(function (schedule) {
          return offeringConflict.schedules.some(function (otherSchedule) {
            return (schedule.weekday === otherSchedule.weekday && schedule.hour === otherSchedule.hour);
          });
        });

        next(!!error || !conflict);
      });
    }.bind(this), next);
  }.bind(this)], next);
}, 'discipline with time conflict');

module.exports = mongoose.model('Requirement', schema);
<commit_msg>Calcular a prioridade #4<commit_after>var VError, async, mongoose, jsonSelect, nconf, courses, calendar, history, Schema, schema;

VError = require('verror');
async = require('async');
mongoose = require('mongoose');
jsonSelect = require('mongoose-json-select');
courses = require('dacos-courses-driver');
calendar = require('dacos-calendar-driver');
history = require('dacos-history-driver');
nconf = require('nconf');
Schema = mongoose.Schema;

schema = new Schema({
  'enrollment' : {
    'type'     : Schema.ObjectId,
    'ref'      : 'Enrollment',
    'required' : true
  },
  'discipline' : {
    'type'     : String,
    'required' : true
  },
  'offering'   : {
    'type'     : String,
    'required' : true
  },
  'status'     : {
    'type'    : String,
    'enum'    : [ 'new', 'approved', 'rejected', 'quit' ],
    'default' : 'new'
  },
  'comment'    : {
    'type' : String
  },
  'priority'   : {
    'type' : Number
  },
  'createdAt'  : {
    'type'    : Date,
    'default' : Date.now
  },
  'updatedAt'  : {
    'type' : Date
  }
}, {
  'collection' : 'requirements',
  'strict'     : true,
  'toJSON'     : {
    'virtuals' : true
  }
});

schema.index({
  'enrollment' : 1,
  'discipline' : 1,
  'offering'   : 1
}, {
  'unique' : true
});

schema.plugin(jsonSelect, {
  '_id'        : 0,
  'enrollment' : 1,
  'discipline' : 1,
  'offering'   : 1,
  'status'     : 1,
  'comment'    : 1,
  'priority'   : 1,
  'createdAt'  : 1,
  'updatedAt'  : 1
});

schema.pre('save', function setRequirementUpdatedAt(next) {
  'use strict';

  this.updatedAt = new Date();
  next();
});

schema.pre('save', function setPriorityScore(next) {
  'use strict';

  var priorityScore;

  this.populate('enrollment');
  this.populate(function () {
    getDisciplineInformation(this.enrollment, this.discipline, this.offering, function (blockType, isAhead, isReserved) {

      // Calculating priority score
      if (blockType === 'required') {
        // Obligatory discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 6;
          } else {
            priorityScore = 3;
          }
        } else {
          if (isReserved) {
            priorityScore = 9;
          } else {
            priorityScore = 7;
          }
        }
      } else if (blockType === 'optional') {
        // Optional discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 5;
          } else {
            priorityScore = 2;
          }
        } else {
          if (isReserved) {
            priorityScore = 8;
          } else {
            priorityScore = 4;
          }
        }
      } else if (blockType === 'extra') {
        // Extra-curricular discipline
        if (isAhead) {
          if (isReserved) {
            priorityScore = 1;
          } else {
            priorityScore = 0;
          }
        } else {
          // TODO check why this is equal to the last conditional
          if (isReserved) {
            priorityScore = 1;
          } else {
            priorityScore = 0;
          }
        }
      }

      this.priority = priorityScore;
      //console.log(this.priority);

      next();
    }.bind(this));
  }.bind(this));
});

function getDisciplineInformation(enrollment, discipline, disciplineOffering, next) {
  'use strict';

  var blockType , isAhead, isReserved;

  blockType = 'optional';
  isAhead = false;
  isReserved = false;

  history.currentHistory(enrollment.user, function (error, currentHistory) {

    courses.blocks(currentHistory.year, currentHistory.course + ' ' + currentHistory.modality, function (error, blocks) {
      async.some(blocks, function(block) {

        courses.requirement(currentHistory.year, currentHistory.course + ' ' + currentHistory.modality, block.code, this.discipline, function (error, requirement) {
          if (requirement) {
            var currentDate = new Date();

            var currentSemester;
            if (currentDate.getMonth() < 6) {
              currentSemester = 1;
            } else if(currentDate.getMonth() > 6) {
              currentSemester = 2;
            } else {
              currentSemester = currentDate.getDay() < 15 ? 1 : 2;
            }

            courses.offering(this.discipline, this.offering, function foundDisciplineOffering(error, offering) {

              var userSemester = (currentDate.getFullYear() - currentHistory.year) * 2 + currentSemester;
              var offeringReservations = offering && offering.reservations || [];

              blockType = block.type;
              isAhead = offeringReservations.some(function (offeringReservation) {
                return offeringReservation.course === currentHistory.course
                && (!offeringReservation.year || offeringReservation.year === currentHistory.year);
              });
              isReserved = requirement && (userSemester < requirement.suggestedSemester);
              next(true);
            }.bind(this));
          }
          else {
            next(false);
          }
        }.bind(this));
      }.bind(this), function(result) {
        next(blockType, isAhead, isReserved);
      });
    }.bind(this));
  }.bind(this));
}

/**
 * Verifica se uma solicitação de aumento de limite de créditos deve ser aberta
 */
schema.pre('save', function openCreditRaiseRequestIfNecessary(next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'requirements': function (next) {
        var query;
        query = this.model('Requirement').find();
        query.where('enrollment').equals(this.enrollment._id);
        query.where('_id').ne(this._id);
        query.exec(next);
      }.bind(this),
      'modality'   : function (next) {
        async.waterfall([function (next) {
          history.currentHistory(this.enrollment.user, next);
        }.bind(this), function (currentHistory, next) {
          courses.modality(currentHistory.year, currentHistory.course + '-' + currentHistory.modality, next);
        }.bind(this)], next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    // sum the actual requirement together with all other requirements
    data.requirements.push(this);

    async.reduce(data.requirements, 0, function (sum, disciplineRequirement, next) {
      courses.discipline(disciplineRequirement.discipline, function (error, discipline) {
        next(error, discipline ? discipline.credits + sum : 0);
      }.bind(this));
    }.bind(this), function (error, credits) {
      if (error) {
        error = new VError(error, 'Error when trying to sum the credits');
        return next(error);
      }

      if (credits <= data.modality.creditLimit) {
        return next();
      }

      this.enrollment.creditRaiseRequest.credits = credits;
      this.enrollment.creditRaiseRequest.date = new Date();
      this.enrollment.creditRaiseRequest.status = 'pending';
      this.enrollment.save(next);
    }.bind(this));
  }.bind(this)], next);
});

schema.path('offering').validate(function validateIfDisciplineOfferingExists(value, next) {
  'use strict';

  courses.offering(this.discipline, this.offering, function foundDisciplineOffering(error, offering) {
    next(!error && !!offering);
  });
}, 'discipline offering not found');

schema.path('discipline').validate(function validateDisciplineRequirement(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'discipline': function (next) {
        courses.discipline(this.discipline, next);
      }.bind(this),
      'histories' : function (next) {
        history.histories(this.enrollment.user, next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.histories, function (userHistory) {
      if (data.discipline.requirements.length > 0) {
        data.discipline.requirements.forEach(function (disciplineRequirement) {
          history.discipline(this.enrollment.user, userHistory.year, disciplineRequirement.code, function (error, disciplineHistory) {
            next(!!error || (disciplineHistory && [1, 2, 3, 4, 7, 10, 11, 12, 13, 14, 15, 16, 20].lastIndexOf(disciplineHistory.status) > -1));
          }.bind(this));
        }.bind(this));
      }
      else {
        next();
      }
    }.bind(this), next);
  }.bind(this)], next);
}, 'discipline requirement not fulfilled');

schema.path('status').validate(function validateIfRequirementCanBeQuit(value, next) {
  'use strict';
  var todayDate, year;
  todayDate = new Date();
  year = todayDate.getFullYear();

  if (this.status === 'quit') {
    calendar.betweenEvents(todayDate, year, 'discipline-quit-starts', year, 'discipline-quit-ends', next);
  }
  else {
    next();
  }
}, 'outside of discipline quit period');

schema.path('discipline').validate(function validateDisciplineApproval(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'histories'  : function (next) {
        history.histories(this.enrollment.user, next);
      }.bind(this),
      'discipline' : function (next) {
        courses.discipline(this.discipline, next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.histories, function (userHistory, next) {
      history.discipline(this.enrollment.user, userHistory.year, data.discipline.code, function (error, disciplineHistory) {
        next(!!error || !(disciplineHistory && [1, 2, 3, 4, 7, 10, 11, 12, 13, 14, 15, 16, 20].lastIndexOf(disciplineHistory.status) > -1));
      }.bind(this));
    }.bind(this), next);
  }.bind(this)], next);
}, 'user was already approved on discipline');

schema.path('offering').validate(function validateIfRequirementHasTimeConflict(value, next) {
  'use strict';

  async.waterfall([function (next) {
    this.populate('enrollment');
    this.populate(next);
  }.bind(this), function (_, next) {
    async.parallel({
      'offering'    : function (next) {
        courses.offering(this.discipline, this.offering, next);
      }.bind(this),
      'requirements': function (next) {
        var query;

        query = this.model('Requirement').find();
        query.where('enrollment').equals(this.enrollment._id);
        query.where('_id').ne(this._id);
        query.where('discipline').ne(this.discipline);
        query.exec(next);
      }.bind(this)
    }, next);
  }.bind(this), function (data, next) {
    async.every(data.requirements, function (requirement, next) {
      courses.offering(requirement.discipline, requirement.offering, function foundDisciplineOffering(error, offeringConflict) {
        var conflict = data.offering.schedules.some(function (schedule) {
          return offeringConflict.schedules.some(function (otherSchedule) {
            return (schedule.weekday === otherSchedule.weekday && schedule.hour === otherSchedule.hour);
          });
        });

        next(!!error || !conflict);
      });
    }.bind(this), next);
  }.bind(this)], next);
}, 'discipline with time conflict');

module.exports = mongoose.model('Requirement', schema);
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var firebaseinit;

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {

        alert('Received Event: ' + id);

        //firebaseauthchange

        firebase.auth().onAuthStateChanged(function(user) {

  if (user) {

      alert('user yes');

      alert(user.providerData[0].displayName);

  } else {

      alert('no user');

startApp();

    // No user is signed in.
  }

     });

    }
};

function startApp(){

    alert('starting');

    firebaseinit = localStorage.getItem('tokenStore');

    if (firebaseinit){
    alert(firebaseinit);

      var credential = firebase.auth.FacebookAuthProvider.credential(firebaseinit);
        alert('about to log ' + credential);

            firebase.auth().signInWithCredential(credential).catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;

        });

    }
    else {
     $( ".ploader" ).show();
      $( ".loginbutton" ).show();
      $( ".login-loader" ).hide();

    alert('no tokenStore');
    }

}

    function logout(){

firebase.auth().signOut().then(function() {
alert('Sign-out successful');
}, function(error) {
  // An error happened.
});

}

<commit_msg>Update index.js<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

var firebaseinit;

var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {

        alert('Received Event: ' + id);

        //firebaseauthchange

        firebase.auth().onAuthStateChanged(function(user) {

  if (user) {

      alert('user yes');

      alert(user.providerData[0].displayName);

  } else {

      alert('no user');

//startApp();

    // No user is signed in.
  }

     });

    }
};

function startApp(){

    alert('starting');

    firebaseinit = localStorage.getItem('tokenStore');

    if (firebaseinit){
    alert(firebaseinit);

      var credential = firebase.auth.FacebookAuthProvider.credential(firebaseinit);
        alert('about to log ' + credential);

            firebase.auth().signInWithCredential(credential).catch(function(error) {
          // Handle Errors here.
          var errorCode = error.code;
          var errorMessage = error.message;
          // The email of the user's account used.
          var email = error.email;
          // The firebase.auth.AuthCredential type that was used.
          var credential = error.credential;

        });

    }
    else {
     $( ".ploader" ).show();
      $( ".loginbutton" ).show();
      $( ".login-loader" ).hide();

    alert('no tokenStore');
    }

}

    function logout(){

firebase.auth().signOut().then(function() {
alert('Sign-out successful');
}, function(error) {
  // An error happened.
});

}

<|endoftext|>


<commit_before>var LevelBase = {
    tilemap : {
        path : 'assets/maps/',
        layer:'layer',
        objects : 'objects',
        collisionStart:0,
        collisionEnd:2,
        weapon1:4,
        weapon2:5,
        weapon3:6,
        stair : 'assets/images/escada.png'
    },
    bg : {
        path : 'assets/images/level/',
        x:0,
        y:0
    }
}

var Level1 = {
    tilemap:{
        jsonPath : LevelBase.tilemap.path + 'level1.json',
        tilePath : LevelBase.tilemap.path + 'tile_base.png'
    },
    bg:{
        path : LevelBase.bg.path + 'bg1.jpg'
    }
};

var Level2 = {
    tilemap:{
        jsonPath : LevelBase.tilemap.path + 'level2.json',
        tilePath : LevelBase.tilemap.path + 'tile_base.png'
    },
    bg:{
        path : LevelBase.bg.path + 'bg2.jpg'
    }
};

function Level(game, level) {
    this.game = game,
    this.level = level,
    this.layer,
    this.weapons,
    this.map,
    this.escadas;
}

Level.prototype = {
    preload : function() {
        this.game.load.tilemap('map', this.level.tilemap.jsonPath, null, Phaser.Tilemap.TILED_JSON);
        this.game.load.image('tileset', this.level.tilemap.tilePath);
        this.game.load.image('bg', this.level.bg.path);
        this.game.load.image('escada', LevelBase.tilemap.stair);
        this.game.load.image('weapon1', Weapon1.weaponImg);
        this.game.load.image('weapon2', Weapon2.weaponImg);
        this.game.load.image('weapon3', Weapon3.weaponImg);
    },

    create : function() {
        // background
        bg = this.game.add.sprite(LevelBase.bg.x, LevelBase.bg.y, 'bg');
        bg.fixedToCamera = true;

        // mapa
        this.map = this.game.add.tilemap('map');
        this.map.addTilesetImage('tileset','tileset');

        this.layer = this.map.createLayer(LevelBase.tilemap.layer);
        this.layer.resizeWorld();
        this.map.setCollisionBetween(LevelBase.tilemap.collisionStart, LevelBase.tilemap.collisionEnd, true, LevelBase.tilemap.layer);

        // criar armas
        this.weapons = this.game.add.group();
        this.weapons.enableBody = true;
        this.map.createFromObjects('objects', 5, 'weapon1', 0, true, false, this.weapons);
        this.map.createFromObjects('objects', 6, 'weapon2', 0, true, false, this.weapons);
        this.map.createFromObjects('objects', 7, 'weapon3', 0, true, false, this.weapons);
        this.weapons.forEach(function(weapon) {weapon.body.allowGravity = false}, this);

        //cria escadas
        this.escadas = game.add.group();
        this.escadas.enableBody = true;
        this.map.createFromObjects(LevelBase.tilemap.objects, 4, 'escada', 0, true, false, this.escadas);

        this.escadas.forEach(function(escada) {
                escada.body.allowGravity = false
        }, this);
    },

    update : function(hero) {
        this.upStair(hero, this.checkOverlap(this.escadas, hero.hero));
    },

    checkOverlap : function(group, hero) {
        return Phaser.Rectangle.intersects(group.getBounds(), hero.getBounds());
    },

    upStair : function(hero, bool){
        hero.climb(bool);
    },

	updateEnemyAttack : function(myEnemy,hero){
        //Verifica de a bola cuspida ainda está em jogo
        myEnemy.projectiles.forEachExists(function(projectile) {
            this.game.physics.arcade.accelerateToObject(projectile, hero.hero, Math.random() * 300);
            var moduloPosition = Math.abs(this.game.world.position.x);
			if (projectile.body.x  < moduloPosition - 50 || projectile.body.x >  moduloPosition + this.game.width
			|| projectile.body.y > this.game.height + 50|| projectile.body.y < 0 ||  this.game.time.time > projectile.timeLife){
			  projectile.kill();
            }
        }, this);

		var muduloHero = Math.round(Math.abs(hero.hero.body.x));
		myEnemy.enemies.forEachExists(function(enemy){
			var moduloEnemy =  Math.round(Math.abs(enemy.body.x));

			if(Math.abs(moduloEnemy - muduloHero) < 400){
                var sentido = hero.hero.body.x > enemy.body.x;
                var time = this.game.time.time;

                if(!enemy.isAttack && enemy.TYPE == myEnemy.BIG_TYPE && enemy.ultimoAtaque < time){
                    enemy.play('attack');
					enemy.ultimoAtaque = time + 3000;
					enemy.isAttack = true;
					this.game.physics.arcade.accelerateToXY(enemy,hero.hero.x,hero.hero.y);
                }else if(!enemy.isAttack && enemy.TYPE == myEnemy.MIDLE_TYPE && enemy.ultimoAtaque < time){
                    var proj = myEnemy.projectiles.getFirstDead();
                    if (proj == null) {
                      proj = myEnemy.projectiles.create(enemy.body.x + enemy.body.width / 2, enemy.body.y + enemy.body.height / 2, 'projectile');
                      this.game.physics.arcade.enable(proj, Phaser.Physics.ARCADE);
                      proj.body.allowGravity = false;
                      proj.anchor.setTo(0.5, 0.5);
                    } else {
                      proj.reset(enemy.body.x + enemy.body.width / 2, enemy.body.y + enemy.body.height / 2);
                    }
					proj.timeLife = time + 5000;
                    enemy.ultimoAtaque = time + 5000;
                }else if(!enemy.isAttack && enemy.TYPE == myEnemy.LITTLE_TYPE){
					enemy.play('rollAtaack');
					enemy.ultimoAtaque = time + 3000;
					enemy.isAttack = true;
					this.game.physics.arcade.accelerateToXY(enemy,hero.hero.x,hero.hero.y);

				}

			}
		},this);

		myEnemy.enemies.forEachExists(function(enemy){
			var time = this.game.time.time;
			if(enemy.isAttack && enemy.TYPE == myEnemy.BIG_TYPE && time > enemy.ultimoAtaque){
				console.log("fui resetado");
				enemy.reset(enemy.body.x,enemy.body.y);
				enemy.isAttack = false;
				enemy.play('walk')
			}else if(enemy.isAttack && enemy.TYPE == myEnemy.LITTLE_TYPE && time > enemy.ultimoAtaque){
				console.log("fui resetado");
				enemy.reset(enemy.body.x,enemy.body.y);
				enemy.isAttack = false;
				enemy.play('walk')
			}
		},this);
	}
}
<commit_msg>ajuste no tempo de ataque<commit_after>var LevelBase = {
    tilemap : {
        path : 'assets/maps/',
        layer:'layer',
        objects : 'objects',
        collisionStart:0,
        collisionEnd:2,
        weapon1:4,
        weapon2:5,
        weapon3:6,
        stair : 'assets/images/escada.png'
    },
    bg : {
        path : 'assets/images/level/',
        x:0,
        y:0
    }
}

var Level1 = {
    tilemap:{
        jsonPath : LevelBase.tilemap.path + 'level1.json',
        tilePath : LevelBase.tilemap.path + 'tile_base.png'
    },
    bg:{
        path : LevelBase.bg.path + 'bg1.jpg'
    }
};

var Level2 = {
    tilemap:{
        jsonPath : LevelBase.tilemap.path + 'level2.json',
        tilePath : LevelBase.tilemap.path + 'tile_base.png'
    },
    bg:{
        path : LevelBase.bg.path + 'bg2.jpg'
    }
};

function Level(game, level) {
    this.game = game,
    this.level = level,
    this.layer,
    this.weapons,
    this.map,
    this.escadas;
}

Level.prototype = {
    preload : function() {
        this.game.load.tilemap('map', this.level.tilemap.jsonPath, null, Phaser.Tilemap.TILED_JSON);
        this.game.load.image('tileset', this.level.tilemap.tilePath);
        this.game.load.image('bg', this.level.bg.path);
        this.game.load.image('escada', LevelBase.tilemap.stair);
        this.game.load.image('weapon1', Weapon1.weaponImg);
        this.game.load.image('weapon2', Weapon2.weaponImg);
        this.game.load.image('weapon3', Weapon3.weaponImg);
    },

    create : function() {
        // background
        bg = this.game.add.sprite(LevelBase.bg.x, LevelBase.bg.y, 'bg');
        bg.fixedToCamera = true;

        // mapa
        this.map = this.game.add.tilemap('map');
        this.map.addTilesetImage('tileset','tileset');

        this.layer = this.map.createLayer(LevelBase.tilemap.layer);
        this.layer.resizeWorld();
        this.map.setCollisionBetween(LevelBase.tilemap.collisionStart, LevelBase.tilemap.collisionEnd, true, LevelBase.tilemap.layer);

        // criar armas
        this.weapons = this.game.add.group();
        this.weapons.enableBody = true;
        this.map.createFromObjects('objects', 5, 'weapon1', 0, true, false, this.weapons);
        this.map.createFromObjects('objects', 6, 'weapon2', 0, true, false, this.weapons);
        this.map.createFromObjects('objects', 7, 'weapon3', 0, true, false, this.weapons);
        this.weapons.forEach(function(weapon) {weapon.body.allowGravity = false}, this);

        //cria escadas
        this.escadas = game.add.group();
        this.escadas.enableBody = true;
        this.map.createFromObjects(LevelBase.tilemap.objects, 4, 'escada', 0, true, false, this.escadas);

        this.escadas.forEach(function(escada) {
                escada.body.allowGravity = false
        }, this);
    },

    update : function(hero) {
        this.upStair(hero, this.checkOverlap(this.escadas, hero.hero));
    },

    checkOverlap : function(group, hero) {
        return Phaser.Rectangle.intersects(group.getBounds(), hero.getBounds());
    },

    upStair : function(hero, bool){
        hero.climb(bool);
    },

	updateEnemyAttack : function(myEnemy,hero){
        //Verifica de a bola cuspida ainda está em jogo
        myEnemy.projectiles.forEachExists(function(projectile) {
            this.game.physics.arcade.accelerateToObject(projectile, hero.hero, Math.random() * 300);
            var moduloPosition = Math.abs(this.game.world.position.x);
			if (projectile.body.x  < moduloPosition - 50 || projectile.body.x >  moduloPosition + this.game.width
			|| projectile.body.y > this.game.height + 50|| projectile.body.y < 0 ||  this.game.time.time > projectile.timeLife){
			  projectile.kill();
            }
        }, this);

		var muduloHero = Math.round(Math.abs(hero.hero.body.x));
		myEnemy.enemies.forEachExists(function(enemy){
			var moduloEnemy =  Math.round(Math.abs(enemy.body.x));

			if(Math.abs(moduloEnemy - muduloHero) < 400){
                var sentido = hero.hero.body.x > enemy.body.x;
                var time = this.game.time.time;

                if(!enemy.isAttack && enemy.TYPE == myEnemy.BIG_TYPE && enemy.ultimoAtaque < time){
                    enemy.play('attack');
					enemy.ultimoAtaque = time + 3000;
					enemy.isAttack = true;
					this.game.physics.arcade.accelerateToXY(enemy,hero.hero.x,hero.hero.y,100);
                }else if(!enemy.isAttack && enemy.TYPE == myEnemy.MIDLE_TYPE && enemy.ultimoAtaque < time){
                    var proj = myEnemy.projectiles.getFirstDead();
                    if (proj == null) {
                      proj = myEnemy.projectiles.create(enemy.body.x + enemy.body.width / 2, enemy.body.y + enemy.body.height / 2, 'projectile');
                      this.game.physics.arcade.enable(proj, Phaser.Physics.ARCADE);
                      proj.body.allowGravity = false;
                      proj.anchor.setTo(0.5, 0.5);
                    } else {
                      proj.reset(enemy.body.x + enemy.body.width / 2, enemy.body.y + enemy.body.height / 2);
                    }
					proj.timeLife = time + 5000;
                    enemy.ultimoAtaque = time + 5000;
                }else if(!enemy.isAttack && enemy.TYPE == myEnemy.LITTLE_TYPE){
					enemy.play('rollAtaack');
					enemy.ultimoAtaque = time + 3000;
					enemy.isAttack = true;
					this.game.physics.arcade.accelerateToXY(enemy,hero.hero.x,hero.hero.y,100);

				}

			}
		},this);

		myEnemy.enemies.forEachExists(function(enemy){
			var time = this.game.time.time;
			if(enemy.isAttack && enemy.TYPE == myEnemy.BIG_TYPE && time > enemy.ultimoAtaque){
				enemy.reset(enemy.body.x,enemy.body.y);
				enemy.isAttack = false;
				enemy.play('walk')
			}else if(enemy.isAttack && enemy.TYPE == myEnemy.LITTLE_TYPE && time > enemy.ultimoAtaque){
				enemy.reset(enemy.body.x,enemy.body.y);
				enemy.isAttack = false;
				enemy.play('walk')
			}
		},this);
	}
}
<|endoftext|>


<commit_before>
define([
  'backbone',
  'static-pages/views/SliderView'
], function(Backbone, SliderView) {

  'use strict';

  var SmallGrantsFundView = Backbone.View.extend({

    el: '#small-grunts-fund',

    initialize: function() {

      if(! !!this.el) {
        return;
      }

      this._setSlides();
    },

    _setSlides: function() {

      var sliders = [{
        slideOptions: {
          el: '#SFGSliderView',
          options: {
            defaultSlider: {
              autoplay: true,
              navigation: false
            }
          }
        }
      },{
        slideOptions: {
          el: '#GrantesForestSliderView',
          options: {
            defaultSlider: {
              infinite: false,
              navigation: false
            }
          }
        }
      }]

      sliders.forEach(function(slider) {
        new SliderView(slider.slideOptions);
      });
    }

  });

  return SmallGrantsFundView;

});
<commit_msg>Fix: Small Grants - Disable slider<commit_after>
define([
  'backbone',
  'static-pages/views/SliderView'
], function(Backbone, SliderView) {

  'use strict';

  var SmallGrantsFundView = Backbone.View.extend({

    el: '#small-grunts-fund',

    initialize: function() {

      if(! !!this.el) {
        return;
      }

      this._setSlides();
    },

    _setSlides: function() {

      var sliders = [{
        slideOptions: {
          el: '#SFGSliderView',
          options: {
            defaultSlider: {
              autoplay: false,
              navigation: false
            }
          }
        }
      },{
        slideOptions: {
          el: '#GrantesForestSliderView',
          options: {
            defaultSlider: {
              infinite: false,
              navigation: false
            }
          }
        }
      }]

      sliders.forEach(function(slider) {
        new SliderView(slider.slideOptions);
      });
    }

  });

  return SmallGrantsFundView;

});
<|endoftext|>


<commit_before><commit_msg>support re-typing in the searchbar<commit_after><|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        navigator.notification.alert("测试跳转", function(){}, "Title", "Button Text");
        navigator.notification.alert("http://1.weishequserver.duapp.com/", function(){}, "Title", "Button Text");
        window.open("http://1.weishequserver.duapp.com/");
        return;

        location.href="http://1.weishequserver.duapp.com/";

        console.log('Received Event: ' + id);
    }
};
<commit_msg>sfsfsdfsdfsdfsdfsd<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
    		window.alert = navigator.notification.alert
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
        alert(11);
				navigator.notification.alert("aaaaa", null, "Title", "Button Text");
        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
        navigator.notification.alert("测试跳转", function(){}, "Title", "Button Text");
        navigator.notification.alert("http://1.weishequserver.duapp.com/", function(){}, "Title", "Button Text");
        window.open("http://1.weishequserver.duapp.com/");
        return;

        location.href="http://1.weishequserver.duapp.com/";

        console.log('Received Event: ' + id);
    }
};
<|endoftext|>


<commit_before>import React from 'react';
import Column from 'flavours/glitch/features/ui/components/column';
import ColumnLink from 'flavours/glitch/features/ui/components/column_link';
import ColumnSubheading from 'flavours/glitch/features/ui/components/column_subheading';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import { openModal } from 'flavours/glitch/actions/modal';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me, invitesEnabled, version } from 'flavours/glitch/util/initial_state';
import { fetchFollowRequests } from 'flavours/glitch/actions/accounts';
import { List as ImmutableList } from 'immutable';
import { createSelector } from 'reselect';
import { fetchLists } from 'flavours/glitch/actions/lists';
import { preferencesLink, profileLink, signOutLink } from 'flavours/glitch/util/backend_links';

const messages = defineMessages({
  heading: { id: 'getting_started.heading', defaultMessage: 'Getting started' },
  home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' },
  notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' },
  public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' },
  navigation_subheading: { id: 'column_subheading.navigation', defaultMessage: 'Navigation' },
  settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' },
  community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' },
  direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' },
  bookmarks: { id: 'navigation_bar.bookmarks', defaultMessage: 'Bookmarks' },
  preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
  settings: { id: 'navigation_bar.app_settings', defaultMessage: 'App settings' },
  follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
  sign_out: { id: 'navigation_bar.logout', defaultMessage: 'Logout' },
  lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
  keyboard_shortcuts: { id: 'navigation_bar.keyboard_shortcuts', defaultMessage: 'Keyboard shortcuts' },
  lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
  lists_subheading: { id: 'column_subheading.lists', defaultMessage: 'Lists' },
  misc: { id: 'navigation_bar.misc', defaultMessage: 'Misc' },
  menu: { id: 'getting_started.heading', defaultMessage: 'Getting started' },
});

const makeMapStateToProps = () => {
  const getOrderedLists = createSelector([state => state.get('lists')], lists => {
    if (!lists) {
      return lists;
    }

    return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title')));
  });

  const mapStateToProps = state => ({
    lists: getOrderedLists(state),
    myAccount: state.getIn(['accounts', me]),
    columns: state.getIn(['settings', 'columns']),
    unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size,
    unreadNotifications: state.getIn(['notifications', 'unread']),
  });

  return mapStateToProps;
};

const mapDispatchToProps = dispatch => ({
  fetchFollowRequests: () => dispatch(fetchFollowRequests()),
  fetchLists: () => dispatch(fetchLists()),
  openSettings: () => dispatch(openModal('SETTINGS', {})),
});

const badgeDisplay = (number, limit) => {
  if (number === 0) {
    return undefined;
  } else if (limit && number >= limit) {
    return `${limit}+`;
  } else {
    return number;
  }
};

const NAVIGATION_PANEL_BREAKPOINT = 600 + (285 * 2) + (10 * 2);

 export default @connect(makeMapStateToProps, mapDispatchToProps)
 @injectIntl
 class GettingStarted extends ImmutablePureComponent {

  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  static propTypes = {
    intl: PropTypes.object.isRequired,
    myAccount: ImmutablePropTypes.map.isRequired,
    columns: ImmutablePropTypes.list,
    multiColumn: PropTypes.bool,
    fetchFollowRequests: PropTypes.func.isRequired,
    unreadFollowRequests: PropTypes.number,
    unreadNotifications: PropTypes.number,
    lists: ImmutablePropTypes.list,
    fetchLists: PropTypes.func.isRequired,
    openSettings: PropTypes.func.isRequired,
  };

  componentWillMount () {
    this.props.fetchLists();
  }

  componentDidMount () {
    const { myAccount, fetchFollowRequests } = this.props;

    if (window.innerWidth >= NAVIGATION_PANEL_BREAKPOINT) {
      this.context.router.history.replace('/timelines/home');
      return;
    }

    if (myAccount.get('locked')) {
      fetchFollowRequests();
    }
  }

  render () {
    const { intl, myAccount, columns, multiColumn, unreadFollowRequests, unreadNotifications, lists, openSettings } = this.props;

    const navItems = [];
    let listItems = [];

    if (multiColumn) {
      if (!columns.find(item => item.get('id') === 'HOME')) {
        navItems.push(<ColumnLink key='0' icon='home' text={intl.formatMessage(messages.home_timeline)} to='/timelines/home' />);
      }

      if (!columns.find(item => item.get('id') === 'NOTIFICATIONS')) {
        navItems.push(<ColumnLink key='1' icon='bell' text={intl.formatMessage(messages.notifications)} badge={badgeDisplay(unreadNotifications)} to='/notifications' />);
      }

      if (!columns.find(item => item.get('id') === 'COMMUNITY')) {
        navItems.push(<ColumnLink key='2' icon='users' text={intl.formatMessage(messages.community_timeline)} to='/timelines/public/local' />);
      }

      if (!columns.find(item => item.get('id') === 'PUBLIC')) {
        navItems.push(<ColumnLink key='3' icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/timelines/public' />);
      }
    }

    if (!multiColumn || !columns.find(item => item.get('id') === 'DIRECT')) {
      navItems.push(<ColumnLink key='4' icon='envelope' text={intl.formatMessage(messages.direct)} to='/timelines/direct' />);
    }

    if (!multiColumn || !columns.find(item => item.get('id') === 'BOOKMARKS')) {
      navItems.push(<ColumnLink key='5' icon='bookmark' text={intl.formatMessage(messages.bookmarks)} to='/bookmarks' />);
    }

    if (myAccount.get('locked')) {
      navItems.push(<ColumnLink key='6' icon='user-plus' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />);
    }

    navItems.push(<ColumnLink key='7' icon='ellipsis-h' text={intl.formatMessage(messages.misc)} to='/getting-started-misc' />);

    listItems = listItems.concat([

        <ColumnLink key='9' icon='bars' text={intl.formatMessage(messages.lists)} to='/lists' />
        {lists.map(list =>
          <ColumnLink key={(9 + Number(list.get('id'))).toString()} to={`/timelines/list/${list.get('id')}`} icon='list-ul' text={list.get('title')} />
        )}

,
    ]);

    return (
      <Column name='getting-started' icon='asterisk' heading={intl.formatMessage(messages.heading)} label={intl.formatMessage(messages.menu)} hideHeadingOnMobile>

            <ColumnSubheading text={intl.formatMessage(messages.navigation_subheading)} />
            {navItems}
            <ColumnSubheading text={intl.formatMessage(messages.lists_subheading)} />
            {listItems}
            <ColumnSubheading text={intl.formatMessage(messages.settings_subheading)} />
            { preferencesLink !== undefined && <ColumnLink icon='cog' text={intl.formatMessage(messages.preferences)} href={preferencesLink} /> }
            <ColumnLink icon='cogs' text={intl.formatMessage(messages.settings)} onClick={openSettings} />
            <ColumnLink icon='sign-out' text={intl.formatMessage(messages.sign_out)} href={signOutLink} method='delete' />

              {invitesEnabled &&
<FormattedMessage id='getting_started.invite' defaultMessage='Invite people' /> ·
}

<FormattedMessage id='navigation_bar.info' defaultMessage='About this server' /> ·

<FormattedMessage id='navigation_bar.apps' defaultMessage='Mobile apps' /> ·

<FormattedMessage id='getting_started.terms' defaultMessage='Terms of service' /> ·

<FormattedMessage id='getting_started.documentation' defaultMessage='Documentation' />

              <FormattedMessage
                id='getting_started.open_source_notice'
                defaultMessage='Glitchsoc is open source software, a friendly fork of {Mastodon}. You can contribute or report issues on GitHub at {github}.'
                values={{
                  github: glitch-soc/mastodon (v{version}),
                  Mastodon: Mastodon }}
              />

      </Column>
    );
  }

}
<commit_msg>[Glitch] Fix wrong redirect from getting started to home in advanced Web UI<commit_after>import React from 'react';
import Column from 'flavours/glitch/features/ui/components/column';
import ColumnLink from 'flavours/glitch/features/ui/components/column_link';
import ColumnSubheading from 'flavours/glitch/features/ui/components/column_subheading';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import { openModal } from 'flavours/glitch/actions/modal';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me, invitesEnabled, version } from 'flavours/glitch/util/initial_state';
import { fetchFollowRequests } from 'flavours/glitch/actions/accounts';
import { List as ImmutableList } from 'immutable';
import { createSelector } from 'reselect';
import { fetchLists } from 'flavours/glitch/actions/lists';
import { preferencesLink, profileLink, signOutLink } from 'flavours/glitch/util/backend_links';

const messages = defineMessages({
  heading: { id: 'getting_started.heading', defaultMessage: 'Getting started' },
  home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' },
  notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' },
  public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' },
  navigation_subheading: { id: 'column_subheading.navigation', defaultMessage: 'Navigation' },
  settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' },
  community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' },
  direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' },
  bookmarks: { id: 'navigation_bar.bookmarks', defaultMessage: 'Bookmarks' },
  preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
  settings: { id: 'navigation_bar.app_settings', defaultMessage: 'App settings' },
  follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
  sign_out: { id: 'navigation_bar.logout', defaultMessage: 'Logout' },
  lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
  keyboard_shortcuts: { id: 'navigation_bar.keyboard_shortcuts', defaultMessage: 'Keyboard shortcuts' },
  lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
  lists_subheading: { id: 'column_subheading.lists', defaultMessage: 'Lists' },
  misc: { id: 'navigation_bar.misc', defaultMessage: 'Misc' },
  menu: { id: 'getting_started.heading', defaultMessage: 'Getting started' },
});

const makeMapStateToProps = () => {
  const getOrderedLists = createSelector([state => state.get('lists')], lists => {
    if (!lists) {
      return lists;
    }

    return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title')));
  });

  const mapStateToProps = state => ({
    lists: getOrderedLists(state),
    myAccount: state.getIn(['accounts', me]),
    columns: state.getIn(['settings', 'columns']),
    unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size,
    unreadNotifications: state.getIn(['notifications', 'unread']),
  });

  return mapStateToProps;
};

const mapDispatchToProps = dispatch => ({
  fetchFollowRequests: () => dispatch(fetchFollowRequests()),
  fetchLists: () => dispatch(fetchLists()),
  openSettings: () => dispatch(openModal('SETTINGS', {})),
});

const badgeDisplay = (number, limit) => {
  if (number === 0) {
    return undefined;
  } else if (limit && number >= limit) {
    return `${limit}+`;
  } else {
    return number;
  }
};

const NAVIGATION_PANEL_BREAKPOINT = 600 + (285 * 2) + (10 * 2);

 export default @connect(makeMapStateToProps, mapDispatchToProps)
 @injectIntl
 class GettingStarted extends ImmutablePureComponent {

  static contextTypes = {
    router: PropTypes.object.isRequired,
  };

  static propTypes = {
    intl: PropTypes.object.isRequired,
    myAccount: ImmutablePropTypes.map.isRequired,
    columns: ImmutablePropTypes.list,
    multiColumn: PropTypes.bool,
    fetchFollowRequests: PropTypes.func.isRequired,
    unreadFollowRequests: PropTypes.number,
    unreadNotifications: PropTypes.number,
    lists: ImmutablePropTypes.list,
    fetchLists: PropTypes.func.isRequired,
    openSettings: PropTypes.func.isRequired,
  };

  componentWillMount () {
    this.props.fetchLists();
  }

  componentDidMount () {
    const { myAccount, fetchFollowRequests, multiColumn } = this.props;

    if (!multiColumn && window.innerWidth >= NAVIGATION_PANEL_BREAKPOINT) {
      this.context.router.history.replace('/timelines/home');
      return;
    }

    if (myAccount.get('locked')) {
      fetchFollowRequests();
    }
  }

  render () {
    const { intl, myAccount, columns, multiColumn, unreadFollowRequests, unreadNotifications, lists, openSettings } = this.props;

    const navItems = [];
    let listItems = [];

    if (multiColumn) {
      if (!columns.find(item => item.get('id') === 'HOME')) {
        navItems.push(<ColumnLink key='0' icon='home' text={intl.formatMessage(messages.home_timeline)} to='/timelines/home' />);
      }

      if (!columns.find(item => item.get('id') === 'NOTIFICATIONS')) {
        navItems.push(<ColumnLink key='1' icon='bell' text={intl.formatMessage(messages.notifications)} badge={badgeDisplay(unreadNotifications)} to='/notifications' />);
      }

      if (!columns.find(item => item.get('id') === 'COMMUNITY')) {
        navItems.push(<ColumnLink key='2' icon='users' text={intl.formatMessage(messages.community_timeline)} to='/timelines/public/local' />);
      }

      if (!columns.find(item => item.get('id') === 'PUBLIC')) {
        navItems.push(<ColumnLink key='3' icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/timelines/public' />);
      }
    }

    if (!multiColumn || !columns.find(item => item.get('id') === 'DIRECT')) {
      navItems.push(<ColumnLink key='4' icon='envelope' text={intl.formatMessage(messages.direct)} to='/timelines/direct' />);
    }

    if (!multiColumn || !columns.find(item => item.get('id') === 'BOOKMARKS')) {
      navItems.push(<ColumnLink key='5' icon='bookmark' text={intl.formatMessage(messages.bookmarks)} to='/bookmarks' />);
    }

    if (myAccount.get('locked')) {
      navItems.push(<ColumnLink key='6' icon='user-plus' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />);
    }

    navItems.push(<ColumnLink key='7' icon='ellipsis-h' text={intl.formatMessage(messages.misc)} to='/getting-started-misc' />);

    listItems = listItems.concat([

        <ColumnLink key='9' icon='bars' text={intl.formatMessage(messages.lists)} to='/lists' />
        {lists.map(list =>
          <ColumnLink key={(9 + Number(list.get('id'))).toString()} to={`/timelines/list/${list.get('id')}`} icon='list-ul' text={list.get('title')} />
        )}

,
    ]);

    return (
      <Column name='getting-started' icon='asterisk' heading={intl.formatMessage(messages.heading)} label={intl.formatMessage(messages.menu)} hideHeadingOnMobile>

            <ColumnSubheading text={intl.formatMessage(messages.navigation_subheading)} />
            {navItems}
            <ColumnSubheading text={intl.formatMessage(messages.lists_subheading)} />
            {listItems}
            <ColumnSubheading text={intl.formatMessage(messages.settings_subheading)} />
            { preferencesLink !== undefined && <ColumnLink icon='cog' text={intl.formatMessage(messages.preferences)} href={preferencesLink} /> }
            <ColumnLink icon='cogs' text={intl.formatMessage(messages.settings)} onClick={openSettings} />
            <ColumnLink icon='sign-out' text={intl.formatMessage(messages.sign_out)} href={signOutLink} method='delete' />

              {invitesEnabled &&
<FormattedMessage id='getting_started.invite' defaultMessage='Invite people' /> ·
}

<FormattedMessage id='navigation_bar.info' defaultMessage='About this server' /> ·

<FormattedMessage id='navigation_bar.apps' defaultMessage='Mobile apps' /> ·

<FormattedMessage id='getting_started.terms' defaultMessage='Terms of service' /> ·

<FormattedMessage id='getting_started.documentation' defaultMessage='Documentation' />

              <FormattedMessage
                id='getting_started.open_source_notice'
                defaultMessage='Glitchsoc is open source software, a friendly fork of {Mastodon}. You can contribute or report issues on GitHub at {github}.'
                values={{
                  github: glitch-soc/mastodon (v{version}),
                  Mastodon: Mastodon }}
              />

      </Column>
    );
  }

}
<|endoftext|>


<commit_before>var LangUtils = require('./LangUtils');

class RulesProcessor {

    static getCostString(skill) {
        var options = {};
        const LN = {
            spend: function (options, cost, currency) {
                if(options.displayCost != undefined){
                    return options.displayCost;
                }
                return cost + currency;
            }
        }
        if (skill.cost == "") {
            return "free";
        }
        return eval(skill.cost);

    }

    // Returns:
    // {
    //  currencySpend:{"currency": spend_amount}
    //  errorMessages: ["its crap", "you are too poor"]
    // }
    // Order of operations:
    // Run all spend analysis
    // Evaluate all rules
    static evalRulesAndSpend(skills, evalOptions = {}) {

        // Build out placeholder for result
        result = {
            currencySpend: {},
            errorMessages: [],
            sideEffects: {
                traits: {},
                stats: {}
            }
        }

        var grantedTags = {}
        var grantedTraits = {}

        // fuck you scope, ill figure it out later
        skillRanks = Object.assign({}, evalOptions.skillRanks);

        if (evalOptions.skillToUpdate != undefined) {
            if(evalOptions.newRank == 0){
                delete skillRanks[evalOptions.skillToUpdate.id]
            }else{
                skillRanks[evalOptions.skillToUpdate.id] = evalOptions.newRank
            }
        }

        currencySpend = {};

        const LN = RulesHelpers.jsToolkit();

        // Loop thru each skill to apply it's granted tags, spend, and side effects to the current state copy
        for (skillId in skillRanks) {

            const skill = skills[skillId]
            const rank = skillRanks[skillId]

            if (rank > 0) {
                skill.skill_tags.filter((skill_tag) => {return skill_tag.gives}).forEach((skillTag)=>{grantedTags[skillTag.tag.id] = skillTag.tag})
                if (skill.cost.length > 0) {
                    var options = {
                        skillRank: rank
                    };
                    try {
                        eval(skill.cost);
                    } catch (e) {
                        result.errorMessages.push(`${skill.name} had an error in the cost, please screenshot this and send it to your GM:  ${e.message}`)
                    }
                }
                if (skill.side_effects != null && skill.side_effects.length > 0) {
                    var options = {
                        skillRank: rank
                    };
                    try {
                        eval(skill.side_effects);
                    } catch (e) {
                        result.errorMessages.push(`${skill.name} had an error in the side effects, please screenshot this and send it to your GM:  ${e.message}`)
                    }
                }
            }
        }

        if(evalOptions.currencyTotals != undefined){
            // make a copy of currencies so we dont fuck with other people's shit
            for(currency in result.currencySpend){
                if(evalOptions.currencyTotals[currency] == undefined || (evalOptions.currencyTotals[currency]-result.currencySpend[currency] < 0)){
                    result.errorMessages.push(`You don't have enough ${currency} to afford that.`)
                }
            }
        }

        // Loop thru each skill to evaluate it's rules
        for (skillId in skillRanks) {

            const skill = skills[skillId]
            const rank = skillRanks[skillId]

            if (rank > 0) {
                if (rank > skill.max_rank) {
                    result.errorMessages.push(`You do not meet the requirements for ${skill.name}`);
                } else if(skill.cost.length > 0) {
                    try {
                        const options = {
                            skillRank: rank
                        };
                        if (eval(skill.rule) == false) {
                            result.errorMessages.push(`You do not meet the requirements for ${skill.name}`);
                        }
                    } catch (e) {
                        result.errorMessages.push(`${skill.name} had an error in the rule, please screenshot this and send it to your GM:  ${e.message}`)
                    }

                }
            }
        }
        result.grantedTags = Object.values(grantedTags)
        result.grantedTraits = Object.values(grantedTraits)
        result.skillRanks = skillRanks;
        return result;

    }

}

module.exports = RulesProcessor;

class RulesHelpers {
    static jsToolkit() {
        return {
            spend: RulesHelpers._spend,
            skillRank: RulesHelpers._skillRank,
            sideEffects: {
                addStat: RulesHelpers._addStat,
                addTrait: RulesHelpers._addTrait
            }
        }
    }

    static _spend(options, cost, currency) {
        if (result.currencySpend[currency] === undefined) {
            result.currencySpend[currency] = 0;
        }
        result.currencySpend[currency] = result.currencySpend[currency] + (cost * options.skillRank);
    }

    static _skillRank = function (options, skill_id) {

        if (skillRanks[skill_id] === undefined) {
            return 0;
        }
        return skillRanks[skill_id];
    }

    static _addStat(options, attributeName, amount) {
        if (result.sideEffects.stats[attributeName] === undefined) {
            result.sideEffects.stats[attributeName] = 0;
        }
        result.sideEffects.stats[attributeName] = result.sideEffects.stats[attributeName] + amount;
    }
    static _addTrait(options, attributeName) {
        if (result.sideEffects.traits[attributeName] === undefined) {
            result.sideEffects.traits[attributeName] = 0;
        }
    }

}<commit_msg>don't multiply on our own, force skill to do it<commit_after>var LangUtils = require('./LangUtils');

class RulesProcessor {

    static getCostString(skill) {
        var options = {};
        const LN = {
            spend: function (options, cost, currency) {
                if(options.displayCost != undefined){
                    return options.displayCost;
                }
                return cost + currency;
            }
        }
        if (skill.cost == "") {
            return "free";
        }
        return eval(skill.cost);

    }

    // Returns:
    // {
    //  currencySpend:{"currency": spend_amount}
    //  errorMessages: ["its crap", "you are too poor"]
    // }
    // Order of operations:
    // Run all spend analysis
    // Evaluate all rules
    static evalRulesAndSpend(skills, evalOptions = {}) {

        // Build out placeholder for result
        result = {
            currencySpend: {},
            errorMessages: [],
            sideEffects: {
                traits: {},
                stats: {}
            }
        }

        var grantedTags = {}
        var grantedTraits = {}

        // fuck you scope, ill figure it out later
        skillRanks = Object.assign({}, evalOptions.skillRanks);

        if (evalOptions.skillToUpdate != undefined) {
            if(evalOptions.newRank == 0){
                delete skillRanks[evalOptions.skillToUpdate.id]
            }else{
                skillRanks[evalOptions.skillToUpdate.id] = evalOptions.newRank
            }
        }

        currencySpend = {};

        const LN = RulesHelpers.jsToolkit();

        // Loop thru each skill to apply it's granted tags, spend, and side effects to the current state copy
        for (skillId in skillRanks) {

            const skill = skills[skillId]
            const rank = skillRanks[skillId]

            if (rank > 0) {
                skill.skill_tags.filter((skill_tag) => {return skill_tag.gives}).forEach((skillTag)=>{grantedTags[skillTag.tag.id] = skillTag.tag})
                if (skill.cost.length > 0) {
                    var options = {
                        skillRank: rank
                    };
                    try {
                        eval(skill.cost);
                    } catch (e) {
                        result.errorMessages.push(`${skill.name} had an error in the cost, please screenshot this and send it to your GM:  ${e.message}`)
                    }
                }
                if (skill.side_effects != null && skill.side_effects.length > 0) {
                    var options = {
                        skillRank: rank
                    };
                    try {
                        eval(skill.side_effects);
                    } catch (e) {
                        result.errorMessages.push(`${skill.name} had an error in the side effects, please screenshot this and send it to your GM:  ${e.message}`)
                    }
                }
            }
        }

        if(evalOptions.currencyTotals != undefined){
            // make a copy of currencies so we dont fuck with other people's shit
            for(currency in result.currencySpend){
                if(evalOptions.currencyTotals[currency] == undefined || (evalOptions.currencyTotals[currency]-result.currencySpend[currency] < 0)){
                    result.errorMessages.push(`You don't have enough ${currency} to afford that.`)
                }
            }
        }

        // Loop thru each skill to evaluate it's rules
        for (skillId in skillRanks) {

            const skill = skills[skillId]
            const rank = skillRanks[skillId]

            if (rank > 0) {
                if (rank > skill.max_rank) {
                    result.errorMessages.push(`You do not meet the requirements for ${skill.name}`);
                } else if(skill.cost.length > 0) {
                    try {
                        const options = {
                            skillRank: rank
                        };
                        if (eval(skill.rule) == false) {
                            result.errorMessages.push(`You do not meet the requirements for ${skill.name}`);
                        }
                    } catch (e) {
                        result.errorMessages.push(`${skill.name} had an error in the rule, please screenshot this and send it to your GM:  ${e.message}`)
                    }

                }
            }
        }
        result.grantedTags = Object.values(grantedTags)
        result.grantedTraits = Object.values(grantedTraits)
        result.skillRanks = skillRanks;
        return result;

    }

}

module.exports = RulesProcessor;

class RulesHelpers {
    static jsToolkit() {
        return {
            spend: RulesHelpers._spend,
            skillRank: RulesHelpers._skillRank,
            sideEffects: {
                addStat: RulesHelpers._addStat,
                addTrait: RulesHelpers._addTrait
            }
        }
    }

    static _spend(options, cost, currency) {
        if (result.currencySpend[currency] === undefined) {
            result.currencySpend[currency] = 0;
        }
        result.currencySpend[currency] = result.currencySpend[currency] + cost;
    }

    static _skillRank = function (options, skill_id) {

        if (skillRanks[skill_id] === undefined) {
            return 0;
        }
        return skillRanks[skill_id];
    }

    static _addStat(options, attributeName, amount) {
        if (result.sideEffects.stats[attributeName] === undefined) {
            result.sideEffects.stats[attributeName] = 0;
        }
        result.sideEffects.stats[attributeName] = result.sideEffects.stats[attributeName] + amount;
    }
    static _addTrait(options, attributeName) {
        if (result.sideEffects.traits[attributeName] === undefined) {
            result.sideEffects.traits[attributeName] = 0;
        }
    }

}<|endoftext|>


<commit_before>var post = function(action, data){
  return new Promise(function(resolve, reject){

    console.log("About to make a post call - ");
    console.log(action);
    console.log(data);

    var request = $.post(action, data);

    request.done(function(serverData){
      resolve(serverData)
    });

    request.fail(function(serverData){
      reject(serverData)
    });
  });
}

var get = function(action, data){
  return new Promise(function(resolve, reject){

    console.log("About to make a get call - ");
    console.log(action);
    console.log(data);

    var request = $.get(action, data);

    request.done(function(serverData){
      resolve(serverData)
    });

    request.fail(function(serverData){
      reject(serverData)
    });
  });
}

var view = {
  goTo: function(contentId){
    $(":mobile-pagecontainer").pagecontainer("change", contentId);
  },
  errorMessage: function(errorTarget, message){
    $(errorTarget).text("There was an error signing in. " + message);
  },
  loginUser: function(){
    this.updatePersonalInfo();
    this.goTo('#cardsPage');
  },
  logoutUser: function(){
    this.goTo('#loginPage');
  },
  updatePersonalInfo: function(){
    var name = localStorage.getItem("u_first_name");
    name += " " + localStorage.getItem("u_last_name");
    $(".uName").text(name);
    $(".uSchoolName").text(localStorage.getItem('u_school_name'));
  },
  showObservation: function(observations){
    observation = observations[0];
    $('#emptyNotice').hide();
    this.updateNickname(observation);
    this.updateObservationForm(observation);
    $('.time').datebox({
        mode: "durationflipbox",
        overrideDurationOrder:["h","i","s"],
        overrideDurationFormat: "%DM:%DS"
    });
  },
  updateNickname: function(observation){
    var student = observation[2];
    var nickname = student['nickname'];
    $("#sAlias").text(nickname);
  },
  updateObservationForm: function(observation){
    var record_inputs = this.makeRecordInputs(observation[1]);
    $('#observationRecordsForm').prepend($(record_inputs));
    $('#observationRecordsForm').trigger('create');
  },
  makeRecordInputs: function(records){
    var inputs = '';
    $.each(records, function(index, record){
      console.log(record)
      input = '' + record["prompt"]  + ''
      if(record["meme"] == "Time"){
        input += '<input name="' + record["id"] + '" type="text" placeholder="10" class="time" />';
      } else if(record["meme"] == "Percentage"){
        input += '<input type="range" name="' + record["id"] + '" value="50" min="0" max="100" />';
      } else if(record["meme"] == "Qualitative"){
        input += '<input type="range" name="' + record["id"] + '" value="5" min="0" max="5" />';
      } else if(record["meme"] == "Incidence"){
        input += '<input type="text" name="' + record["id"] + '"/>';
      } else if(record["meme"] == "Boolean"){
        input += '<select name="' + record["id"] + '" data-role="slider"><option value="true">Yes</option><option value="false">No</option></select>';
      } else {
        input += '<input type="text" name="' + record["id"] + '" />';
      }
      inputs += input;
    });
    return inputs;
  }
}

var app = {
  initialize: function() {
    this.bindEvents();
  },
  bindEvents: function() {
    $("#loginForm").submit(this.submitLoginForm);
    $("#observationRecordsForm").submit(this.submitObservationForm);
    $("#logoutLink").click(this.handleLogOut);
  },
  handleLogOut: function(){
    localStorage.removeItem("uid");
    localStorage.removeItem("utoken");
    view.logoutUser();
  },
  getObservations: function(user_id, authenticity_token){
    var data = "user_id=" + user_id + "&authenticity_token=" + authenticity_token;

    get('http://localhost:3000/api/v1/observations?' + data)
      .then(function(serverData){
        localStorage.setItem("observations", serverData);
        view.showObservation(serverData);
      })
      .catch(function(serverData){
        console.log('error');
        console.log(serverData.responseText)
      });
  },
  submitLoginForm: function(){
    var data = $("#loginForm").serialize();
    post('http://localhost:3000/api/v1/login', data)
      .then(function(serverData){
        localStorage.setItem("uid", serverData.id);
        localStorage.setItem("utoken", serverData.token);
        localStorage.setItem("u_first_name", serverData.first_name);
        localStorage.setItem("u_last_name", serverData.last_name);
        localStorage.setItem("u_school_name", serverData.school_name);

        app.getObservations(serverData.id, serverData.token);
        view.loginUser();
      })
      .catch(function(serverData){
        view.errorMessage('#loginError', serverData.responseText);
      });

    return false;
  },
  submitObservationForm: function(){
    console.log('got to submitObservationForm');
    return false;
  }
};<commit_msg>Create current observation update path<commit_after>var post = function(action, data){
  return new Promise(function(resolve, reject){

    console.log("About to make a post call - ");
    console.log(action);
    console.log(data);

    var request = $.post(action, data);

    request.done(function(serverData){
      resolve(serverData)
    });

    request.fail(function(serverData){
      reject(serverData)
    });
  });
}

var get = function(action, data){
  return new Promise(function(resolve, reject){

    console.log("About to make a get call - ");
    console.log(action);
    console.log(data);

    var request = $.get(action, data);

    request.done(function(serverData){
      resolve(serverData)
    });

    request.fail(function(serverData){
      reject(serverData)
    });
  });
}

var view = {
  goTo: function(contentId){
    $(":mobile-pagecontainer").pagecontainer("change", contentId);
  },
  errorMessage: function(errorTarget, message){
    $(errorTarget).text("There was an error signing in. " + message);
  },
  loginUser: function(){
    this.updatePersonalInfo();
    this.goTo('#cardsPage');
  },
  logoutUser: function(){
    this.goTo('#loginPage');
  },
  updatePersonalInfo: function(){
    var name = localStorage.getItem("u_first_name");
    name += " " + localStorage.getItem("u_last_name");
    $(".uName").text(name);
    $(".uSchoolName").text(localStorage.getItem('u_school_name'));
  },
  showObservation: function(observations){
    observation = observations[0];
    $('#emptyNotice').hide();
    this.updateNickname(observation);
    this.updateObservationForm(observation);
    $('.time').datebox({
        mode: "durationflipbox",
        overrideDurationOrder:["h","i","s"],
        overrideDurationFormat: "%DM:%DS"
    });
  },
  updateNickname: function(observation){
    var student = observation[2];
    var nickname = student['nickname'];
    $("#sAlias").text(nickname);
  },
  updateObservationForm: function(observation){
    var record_inputs = this.makeRecordInputs(observation[1]);
    $('#observationRecordsForm').prepend($(record_inputs));
    $('#observationRecordsForm').trigger('create');
  },
  makeRecordInputs: function(records){
    var inputs = '';
    $.each(records, function(index, record){
      console.log(record)
      input = '' + record["prompt"]  + ''
      if(record["meme"] == "Time"){
        input += '<input name="' + record["id"] + '" type="text" placeholder="10" class="time" />';
      } else if(record["meme"] == "Percentage"){
        input += '<input type="range" name="' + record["id"] + '" value="50" min="0" max="100" />';
      } else if(record["meme"] == "Qualitative"){
        input += '<input type="range" name="' + record["id"] + '" value="5" min="0" max="5" />';
      } else if(record["meme"] == "Incidence"){
        input += '<input type="text" name="' + record["id"] + '"/>';
      } else if(record["meme"] == "Boolean"){
        input += '<select name="' + record["id"] + '" data-role="slider"><option value="true">Yes</option><option value="false">No</option></select>';
      } else {
        input += '<input type="text" name="' + record["id"] + '" />';
      }
      inputs += input;
    });
    return inputs;
  }
}

var app = {
  initialize: function() {
    this.bindEvents();
  },
  bindEvents: function() {
    $("#loginForm").submit(this.submitLoginForm);
    $("#observationRecordsForm").submit(this.submitObservationForm);
    $("#logoutLink").click(this.handleLogOut);
  },
  handleLogOut: function(){
    localStorage.removeItem("uid");
    localStorage.removeItem("utoken");
    view.logoutUser();
  },
  getObservations: function(user_id, authenticity_token){
    var data = "user_id=" + user_id + "&authenticity_token=" + authenticity_token;

    get('http://localhost:3000/api/v1/observations?' + data)
      .then(function(serverData){
        console.log(serverData)
        localStorage.setItem("observation_id", serverData[0][0]["id"]);
        view.showObservation(serverData);
      })
      .catch(function(serverData){
        console.log('error');
        console.log(serverData.responseText)
      });
  },
  submitLoginForm: function(){
    var data = $("#loginForm").serialize();
    post('http://localhost:3000/api/v1/login', data)
      .then(function(serverData){
        localStorage.setItem("uid", serverData.id);
        localStorage.setItem("utoken", serverData.token);
        localStorage.setItem("u_first_name", serverData.first_name);
        localStorage.setItem("u_last_name", serverData.last_name);
        localStorage.setItem("u_school_name", serverData.school_name);

        app.getObservations(serverData.id, serverData.token);
        view.loginUser();
      })
      .catch(function(serverData){
        view.errorMessage('#loginError', serverData.responseText);
      });

    return false;
  },
  submitObservationForm: function(){
    var id = localStorage.getItem('observation_id');
    var data = $("#observationRecordsForm").serialize();
    var action = "http://localhost:3000/api/v1/observations/" + id;
    console.log(data);
    console.log(action);
    // post(login', data)
    //   .then(function(serverData){
    //     localStorage.setItem("uid", serverData.id);
    //     localStorage.setItem("utoken", serverData.token);
    //     localStorage.setItem("u_first_name", serverData.first_name);
    //     localStorage.setItem("u_last_name", serverData.last_name);
    //     localStorage.setItem("u_school_name", serverData.school_name);

    //     app.getObservations(serverData.id, serverData.token);
    //     view.loginUser();
    //   })
    //   .catch(function(serverData){
    //     view.errorMessage('#loginError', serverData.responseText);
    //   });
    return false;
  }
};<|endoftext|>