<commit_before>define(
  ["jquery"],
  function($) {

    $(document).ready(function(){
      setTimeout(function(){
        appMaster.init();
      },100);
    });

    var appMaster = {

      currentLevel : 0,
      levelGoalStep : 0, //This is the goal step of the level

      //Various element placeholders
      levelStatus : "",
      stepStatus : "",
      gameStatus : "",
      phoneCanvas : "",

      levels : [
        {
        "description" : "Cat.Random()",
        "steps" : [
          {
            "description" : "Place a randomcat component on the phone",
            "component" : "app-randomcat",
            "goal"    : "place",
            "completed" : false,
            "levelgoal" : true
          }]
        },
        {
        "description" : "Butt Out!",
        "steps" : [
          {
            "description" : "Click a button",
            "component" : "app-button",
            "goal"    : "event",
            "eventName"   : "broadcast",
            "eventValue" : "Click",
            "completed" : false,
            "levelgoal" : true
          }]
        },

        {
        "description" : "That food sucked!",
        "steps" : [
          {
            "description" : "Give a one star rating",
            "component" : "app-rating",
            "goal"    : "event",
            "eventName"   : "emit",
            "eventValue" : 1,
            "completed" : false,
            "levelgoal" : true
          }]
        },
        {
        "description" : "Humble Beginnings",
        "steps" : [
          {
            "description" : "Place a button on the page",
            "component" : "app-button",
            "goal"    : "place",
            "completed" : false
          },
          {
            "description" : "Place a fireworks on the page",
            "component" : "app-fireworks",
            "goal"    : "place",
            "completed" : false
          },
          {
            "description" : "Shoot a firework",
            "component" : "app-fireworks",
            "goal"    : "event",
            "eventName"   : "shootRocket",
            "completed" : false,
            "levelgoal" : true
          }
          ]
        },
      ],
      init : function(){
        console.log(localStorage.wantGame);
        if(localStorage.wantGame == "yep"){
          this.startGame();
        }
      },
      startGame : function(){

        $("body").prepend("
 \

 \

\
            Next Level\

\

\

\

\
            START\
            I don't want to play :(\
            I'm Stuck!\

\

");

        this.gameStatus = $(".game-status");
        this.levelStatus = $(".level-status");
        this.stepList = $(".step-list");

        this.phoneCanvas = $(".phone-canvas");
        var t = this;

        this.loadLevel(1);

        this.gameStatus.find(".start").on("click",function(){
          t.gameStatus.removeClass("big");
          return false;
        });
        this.gameStatus.find(".show-hints").on("click",function(){
          $(this).hide();
          t.gameStatus.find(".hint-step").show();
          return false;
        });

        this.gameStatus.find(".next-level").on("click",function(){
          t.currentLevel++;
          t.loadLevel(t.currentLevel);
          return false;
        });

        this.gameStatus.find(".optout").on("click",function(){
          t.endGame();
          return false;
        });

      },
      endGame : function() {
        localStorage.wantGame = "nah";
        this.gameStatus.remove();
      },
      changeStatus : function(type,status){
        if(type == "level"){
          this.levelStatus.html(status);
        }
      },
      loadLevel : function(levelNumber){

        this.phoneCanvas.find("*").remove();
        this.currentLevel = levelNumber;
        this.gameStatus.addClass("big");
        this.gameStatus.find(".level-finished").hide();
        this.gameStatus.find(".level-intro").show();

        var level = this.levels[levelNumber-1];
        var description = level["description"];
        var steps = level["steps"];
        this.changeStatus("level","Level " + this.currentLevel + " - " + description);

        //Loads all the Steps and listners
        this.stepList.html("");

        for(var i = 0;  i < steps.length; i++){
          var step = steps[i];

          var stepEl = document.createElement("div");

          $(stepEl).text(step["description"]);
          $(stepEl).attr("level",i);

          if(step["levelgoal"]){
            this.levelGoalStep = i;
            $(stepEl).addClass("goal-step");
          } else {
            $(stepEl).addClass("hint-step");
          }

          this.stepList.append(stepEl);

          if(step["goal"] == "place"){
            this.addPlaceChecker(step["component"],i);
          }
          if(step["goal"] == "event"){
            this.addEventChecker(step["component"],step["eventName"],step["eventValue"],i);
          }
        }

        if (steps.length > 1) {
          this.gameStatus.find(".show-hints").show();
        } else {
          this.gameStatus.find(".show-hints").hide();
        }

      },
      checkLevelFinish : function(){
        var t = this;
        var done = this.levels[this.currentLevel-1]["steps"][this.levelGoalStep]["completed"];
        if(done){
          setTimeout(function(){
            t.gameStatus.addClass("big").show();
            t.gameStatus.find(".level-finished").show();
            t.gameStatus.find(".level-intro").hide();
            t.gameStatus.find(".level-finished h1").text("Congrats, you finished Level " + this.currentLevel + ", you monster!");
          },1000);
        }
      },
      finishStep : function(step){
        this.levels[this.currentLevel-1]["steps"][step]["completed"] = true;
        var stepItem = this.stepList.find("div[level="+step+"]");
        stepItem.css("text-decoration","line-through");
        this.checkLevelFinish();
      },
      addPlaceChecker : function(component,step){
        var t = this;
        var checkerInterval = setInterval(function(){
          var present = false;
          if($(".phone-canvas").find(component).length > 0){
            present = true;
            t.finishStep(step);
            clearInterval(checkerInterval);
          }
        },300);
      },
      addEventChecker : function(component,eventName,eventValue,step){
        var t = this;
        var checkerInterval = setInterval(function(){
          var present = false;
          if($(".phone-canvas").find(component).length > 0){

            var el = $(component)[0];
            var originalEvent = el[eventName];

            el[eventName] = function(value){
              if(eventValue){
                if(value == eventValue){
                  t.finishStep(step);
                  el[eventName] = originalEvent;
                  el[eventName](value);
                }
              } else {
                t.finishStep(step);
                el[eventName] = originalEvent;
                el[eventName](value);
              }

            }
            clearInterval(checkerInterval);
          }
        },300);

      }
    }
   }
);
<commit_msg>Added missing semicolons (thanks grunt!)<commit_after>define(
  ["jquery"],
  function($) {

    $(document).ready(function(){
      setTimeout(function(){
        appMaster.init();
      },100);
    });

    var appMaster = {

      currentLevel : 0,
      levelGoalStep : 0, //This is the goal step of the level

      //Various element placeholders
      levelStatus : "",
      stepStatus : "",
      gameStatus : "",
      phoneCanvas : "",

      levels : [
        {
        "description" : "Cat.Random()",
        "steps" : [
          {
            "description" : "Place a randomcat component on the phone",
            "component" : "app-randomcat",
            "goal"    : "place",
            "completed" : false,
            "levelgoal" : true
          }]
        },
        {
        "description" : "Butt Out!",
        "steps" : [
          {
            "description" : "Click a button",
            "component" : "app-button",
            "goal"    : "event",
            "eventName"   : "broadcast",
            "eventValue" : "Click",
            "completed" : false,
            "levelgoal" : true
          }]
        },

        {
        "description" : "That food sucked!",
        "steps" : [
          {
            "description" : "Give a one star rating",
            "component" : "app-rating",
            "goal"    : "event",
            "eventName"   : "emit",
            "eventValue" : 1,
            "completed" : false,
            "levelgoal" : true
          }]
        },
        {
        "description" : "Humble Beginnings",
        "steps" : [
          {
            "description" : "Place a button on the page",
            "component" : "app-button",
            "goal"    : "place",
            "completed" : false
          },
          {
            "description" : "Place a fireworks on the page",
            "component" : "app-fireworks",
            "goal"    : "place",
            "completed" : false
          },
          {
            "description" : "Shoot a firework",
            "component" : "app-fireworks",
            "goal"    : "event",
            "eventName"   : "shootRocket",
            "completed" : false,
            "levelgoal" : true
          }
          ]
        },
      ],
      init : function(){
        console.log(localStorage.wantGame);
        if(localStorage.wantGame == "yep"){
          this.startGame();
        }
      },
      startGame : function(){

        $("body").prepend("
\

\

\
            Next Level\

\

\

\

\
            START\
            I don't want to play :(\
            I'm Stuck!\

\

");

        this.gameStatus = $(".game-status");
        this.levelStatus = $(".level-status");
        this.stepList = $(".step-list");

        this.phoneCanvas = $(".phone-canvas");
        var t = this;

        this.loadLevel(1);

        this.gameStatus.find(".start").on("click",function(){
          t.gameStatus.removeClass("big");
          return false;
        });
        this.gameStatus.find(".show-hints").on("click",function(){
          $(this).hide();
          t.gameStatus.find(".hint-step").show();
          return false;
        });

        this.gameStatus.find(".next-level").on("click",function(){
          t.currentLevel++;
          t.loadLevel(t.currentLevel);
          return false;
        });

        this.gameStatus.find(".optout").on("click",function(){
          t.endGame();
          return false;
        });

      },
      endGame : function() {
        localStorage.wantGame = "nah";
        this.gameStatus.remove();
      },
      changeStatus : function(type,status){
        if(type == "level"){
          this.levelStatus.html(status);
        }
      },
      loadLevel : function(levelNumber){

        this.phoneCanvas.find("*").remove();
        this.currentLevel = levelNumber;
        this.gameStatus.addClass("big");
        this.gameStatus.find(".level-finished").hide();
        this.gameStatus.find(".level-intro").show();

        var level = this.levels[levelNumber-1];
        var description = level["description"];
        var steps = level["steps"];
        this.changeStatus("level","Level " + this.currentLevel + " - " + description);

        //Loads all the Steps and listners
        this.stepList.html("");

        for(var i = 0;  i < steps.length; i++){
          var step = steps[i];

          var stepEl = document.createElement("div");

          $(stepEl).text(step["description"]);
          $(stepEl).attr("level",i);

          if(step["levelgoal"]){
            this.levelGoalStep = i;
            $(stepEl).addClass("goal-step");
          } else {
            $(stepEl).addClass("hint-step");
          }

          this.stepList.append(stepEl);

          if(step["goal"] == "place"){
            this.addPlaceChecker(step["component"],i);
          }
          if(step["goal"] == "event"){
            this.addEventChecker(step["component"],step["eventName"],step["eventValue"],i);
          }
        }

        if (steps.length > 1) {
          this.gameStatus.find(".show-hints").show();
        } else {
          this.gameStatus.find(".show-hints").hide();
        }

      },
      checkLevelFinish : function(){
        var t = this;
        var done = this.levels[this.currentLevel-1]["steps"][this.levelGoalStep]["completed"];
        if(done){
          setTimeout(function(){
            t.gameStatus.addClass("big").show();
            t.gameStatus.find(".level-finished").show();
            t.gameStatus.find(".level-intro").hide();
            t.gameStatus.find(".level-finished h1").text("Congrats, you finished Level " + this.currentLevel + ", you monster!");
          },1000);
        }
      },
      finishStep : function(step){
        this.levels[this.currentLevel-1]["steps"][step]["completed"] = true;
        var stepItem = this.stepList.find("div[level="+step+"]");
        stepItem.css("text-decoration","line-through");
        this.checkLevelFinish();
      },
      addPlaceChecker : function(component,step){
        var t = this;
        var checkerInterval = setInterval(function(){
          var present = false;
          if($(".phone-canvas").find(component).length > 0){
            present = true;
            t.finishStep(step);
            clearInterval(checkerInterval);
          }
        },300);
      },
      addEventChecker : function(component,eventName,eventValue,step){
        var t = this;
        var checkerInterval = setInterval(function(){
          var present = false;
          if($(".phone-canvas").find(component).length > 0){

            var el = $(component)[0];
            var originalEvent = el[eventName];

            el[eventName] = function(value){
              if(eventValue){
                if(value == eventValue){
                  t.finishStep(step);
                  el[eventName] = originalEvent;
                  el[eventName](value);
                }
              } else {
                t.finishStep(step);
                el[eventName] = originalEvent;
                el[eventName](value);
              }
            };
            clearInterval(checkerInterval);
          }
        },300);
      }
    };
});
<|endoftext|>


<commit_before>/*!
 * Copyright 2015 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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 _ = require('underscore');
var fs = require('fs');
var gift = require('gift');
var path = require('path');
var util = require('util');

var IO = require('oae-util/lib/io');
var log = require('oae-logger').logger('oae-version');

// A variable that will hold the path to the UI directory
var _uiPath = null;

// A variable that will hold a copy of the version information
var _version = null;

/**
 * Initialize the version module
 *
 * @param  {String}     uiPath  The path to the UI directory
 */
var init = module.exports.init = function(uiPath) {
    _uiPath = uiPath;
};

/**
 * Get the version information for OAE
 *
 * @param  {Function}   callback                    Standard callback function
 * @param  {Object}     callback.err                An error that occurred, if any
 * @param  {Object}     callback.version            The version information
 * @param  {String}     callback.version.hilary     The version information for Hilary
 * @param  {String}     callback.version.3akai-ux   The version information for the UI
 */
var getVersion = module.exports.getVersion = function(callback) {
    if (_version) {
        return callback(null, _version);
    }

    _getHilaryVersion(function(err, hilaryVersion) {
        if (err) {
            return callback(err);
        }

        _getUIVersion(function(err, uiVersion) {
            if (err) {
                return callback(err);
            }

            _version = {
                'hilary': hilaryVersion,
                '3akai-ux': uiVersion
            };
            return callback(null, _version);
        });
    });
};

/**
 * Get the version information for the backend
 *
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the backend
 * @api private
 */
function _getHilaryVersion(callback) {
    var hilaryDirectory = path.resolve(__dirname, '..', '..', '..');
    _getVersionInfo(hilaryDirectory, callback);
}

/**
 * Get the version information for the UI
 *
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the UI
 * @api private
 */
function _getUIVersion(callback) {
    _getVersionInfo(_uiPath, callback);
}

/**
 * Get the version information for a directory. The version will be retrieved from
 * the build info file in the root of the directory. If there's no such file present
 * or it can't be parsed, the information will be retrieved from git. If that fails
 * as well `Unknown` will be returned
 *
 * @param  {String}     directory           The directory to get the version information for
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the directory
 * @api private
 */
function _getVersionInfo(directory, callback) {
    _getBuildInfoFile(directory, function(err, buildInfoPath) {
        if (err) {
            return callback(err);
        } else if (buildInfoPath) {
            return _getBuildVersion(buildInfoPath, callback);
        } else {
            return _getGitVersion(directory, callback);
        }
    });
}

/**
 * Each generated build has a `build-info.json` file that contains information about the build.
 * Parse it and return the relevant version information
 *
 * @param  {String}     buildInfoPath       The path to the build info file
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the directory
 * @api private
 */
function _getBuildVersion(buildInfoPath, callback) {
    fs.readFile(buildInfoPath, function(err, buildInfo) {
        if (err) {
            return callback({'code': 500, 'msg': 'Unable to read the build info file'});
        }

        try {
            buildInfo = JSON.parse(buildInfo);
        } catch (ex) {
            log().error({
                'err': ex,
                'path': buildInfoPath
            }, 'Unable to parse the build info file');
            return callback({'code': 500, 'msg': 'Unable to parse the build info file'});
        }
        buildInfo.type = 'archive';

        return callback(null, buildInfo);
    });
}

/**
 * Get the version from git
 *
 * @param  {String}     directory           The directory to the git repository
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the directory
 * @api private
 */
function _getGitVersion(directory, callback) {
    gift.init(directory, function(err, repo) {
        if (err) {
            log().error({
                'err': err,
                'path': directory
            }, 'Could not open the git repo to get the version information');
            return callback({'code': 500, 'msg': 'Could not open the git repo'});
        }

        // Get the tag info
         repo.tags(function(err, tags) {
            if (err) {
                log().error({
                    'err': err,
                    'path': directory
                }, 'Could not get the git tags');
                return callback({'code': 500, 'msg': 'Could not get the git tags'});
            }

            var tagsByCommitId = _.indexBy(tags, function(tag) {
                return tag.commit.id;
            });

            // Get the current branch info
            repo.branch(function(err, branch) {
                if (err) {
                    log().error({
                        'err': err,
                        'path': directory
                    }, 'Could not get the current git branch for the version information');
                    return callback({'code': 500, 'msg': 'Could not get the branch information'});
                }

                // Get the number of commits since the last tag
                _getGitDescribeVersion(repo, branch.name, tagsByCommitId, function(err, describeVersion) {
                    if (err) {
                        log().error({
                            'err': err,
                            'path': directory
                        }, 'Could not get the git describe version for a repo');
                        return callback({'code': 500, 'msg': 'Could not get the branch information'});
                    }

                    var buildInfo = {
                        'branch': branch.name,
                        'date': branch.commit.committed_date,
                        'type': 'git',
                        'version': describeVersion
                    };
                    return callback(null, buildInfo);
                });
            });
        });
    });
}

/**
 * Get a "git describe"-like descriptor for a branch.
 *
 * This will return information in the form:
 *   <last tag>+<number of commits>+<sha1 of last commit>
 *
 * @param  {Repository}     repo                The git repository to get the information for
 * @param  {String}         branchName          The name of the branch to get the information for
 * @param  {Object}         tagsByCommitId      The Tag objects keyed by their commit sha1 hash
 * @param  {Function}       callback            Standard callback function
 * @param  {Object}         callback.err        An error that occurred, if any
 * @param  {String}         callback.version    The git describe information
 * @api private
 */
function _getGitDescribeVersion(repo, branchName, tagsByCommitId, callback, _nrOfCommits, _lastCommitSha) {
    _nrOfCommits = _nrOfCommits || 0;
    repo.commits(branchName, 30, _nrOfCommits, function(err, commits) {
        if (err) {
            return callback(err);
        }

        // Retain the sha1 of the last commit on this branch
        _lastCommitSha = _lastCommitSha || commits[0].id;

        // Try to find the last tagged commit in these set of commits
        var lastTag = null;
        for (var i = 0; i < commits.length; i++) {
            if (tagsByCommitId[commits[i].id]) {
                lastTag = tagsByCommitId[commits[i].id].name;
                break;
            }
            _nrOfCommits++;
        }

        // If we found a tag in the set of commits we can return the git describe information
        if (lastTag) {
            var describeVersion = util.format('%s+%d+%s', lastTag, _nrOfCommits, _lastCommitSha);
            return callback(null, describeVersion);

        // Otherwise we need to retrieve the next set of commits
        } else {
            return _getGitDescribeVersion(repo, branchName, tagsByCommitId, callback, _nrOfCommits, _lastCommitSha);
        }
    });
}
/**
 * Check whether a directory has a build-info.json file. This function
 * will recursively check each parent directory as well.
 *
 * @param  {String}     directory                       The directory to get the version information for
 * @param  {Function}   callback                        Standard callback function
 * @param  {Object}     callback.err                    An error that occurred, if any
 * @param  {String}     [callback.buildInfoPath]        The path to the build-info.json file. `null` if no such file could be found
 * @api private
 */
function _getBuildInfoFile(directory, callback) {
    var buildInfoPath = _getBuildInfoFilePath(directory);
    IO.exists(buildInfoPath, function(err, exists) {
        if (err) {
            log.error({
                'directory': directory,
                'err': err
            }, 'Unable to check if a build info file exists');
            return callback(err);
        } else if (exists) {
            return callback(null, buildInfoPath);
        } else {
            var parent = path.dirname(directory);
            if (parent !== directory) {
                return _getBuildInfoFile(parent, callback);
            } else {
                return callback(null, null);
            }
        }
    });
}

/**
 * Get the path to the `build-info.json` file
 *
 * @param  {String}     directory       The directory to get the version information for
 * @return {String}                     The path to the `build-info.json` file
 * @api private
 */
function _getBuildInfoFilePath(directory) {
    return path.join(directory, 'build-info.json');
}
<commit_msg>Style issue in versions api<commit_after>/*!
 * Copyright 2015 Apereo Foundation (AF) Licensed under the
 * Educational Community 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://opensource.org/licenses/ECL-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 _ = require('underscore');
var fs = require('fs');
var gift = require('gift');
var path = require('path');
var util = require('util');

var IO = require('oae-util/lib/io');
var log = require('oae-logger').logger('oae-version');

// A variable that will hold the path to the UI directory
var _uiPath = null;

// A variable that will hold a copy of the version information
var _version = null;

/**
 * Initialize the version module
 *
 * @param  {String}     uiPath  The path to the UI directory
 */
var init = module.exports.init = function(uiPath) {
    _uiPath = uiPath;
};

/**
 * Get the version information for OAE
 *
 * @param  {Function}   callback                    Standard callback function
 * @param  {Object}     callback.err                An error that occurred, if any
 * @param  {Object}     callback.version            The version information
 * @param  {String}     callback.version.hilary     The version information for Hilary
 * @param  {String}     callback.version.3akai-ux   The version information for the UI
 */
var getVersion = module.exports.getVersion = function(callback) {
    if (_version) {
        return callback(null, _version);
    }

    _getHilaryVersion(function(err, hilaryVersion) {
        if (err) {
            return callback(err);
        }

        _getUIVersion(function(err, uiVersion) {
            if (err) {
                return callback(err);
            }

            _version = {
                'hilary': hilaryVersion,
                '3akai-ux': uiVersion
            };
            return callback(null, _version);
        });
    });
};

/**
 * Get the version information for the backend
 *
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the backend
 * @api private
 */
function _getHilaryVersion(callback) {
    var hilaryDirectory = path.resolve(__dirname, '..', '..', '..');
    _getVersionInfo(hilaryDirectory, callback);
}

/**
 * Get the version information for the UI
 *
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the UI
 * @api private
 */
function _getUIVersion(callback) {
    _getVersionInfo(_uiPath, callback);
}

/**
 * Get the version information for a directory. The version will be retrieved from
 * the build info file in the root of the directory. If there's no such file present
 * or it can't be parsed, the information will be retrieved from git. If that fails
 * as well `Unknown` will be returned
 *
 * @param  {String}     directory           The directory to get the version information for
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the directory
 * @api private
 */
function _getVersionInfo(directory, callback) {
    _getBuildInfoFile(directory, function(err, buildInfoPath) {
        if (err) {
            return callback(err);
        } else if (buildInfoPath) {
            return _getBuildVersion(buildInfoPath, callback);
        } else {
            return _getGitVersion(directory, callback);
        }
    });
}

/**
 * Each generated build has a `build-info.json` file that contains information about the build.
 * Parse it and return the relevant version information
 *
 * @param  {String}     buildInfoPath       The path to the build info file
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the directory
 * @api private
 */
function _getBuildVersion(buildInfoPath, callback) {
    fs.readFile(buildInfoPath, function(err, buildInfo) {
        if (err) {
            return callback({'code': 500, 'msg': 'Unable to read the build info file'});
        }

        try {
            buildInfo = JSON.parse(buildInfo);
        } catch (ex) {
            log().error({
                'err': ex,
                'path': buildInfoPath
            }, 'Unable to parse the build info file');
            return callback({'code': 500, 'msg': 'Unable to parse the build info file'});
        }
        buildInfo.type = 'archive';

        return callback(null, buildInfo);
    });
}

/**
 * Get the version from git
 *
 * @param  {String}     directory           The directory to the git repository
 * @param  {Function}   callback            Standard callback function
 * @param  {Object}     callback.err        An error that occurred, if any
 * @param  {String}     callback.version    The version information for the directory
 * @api private
 */
function _getGitVersion(directory, callback) {
    gift.init(directory, function(err, repo) {
        if (err) {
            log().error({
                'err': err,
                'path': directory
            }, 'Could not open the git repo to get the version information');
            return callback({'code': 500, 'msg': 'Could not open the git repo'});
        }

        // Get the tag info
         repo.tags(function(err, tags) {
            if (err) {
                log().error({
                    'err': err,
                    'path': directory
                }, 'Could not get the git tags');
                return callback({'code': 500, 'msg': 'Could not get the git tags'});
            }

            var tagsByCommitId = _.indexBy(tags, function(tag) {
                return tag.commit.id;
            });

            // Get the current branch info
            repo.branch(function(err, branch) {
                if (err) {
                    log().error({
                        'err': err,
                        'path': directory
                    }, 'Could not get the current git branch for the version information');
                    return callback({'code': 500, 'msg': 'Could not get the branch information'});
                }

                // Get the number of commits since the last tag
                _getGitDescribeVersion(repo, branch.name, tagsByCommitId, function(err, describeVersion) {
                    if (err) {
                        log().error({
                            'err': err,
                            'path': directory
                        }, 'Could not get the git describe version for a repo');
                        return callback({'code': 500, 'msg': 'Could not get the branch information'});
                    }

                    var buildInfo = {
                        'branch': branch.name,
                        'date': branch.commit.committed_date,
                        'type': 'git',
                        'version': describeVersion
                    };
                    return callback(null, buildInfo);
                });
            });
        });
    });
}

/**
 * Get a "git describe"-like descriptor for a branch.
 *
 * This will return information in the form:
 *   <last tag>+<number of commits>+<sha1 of last commit>
 *
 * @param  {Repository}     repo                The git repository to get the information for
 * @param  {String}         branchName          The name of the branch to get the information for
 * @param  {Object}         tagsByCommitId      The Tag objects keyed by their commit sha1 hash
 * @param  {Function}       callback            Standard callback function
 * @param  {Object}         callback.err        An error that occurred, if any
 * @param  {String}         callback.version    The git describe information
 * @api private
 */
function _getGitDescribeVersion(repo, branchName, tagsByCommitId, callback, _nrOfCommits, _lastCommitSha) {
    _nrOfCommits = _nrOfCommits || 0;
    repo.commits(branchName, 30, _nrOfCommits, function(err, commits) {
        if (err) {
            return callback(err);
        }

        // Retain the sha1 of the last commit on this branch
        _lastCommitSha = _lastCommitSha || commits[0].id;

        // Try to find the last tagged commit in these set of commits
        var lastTag = null;
        for (var i = 0; i < commits.length; i++) {
            if (tagsByCommitId[commits[i].id]) {
                lastTag = tagsByCommitId[commits[i].id].name;
                break;
            }
            _nrOfCommits++;
        }

        // If we found a tag in the set of commits we can return the git describe information
        if (lastTag) {
            var describeVersion = util.format('%s+%d+%s', lastTag, _nrOfCommits, _lastCommitSha);
            return callback(null, describeVersion);

        // Otherwise we need to retrieve the next set of commits
        } else {
            return _getGitDescribeVersion(repo, branchName, tagsByCommitId, callback, _nrOfCommits, _lastCommitSha);
        }
    });
}
/**
 * Check whether a directory has a build-info.json file. This function
 * will recursively check each parent directory as well.
 *
 * @param  {String}     directory                       The directory to get the version information for
 * @param  {Function}   callback                        Standard callback function
 * @param  {Object}     callback.err                    An error that occurred, if any
 * @param  {String}     [callback.buildInfoPath]        The path to the build-info.json file. `null` if no such file could be found
 * @api private
 */
function _getBuildInfoFile(directory, callback) {
    var buildInfoPath = _getBuildInfoFilePath(directory);
    IO.exists(buildInfoPath, function(err, exists) {
        if (err) {
            log.error({
                'directory': directory,
                'err': err
            }, 'Unable to check if a build info file exists');
            return callback(err);
        } else if (exists) {
            return callback(null, buildInfoPath);
        } else {
            var parent = path.dirname(directory);
            if (parent !== directory) {
                return _getBuildInfoFile(parent, callback);
            } else {
                return callback();
            }
        }
    });
}

/**
 * Get the path to the `build-info.json` file
 *
 * @param  {String}     directory       The directory to get the version information for
 * @return {String}                     The path to the `build-info.json` file
 * @api private
 */
function _getBuildInfoFilePath(directory) {
    return path.join(directory, 'build-info.json');
}
<|endoftext|>


<commit_before>'use strict';

/* eslint-disable */

function PushReceiver(quiet) {
    this.set = {};
    this.quiet = true;
    if (quiet != undefined) {
        this.quiet = quiet;
    }
};

function __aggr(tgt, src) {
    for(var key in src) {
        if(!tgt.hasOwnProperty(key)) {
            tgt[key] = { "_type" : src[key]._type, "_value": []};
        }
        if (Array.isArray(src[key]._value)) {
            for (var v in src[key]._value) {
                tgt[key]._value.push(src[key]._value[v]);
            }
        } else {
            tgt[key]._value.push(src[key]._value);
        }
    }
}

PushReceiver.prototype.run = function(details, cb, req, args, instance) {
    const num_items = Object.keys(this.set).length;
    const metrics = {};

    for (var x in this.set) {
        var o = this.set[x];

        var period = req ? req.headers['x-reconnoiter-period'] : 0;
        if(!period) period = 60000;
        var this_idx = Math.floor((+new Date()) / 1000);
        var start_idx = this_idx -= Math.floor(period/1000);
        var s = {};
        for(var i = start_idx; i <= o.last_idx; i++) {
            __aggr(s, o.windows[i % 60]);
        }

        metrics[x] = s;
    }

    cb(details, metrics, instance);
    details.running = false;
};

PushReceiver.prototype.some_data = function(name, incoming_data) {
    if (this.quiet === false) {
        console.log("Received some_data for [" + name + "]: " + incoming_data);
    }

    if (!this.set.hasOwnProperty(name)) {
        this.set[name] = {
            last_idx: 0,
            windows: []
        };
        for (var i = 0; i < 60; i++) {
            this.set[name].windows[i] = {};
        }
    }

    var o = this.set[name];

    /* for each incoming key, save all the data */
    var this_idx = Math.floor((+new Date()) / 1000);
    if(!o.last_idx) o.last_idx = this_idx;

    /* everything from last up to now is moot */
    for(var i = o.last_idx + 1; i < this_idx; i++) {
      o.windows[i % 60] = {};
    }

    let data = null;

    try {
        data = JSON.parse(incoming_data);
    } catch (err) {
        console.error(err);
        return;
    }

    if (this.quiet === false) {
        console.log("Saving incoming " + JSON.stringify(x) + " in " + (this_idx % 60));
    }

    o.windows[this_idx % 60] = data;
    o.last_idx = this_idx;
};

module.exports = PushReceiver;
<commit_msg>fix: downgrade for node v0.10<commit_after>'use strict';

/* eslint-disable */

function PushReceiver(quiet) {
    this.set = {};
    this.quiet = true;
    if (quiet != undefined) {
        this.quiet = quiet;
    }
};

function __aggr(tgt, src) {
    for(var key in src) {
        if(!tgt.hasOwnProperty(key)) {
            tgt[key] = { "_type" : src[key]._type, "_value": []};
        }
        if (Array.isArray(src[key]._value)) {
            for (var v in src[key]._value) {
                tgt[key]._value.push(src[key]._value[v]);
            }
        } else {
            tgt[key]._value.push(src[key]._value);
        }
    }
}

PushReceiver.prototype.run = function(details, cb, req, args, instance) {
    var num_items = Object.keys(this.set).length;
    var metrics = {};

    for (var x in this.set) {
        var o = this.set[x];

        var period = req ? req.headers['x-reconnoiter-period'] : 0;
        if(!period) period = 60000;
        var this_idx = Math.floor((+new Date()) / 1000);
        var start_idx = this_idx -= Math.floor(period/1000);
        var s = {};
        for(var i = start_idx; i <= o.last_idx; i++) {
            __aggr(s, o.windows[i % 60]);
        }

        metrics[x] = s;
    }

    cb(details, metrics, instance);
    details.running = false;
};

PushReceiver.prototype.some_data = function(name, incoming_data) {
    if (this.quiet === false) {
        console.log("Received some_data for [" + name + "]: " + incoming_data);
    }

    if (!this.set.hasOwnProperty(name)) {
        this.set[name] = {
            last_idx: 0,
            windows: []
        };
        for (var i = 0; i < 60; i++) {
            this.set[name].windows[i] = {};
        }
    }

    var o = this.set[name];

    /* for each incoming key, save all the data */
    var this_idx = Math.floor((+new Date()) / 1000);
    if(!o.last_idx) o.last_idx = this_idx;

    /* everything from last up to now is moot */
    for(var i = o.last_idx + 1; i < this_idx; i++) {
      o.windows[i % 60] = {};
    }

    var data = null;

    try {
        data = JSON.parse(incoming_data);
    } catch (err) {
        console.error(err);
        return;
    }

    if (this.quiet === false) {
        console.log("Saving incoming " + JSON.stringify(x) + " in " + (this_idx % 60));
    }

    o.windows[this_idx % 60] = data;
    o.last_idx = this_idx;
};

module.exports = PushReceiver;
<|endoftext|>


<commit_before>var app = angular.module('pelias', []);

app.run(function($rootScope) {});

app.controller('SearchController', function($scope, $rootScope, $sce, $http) {

  var default_zoom = 3;

  $scope.map = L.map('map', {
      zoom: default_zoom,
      center: [0,0],
      maxBounds: L.latLngBounds(L.latLng(-80, -180), L.latLng(82, 180))
  });

  L.tileLayer('//{s}.tiles.mapbox.com/v3/randyme.i0568680/{z}/{x}/{y}.png', {
      attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
      maxZoom: 18,
      minZoom: 3,
      noWrap: true
  }).addTo($scope.map);
  $scope.map_class = 'hidden';

  $scope.search = '';
  $scope.searchresults = [];
  $scope.searchType = 'fine';
  $scope.api_url = '//pelias.mapzen.com';
  $scope.feedback_url = '/';
  $scope.resultsSelected = 0;
  $scope.button = {
    class: 'hidden',
    text: ''
  }
  $scope.log={};
  $scope.attempt =0;

  var not_found = {
    class: 'btn-danger',
    text: 'Not Found'
  };

  var not_found_in_pelias = not_found.text + ' in pelias? Click here to search other sources';
  var not_found_in_nominatum = not_found.text + ' in other sources either? Click here to report';
  var calling_nominatum = 'Please wait, Searching other sources..';
  var uploading_feedback= 'Sending your feedback! Thank you again';

  var found = {
    class: 'btn-success',
    text: 'Click here to send us your feedback. Thank you!'
  };

  var highlight = function( text, focus ){
    var r = RegExp( '('+ focus + ')', 'gi' );
    return text.replace( r, '$1' );
  }

  var getResults = function(url, resultkey) {
    var params = {
      input: $scope.search,
      // datasets: $scope.queryDatasets.join(','),
      size: 10
    }

    $http({
      url: $scope.api_url+url,
      method: 'GET',
      params: params,
      headers: { 'Accept': 'application/json' }
    }).success(function (data, status, headers, config) {
      if( data ){
        $scope.log = {};
        $scope.attempt = 0;
        $scope[resultkey].length = 0;
        $scope.resultsSelected = 0;
        $scope[resultkey] = data.features.map( function( res ){
          var text = res.properties.text + ((res.properties.alpha3 && (res.properties.text !== res.properties.admin0)) ? ', '+ res.properties.alpha3 : '');
          res.htmltext = $sce.trustAsHtml(highlight( text, $scope.search ));
          res.icon = 'unchecked';
          res.type = res.properties.type;
          return res;
        });
        $scope.button.class = not_found.class;
        $scope.button.text  = not_found_in_pelias;
      }
      else {
        $scope[resultkey] = [];
      }
    }).error(function (data, status, headers, config) {
      $scope[resultkey] = [];
    });
  };

  var getResultsFromNominatum = function(resultkey) {
    var params = {
      q: $scope.search,
      format: 'json'
    };
    resultkey = resultkey || 'searchresults';

    $http({
      url: 'http://nominatim.openstreetmap.org/search',
      method: 'GET',
      params: params,
      headers: { 'Accept': 'application/json' }
    }).success(function (data, status, headers, config) {
      if( data ){
        $scope[resultkey].length = 0;
        $scope.resultsSelected = 0;
        $scope[resultkey] = data.map( function( res ){
          res.htmltext = $sce.trustAsHtml(highlight( res.display_name, $scope.search ));
          res.icon = 'unchecked';
          return res;
        });
      }
      else {
        $scope[resultkey] = [];
      }
      $scope.button.class = not_found.class;
      $scope.button.text  = not_found_in_nominatum;
    }).error(function (data, status, headers, config) {
      $scope[resultkey] = [];
      $scope.button.class = not_found.class;
      $scope.button.text  = not_found_in_nominatum;
    });
  }
  $scope.selectResult = function( result, changeQuery ){
    if (result.icon === 'unchecked') {
      $scope.resultsSelected++;
      result.icon = 'check';
    } else {
      $scope.resultsSelected--;
      result.icon = 'unchecked';
    }
    $scope.button.class = $scope.resultsSelected > 0 ? found.class : not_found.class;
    $scope.button.text  = $scope.resultsSelected > 0 ? found.text : not_found.text;
  }

  $rootScope.$on( 'hideall', function( ev ){
    $scope.searchresults = []
  });

  $rootScope.$on( 'hidesearch', function( ev ){
    $scope.searchresults = [];
  });

  $scope.keyPressed = function(ev) {
    if (ev.which == 13) {
      $scope.fullTextSearch();
    }
  }

  $scope.onFocus = function(ev) {
    // $("#searchresults").removeClass("smaller");
  }

  $scope.onBlur = function(ev) {
    // $("#searchresults").addClass("smaller");
  }

  $scope.fullTextSearch = function(){
    var url = $scope.searchType.toLowerCase() === 'fine' ? '/search' : '/search/coarse';
    getResults(url, 'searchresults');
  }

  var markers = [];
  var remove_markers = function(){
    for (i=0; i<markers.length; i++) {
      $scope.map.removeLayer(markers[i]);
    }
    markers = [];
  };

  var add_marker = function(geo, text) {
    var marker;

    if (typeof text == 'string') {
      marker = new L.marker(geo).bindPopup(text);
    } else if (typeof text == 'object') {
      var full_text = '';
      for (key in text){
        full_text += ('' + key + ': ' + text[key] + '
');
      }
      marker = new L.marker(geo).bindPopup(full_text);
    }

    $scope.map.addLayer(marker);
    markers.push(marker);
    marker.openPopup();
  };

  $scope.showMap = function(result) {
    $scope.map_class = '';
    remove_markers();

    if (result.geometry) {
      var geo = [result.geometry.coordinates[1],result.geometry.coordinates[0]];
      $scope.map.setView(geo, default_zoom);
      add_marker(geo, result.properties);
    } else {
      var geo = [result.lat,result.lon];
      $scope.map.setView(geo, default_zoom);
      add_marker(geo, result.display_name);
    }
  };

  $scope.giveFeedback = function(button_class) {
    var success = button_class === found.class;

    if ($scope.attempt === 0) {
      var searchresults = $scope.searchresults.map(function(res) {
        return {
          type: res.type,
          geometry: res.geometry,
          properties: res.properties,
          icon: res.icon
        }
      });
      $scope.log = {
        query: $scope.search,
        found: success,
        results: searchresults
      };

      $scope.log.foundInPelias = success;
      if (!success) {
        //call nominatum
        $scope.button.class = found.class;
        $scope.button.text  = calling_nominatum;
        getResultsFromNominatum();
      }
    } else {
      // logging nominatum
      var searchresults = $scope.searchresults;
      $scope.log.found = success;
      $scope.log.nominatum_results = searchresults;
    }

    $scope.attempt++;

    if (success) {
      $scope.log.selected = searchresults.filter(function(res){
        return res.icon === 'check';
      });
    }

    if (success || $scope.attempt===2) {
      // upload logs
      $http({
        url: $scope.feedback_url + 'upload',
        method: 'POST',
        params: {'log': $scope.log},
        headers: { 'Accept': 'application/json' }
      }).success(function (data, status, headers, config) {
        $scope.button.class = found.class;
        $scope.button.text  = uploading_feedback;
        resetScope();
      }).error(function (data, status, headers, config) {
        console.log(data);
        resetScope();
      });

      var resetScope = function() {
        // reset
        $scope.search = '';
        $scope.searchresults = [];
        $scope.resultsSelected = 0;
        $scope.button = {
          class: 'hidden',
          text: ''
        }
        $scope.log={};
        $scope.attempt =0;
        $scope.map_class='hidden';
      }
    }
  }

})
<commit_msg>always show the map - set initial map_class as initial_state<commit_after>var app = angular.module('pelias', []);

app.run(function($rootScope) {});

app.controller('SearchController', function($scope, $rootScope, $sce, $http) {

  var default_zoom = 3;

  $scope.map = L.map('map', {
      zoom: default_zoom,
      center: [0,0],
      maxBounds: L.latLngBounds(L.latLng(-80, -180), L.latLng(82, 180))
  });

  L.tileLayer('//{s}.tiles.mapbox.com/v3/randyme.i0568680/{z}/{x}/{y}.png', {
      attribution: 'Map data © OpenStreetMap contributors, CC-BY-SA, Imagery © Mapbox',
      maxZoom: 18,
      minZoom: 3,
      noWrap: true
  }).addTo($scope.map);
  $scope.map_class = 'initial_state';

  $scope.search = '';
  $scope.searchresults = [];
  $scope.searchType = 'fine';
  $scope.api_url = '//pelias.mapzen.com';
  $scope.feedback_url = '/';
  $scope.resultsSelected = 0;
  $scope.button = {
    class: 'hidden',
    text: ''
  }
  $scope.log={};
  $scope.attempt =0;

  var not_found = {
    class: 'btn-danger',
    text: 'Not Found'
  };

  var not_found_in_pelias = not_found.text + ' in pelias? Click here to search other sources';
  var not_found_in_nominatum = not_found.text + ' in other sources either? Click here to report';
  var calling_nominatum = 'Please wait, Searching other sources..';
  var uploading_feedback= 'Sending your feedback! Thank you again';

  var found = {
    class: 'btn-success',
    text: 'Click here to send us your feedback. Thank you!'
  };

  var highlight = function( text, focus ){
    var r = RegExp( '('+ focus + ')', 'gi' );
    return text.replace( r, '$1' );
  }

  var getResults = function(url, resultkey) {
    var params = {
      input: $scope.search,
      // datasets: $scope.queryDatasets.join(','),
      size: 10
    }

    $http({
      url: $scope.api_url+url,
      method: 'GET',
      params: params,
      headers: { 'Accept': 'application/json' }
    }).success(function (data, status, headers, config) {
      if( data ){
        $scope.log = {};
        $scope.attempt = 0;
        $scope[resultkey].length = 0;
        $scope.resultsSelected = 0;
        $scope[resultkey] = data.features.map( function( res ){
          var text = res.properties.text + ((res.properties.alpha3 && (res.properties.text !== res.properties.admin0)) ? ', '+ res.properties.alpha3 : '');
          res.htmltext = $sce.trustAsHtml(highlight( text, $scope.search ));
          res.icon = 'unchecked';
          res.type = res.properties.type;
          return res;
        });
        $scope.button.class = not_found.class;
        $scope.button.text  = not_found_in_pelias;
      }
      else {
        $scope[resultkey] = [];
      }
    }).error(function (data, status, headers, config) {
      $scope[resultkey] = [];
    });
  };

  var getResultsFromNominatum = function(resultkey) {
    var params = {
      q: $scope.search,
      format: 'json'
    };
    resultkey = resultkey || 'searchresults';

    $http({
      url: 'http://nominatim.openstreetmap.org/search',
      method: 'GET',
      params: params,
      headers: { 'Accept': 'application/json' }
    }).success(function (data, status, headers, config) {
      if( data ){
        $scope[resultkey].length = 0;
        $scope.resultsSelected = 0;
        $scope[resultkey] = data.map( function( res ){
          res.htmltext = $sce.trustAsHtml(highlight( res.display_name, $scope.search ));
          res.icon = 'unchecked';
          return res;
        });
      }
      else {
        $scope[resultkey] = [];
      }
      $scope.button.class = not_found.class;
      $scope.button.text  = not_found_in_nominatum;
    }).error(function (data, status, headers, config) {
      $scope[resultkey] = [];
      $scope.button.class = not_found.class;
      $scope.button.text  = not_found_in_nominatum;
    });
  }
  $scope.selectResult = function( result, changeQuery ){
    if (result.icon === 'unchecked') {
      $scope.resultsSelected++;
      result.icon = 'check';
    } else {
      $scope.resultsSelected--;
      result.icon = 'unchecked';
    }
    $scope.button.class = $scope.resultsSelected > 0 ? found.class : not_found.class;
    $scope.button.text  = $scope.resultsSelected > 0 ? found.text : not_found.text;
  }

  $rootScope.$on( 'hideall', function( ev ){
    $scope.searchresults = []
  });

  $rootScope.$on( 'hidesearch', function( ev ){
    $scope.searchresults = [];
  });

  $scope.keyPressed = function(ev) {
    if (ev.which == 13) {
      $scope.fullTextSearch();
    }
  }

  $scope.onFocus = function(ev) {
    // $("#searchresults").removeClass("smaller");
  }

  $scope.onBlur = function(ev) {
    // $("#searchresults").addClass("smaller");
  }

  $scope.fullTextSearch = function(){
    var url = $scope.searchType.toLowerCase() === 'fine' ? '/search' : '/search/coarse';
    getResults(url, 'searchresults');
  }

  var markers = [];
  var remove_markers = function(){
    for (i=0; i<markers.length; i++) {
      $scope.map.removeLayer(markers[i]);
    }
    markers = [];
  };

  var add_marker = function(geo, text) {
    var marker;

    if (typeof text == 'string') {
      marker = new L.marker(geo).bindPopup(text);
    } else if (typeof text == 'object') {
      var full_text = '';
      for (key in text){
        full_text += ('' + key + ': ' + text[key] + '
');
      }
      marker = new L.marker(geo).bindPopup(full_text);
    }

    $scope.map.addLayer(marker);
    markers.push(marker);
    marker.openPopup();
  };

  $scope.showMap = function(result) {
    $scope.map_class = '';
    remove_markers();

    if (result.geometry) {
      var geo = [result.geometry.coordinates[1],result.geometry.coordinates[0]];
      $scope.map.setView(geo, default_zoom);
      add_marker(geo, result.properties);
    } else {
      var geo = [result.lat,result.lon];
      $scope.map.setView(geo, default_zoom);
      add_marker(geo, result.display_name);
    }
  };

  $scope.giveFeedback = function(button_class) {
    var success = button_class === found.class;

    if ($scope.attempt === 0) {
      var searchresults = $scope.searchresults.map(function(res) {
        return {
          type: res.type,
          geometry: res.geometry,
          properties: res.properties,
          icon: res.icon
        }
      });
      $scope.log = {
        query: $scope.search,
        found: success,
        results: searchresults
      };

      $scope.log.foundInPelias = success;
      if (!success) {
        //call nominatum
        $scope.button.class = found.class;
        $scope.button.text  = calling_nominatum;
        getResultsFromNominatum();
      }
    } else {
      // logging nominatum
      var searchresults = $scope.searchresults;
      $scope.log.found = success;
      $scope.log.nominatum_results = searchresults;
    }

    $scope.attempt++;

    if (success) {
      $scope.log.selected = searchresults.filter(function(res){
        return res.icon === 'check';
      });
    }

    if (success || $scope.attempt===2) {
      // upload logs
      $http({
        url: $scope.feedback_url + 'upload',
        method: 'POST',
        params: {'log': $scope.log},
        headers: { 'Accept': 'application/json' }
      }).success(function (data, status, headers, config) {
        $scope.button.class = found.class;
        $scope.button.text  = uploading_feedback;
        resetScope();
      }).error(function (data, status, headers, config) {
        console.log(data);
        resetScope();
      });

      var resetScope = function() {
        // reset
        $scope.search = '';
        $scope.searchresults = [];
        $scope.resultsSelected = 0;
        $scope.button = {
          class: 'hidden',
          text: ''
        }
        $scope.log={};
        $scope.attempt =0;
        $scope.map_class='initial_state';
      }
    }
  }

})
<|endoftext|>


<commit_before>'use strict';

/*
 * Client entrypoint.
 *
 * This script contains all code necessary to bootstrap Tanura in a client.
 */

/**
 * Information about Nuve.
 */
tanura.nuve = {
    url: tanura.url + 'nuve/',
    room: null
};

/**
 * Information about Erizo.
 */
tanura.erizo = {
    localStream: null
};

/**
 * Information about the whiteboard.
 */
tanura.whiteboard = {
    url: tanura.url + 'whiteboard/',
    canvas: null
};

/**
 * Tanura init routine.
 */
tanura.run = function() {

    /**
     * Fake resize indicator.  Because of CSS bugs and limitations, Tanura will
     * sometimes have to change layout parameters manually in Js. As this
     * happens after the resize, a second resize event may be triggered to give
     * other Js code the ability to react to changes Tanura has made to the
     * layout. In this case, this variable will be set to true, to tell Tanura,
     * that the resize event was a fake resize event triggered by Tanura's own
     * code and should be ignored.
     */
    var fakeResize = false;

    /**
     * Options that should be used to stream.
     */
    var streamOpts = {
        audio: !! tanura.options.audio,
        video: !! tanura.options.video,
        data: true,
        screen: false,
    };

    /**
     * The stream options Tanura will fall back to.  These options will be used
     * when establishing a stream with the default options fails. This is
     * usually due to the user not granting the necessary permissions, the
     * browser not supporting all necessary features, or is blocking some of
     * them due to security concerns.
     */
    var fallbackStreamOpts = {
        audio: false,
        video: false,
        data: true,
        screen: false,
    };

    /**
     * This will initialize the whiteboard on the canvas from a given snapshot.
     */
    var mkCanvas = (_) => {
        tanura.whiteboard.canvas = LC.init(
                document.getElementById('whiteboard'),
                {snapshot: _});
        tanura.whiteboard.canvas.setTool(
            new LC.tools.Pencil(tanura.whiteboard.canvas));
        tanura.whiteboard.canvas.on(
            'drawEnd', () => tanura.erizo.localStream.sendData({
                type: 'canvas-draw',
                data: tanura.whiteboard.canvas.getSnapshot()
            }));
    }

    var body = document.getElementsByTagName('body')[0];

    // Manually calculate the size of some elements to work around flexbox
    // issues and limitations.
    var f = () => {
        if (!fakeResize) {

            // Wait for transitions.
            setTimeout(() => {
                // Fire the resize-event.
                tanura.eventHandler.fire('client_resized', document);

                // Pass another resize for Literallycanvas.
                fakeResize = true;
                dispatchEvent(new Event('resize'));
            }, 200);
        } else {
            fakeResize = false;
        }
    }
    tanura.throttle('resize', 'throttledResize');
    window.addEventListener('throttledResize', f);
    f();

    // Connect to Tanura.
    var connect = () => {
        // Wait for Erizo to load.
        if (typeof Erizo === 'undefined' || Erizo == null) {
            setTimeout(connect, 100);
            return;
        }

        // Prepare a request for a room token.
        var req = new XMLHttpRequest();
        req.addEventListener('load', function() {
            var token = this.responseText;
            tanura.log(token);
            tanura.nuve.room = Erizo.Room({token: token});
            var join = function() {
                // Add a single stream to the DOM.
                var addStream = function(_, o) {
                    if (_.hasVideo()) {
                        var e = document.createElement('div');
                        e.setAttribute('id', 'videoEntry_' + _.getID());
                        document.getElementById('people').appendChild(e);
                        _.show('videoEntry_' + _.getID(), o);
                    }
                };

                // Subscribe to a list of streams.
                var subscribeToStreams = function(l) {
                    for (var i in l) {
                        tanura.nuve.room.subscribe(l[i]);
                        l[i].addEventListener(
                                    'bandwidth-alert',
                                    function(_) {
                                        tanura.log(
                                                'Bandwidth Alert',
                                                _.msg,
                                                _.bandwidth);
                                    });
                        l[i].addEventListener('stream-data', (_) => {
                            switch(_.msg.type) {
                                case 'canvas-clear':
                                    tanura.whiteboard.canvas.clear();
                                    tanura.log('Cleared the whiteboard.');
                                    break;
                                case 'canvas-draw':
                                    tanura
                                        .whiteboard
                                        .canvas
                                        .loadSnapshot(_.msg.data);
                                    tanura.log('Loaded a whiteboard change.');
                                    break;
                                case 'canvas-init':
                                    if (!tanura.whiteboard.canvas) {
                                        mkCanvas(_.msg.data);
                                    }
                                    tanura.log(
                                            'Created canvas from existing '
                                            + 'snapshot.');
                                    break;
                                default:
                                    tanura.eventHandler.fire(
                                            'data_received', _.msg.data);
                            }
                        });
                    }
                };

                // This will run as soon as signalling is fully initialized.
                tanura.nuve.room.addEventListener(
                    'room-connected', function(_) {
                        // If we are the only one in the room, add a fresh
                        // whiteboard.
                        if (_.streams.length == 0) {
                            mkCanvas();
                            tanura.log('Created new canvas.');
                        }

                        // Publish the local stream.
                        tanura.nuve.room.publish(
                            tanura.erizo.localStream, {maxVideoBW: 300});
                        subscribeToStreams(_.streams);

                        // Init done, run callback.
                        tanura.eventHandler.fire('client_initialized', document);
                    });

                // This will run whenever the client was successfully subscribed
                // to a new stream.
                tanura.nuve.room.addEventListener(
                        'stream-subscribed',
                        function(_) { addStream(_.stream); });

                // This will run whenever a new stream was added to the room.
                tanura.nuve.room.addEventListener(
                    'stream-added', function(_) {
                        // Attach to the new stream.
                        subscribeToStreams([_.stream]);

                        // If the new stream isn't our own stream.
                        if (
                            tanura.erizo.localStream.getID() != _.stream.getID()
                        ) {
                            // Send the newcomer the current state of the
                            // whiteboard.  This is wasteful as the new client
                            // will get the state by each other client, but
                            // I don't know a better way to do it.  The way
                            // forward will likely be to have the server control
                            // the whiteboard.
                            tanura.erizo.localStream.sendData({
                                type: 'canvas-init',
                                data: tanura.whiteboard.canvas.getSnapshot()
                            });
                        }
                    });

                // This will run whenever a stream disappeared from the room.
                tanura.nuve.room.addEventListener(
                    'stream-removed', function(_) {
                        document
                            .getElementById('videoEntry_' + _.stream.getID())
                            .remove();
                    });

                // This will run if opening the stream has failed.
                tanura.nuve.room.addEventListener('stream-failed', function(_) {
                        // FIXME This needs error handling.
                        tanura.log('Stream Failed... uh-oh');
                    });

                // All set. Connect to the room.
                tanura.nuve.room.connect();

                // Don't attach to the local stream. For development purposes it
                // is nicer if the users own stream is attached remotely too.
                //addStream(tanura.erizo.localStream, {speaker: false});
            }

            // Get local media.
            tanura.erizo.localStream = Erizo.Stream(streamOpts);
            tanura
                .erizo
                .localStream
                .addEventListener('access-accepted', function(_) { join(); });
            tanura
                .erizo
                .localStream
                .addEventListener('access-denied', function(_) {
                    tanura.erizo.localStream.close();
                    tanura.erizo.localStream = Erizo.Stream(fallbackStreamOpts);
                    tanura
                        .erizo
                        .localStream
                        .addEventListener('access-accepted', function(_) {
                            tanura.eventHandler.fire(
                                    'fallbackmedia_opened', fallbackStreamOpts);
                            join();
                        });
                    tanura
                        .erizo
                        .localStream
                        .addEventListener('access-denied', function(_) {
                            tanura.log('Stream creation failed.');
                        });
                    tanura.erizo.localStream.init();
                });
            tanura.erizo.localStream.init();
        });
        req.open('POST', tanura.nuve.url + 'createToken/', true);
        req.setRequestHeader('Content-Type', 'application/json');

        // Send the room-token request.
        req.send(JSON.stringify({username: 'user', role: 'presenter'}));
    }

    connect();
}

// Run, if initialisation is done already.
if (tanura.options) { tanura.run(); }
<commit_msg>Fire tanura.eventHandler.events.fallbackmedia_failed[].<commit_after>'use strict';

/*
 * Client entrypoint.
 *
 * This script contains all code necessary to bootstrap Tanura in a client.
 */

/**
 * Information about Nuve.
 */
tanura.nuve = {
    url: tanura.url + 'nuve/',
    room: null
};

/**
 * Information about Erizo.
 */
tanura.erizo = {
    localStream: null
};

/**
 * Information about the whiteboard.
 */
tanura.whiteboard = {
    url: tanura.url + 'whiteboard/',
    canvas: null
};

/**
 * Tanura init routine.
 */
tanura.run = function() {

    /**
     * Fake resize indicator.  Because of CSS bugs and limitations, Tanura will
     * sometimes have to change layout parameters manually in Js. As this
     * happens after the resize, a second resize event may be triggered to give
     * other Js code the ability to react to changes Tanura has made to the
     * layout. In this case, this variable will be set to true, to tell Tanura,
     * that the resize event was a fake resize event triggered by Tanura's own
     * code and should be ignored.
     */
    var fakeResize = false;

    /**
     * Options that should be used to stream.
     */
    var streamOpts = {
        audio: !! tanura.options.audio,
        video: !! tanura.options.video,
        data: true,
        screen: false,
    };

    /**
     * The stream options Tanura will fall back to.  These options will be used
     * when establishing a stream with the default options fails. This is
     * usually due to the user not granting the necessary permissions, the
     * browser not supporting all necessary features, or is blocking some of
     * them due to security concerns.
     */
    var fallbackStreamOpts = {
        audio: false,
        video: false,
        data: true,
        screen: false,
    };

    /**
     * This will initialize the whiteboard on the canvas from a given snapshot.
     */
    var mkCanvas = (_) => {
        tanura.whiteboard.canvas = LC.init(
                document.getElementById('whiteboard'),
                {snapshot: _});
        tanura.whiteboard.canvas.setTool(
            new LC.tools.Pencil(tanura.whiteboard.canvas));
        tanura.whiteboard.canvas.on(
            'drawEnd', () => tanura.erizo.localStream.sendData({
                type: 'canvas-draw',
                data: tanura.whiteboard.canvas.getSnapshot()
            }));
    }

    var body = document.getElementsByTagName('body')[0];

    // Manually calculate the size of some elements to work around flexbox
    // issues and limitations.
    var f = () => {
        if (!fakeResize) {

            // Wait for transitions.
            setTimeout(() => {
                // Fire the resize-event.
                tanura.eventHandler.fire('client_resized', document);

                // Pass another resize for Literallycanvas.
                fakeResize = true;
                dispatchEvent(new Event('resize'));
            }, 200);
        } else {
            fakeResize = false;
        }
    }
    tanura.throttle('resize', 'throttledResize');
    window.addEventListener('throttledResize', f);
    f();

    // Connect to Tanura.
    var connect = () => {
        // Wait for Erizo to load.
        if (typeof Erizo === 'undefined' || Erizo == null) {
            setTimeout(connect, 100);
            return;
        }

        // Prepare a request for a room token.
        var req = new XMLHttpRequest();
        req.addEventListener('load', function() {
            var token = this.responseText;
            tanura.log(token);
            tanura.nuve.room = Erizo.Room({token: token});
            var join = function() {
                // Add a single stream to the DOM.
                var addStream = function(_, o) {
                    if (_.hasVideo()) {
                        var e = document.createElement('div');
                        e.setAttribute('id', 'videoEntry_' + _.getID());
                        document.getElementById('people').appendChild(e);
                        _.show('videoEntry_' + _.getID(), o);
                    }
                };

                // Subscribe to a list of streams.
                var subscribeToStreams = function(l) {
                    for (var i in l) {
                        tanura.nuve.room.subscribe(l[i]);
                        l[i].addEventListener(
                                    'bandwidth-alert',
                                    function(_) {
                                        tanura.log(
                                                'Bandwidth Alert',
                                                _.msg,
                                                _.bandwidth);
                                    });
                        l[i].addEventListener('stream-data', (_) => {
                            switch(_.msg.type) {
                                case 'canvas-clear':
                                    tanura.whiteboard.canvas.clear();
                                    tanura.log('Cleared the whiteboard.');
                                    break;
                                case 'canvas-draw':
                                    tanura
                                        .whiteboard
                                        .canvas
                                        .loadSnapshot(_.msg.data);
                                    tanura.log('Loaded a whiteboard change.');
                                    break;
                                case 'canvas-init':
                                    if (!tanura.whiteboard.canvas) {
                                        mkCanvas(_.msg.data);
                                    }
                                    tanura.log(
                                            'Created canvas from existing '
                                            + 'snapshot.');
                                    break;
                                default:
                                    tanura.eventHandler.fire(
                                            'data_received', _.msg.data);
                            }
                        });
                    }
                };

                // This will run as soon as signalling is fully initialized.
                tanura.nuve.room.addEventListener(
                    'room-connected', function(_) {
                        // If we are the only one in the room, add a fresh
                        // whiteboard.
                        if (_.streams.length == 0) {
                            mkCanvas();
                            tanura.log('Created new canvas.');
                        }

                        // Publish the local stream.
                        tanura.nuve.room.publish(
                            tanura.erizo.localStream, {maxVideoBW: 300});
                        subscribeToStreams(_.streams);

                        // Init done, run callback.
                        tanura.eventHandler.fire('client_initialized', document);
                    });

                // This will run whenever the client was successfully subscribed
                // to a new stream.
                tanura.nuve.room.addEventListener(
                        'stream-subscribed',
                        function(_) { addStream(_.stream); });

                // This will run whenever a new stream was added to the room.
                tanura.nuve.room.addEventListener(
                    'stream-added', function(_) {
                        // Attach to the new stream.
                        subscribeToStreams([_.stream]);

                        // If the new stream isn't our own stream.
                        if (
                            tanura.erizo.localStream.getID() != _.stream.getID()
                        ) {
                            // Send the newcomer the current state of the
                            // whiteboard.  This is wasteful as the new client
                            // will get the state by each other client, but
                            // I don't know a better way to do it.  The way
                            // forward will likely be to have the server control
                            // the whiteboard.
                            tanura.erizo.localStream.sendData({
                                type: 'canvas-init',
                                data: tanura.whiteboard.canvas.getSnapshot()
                            });
                        }
                    });

                // This will run whenever a stream disappeared from the room.
                tanura.nuve.room.addEventListener(
                    'stream-removed', function(_) {
                        document
                            .getElementById('videoEntry_' + _.stream.getID())
                            .remove();
                    });

                // This will run if opening the stream has failed.
                tanura.nuve.room.addEventListener('stream-failed', function(_) {
                        // FIXME This needs error handling.
                        tanura.log('Stream Failed... uh-oh');
                    });

                // All set. Connect to the room.
                tanura.nuve.room.connect();

                // Don't attach to the local stream. For development purposes it
                // is nicer if the users own stream is attached remotely too.
                //addStream(tanura.erizo.localStream, {speaker: false});
            }

            // Get local media.
            tanura.erizo.localStream = Erizo.Stream(streamOpts);
            tanura
                .erizo
                .localStream
                .addEventListener('access-accepted', function(_) { join(); });
            tanura
                .erizo
                .localStream
                .addEventListener('access-denied', function(_) {
                    tanura.erizo.localStream.close();
                    tanura.erizo.localStream = Erizo.Stream(fallbackStreamOpts);
                    tanura
                        .erizo
                        .localStream
                        .addEventListener('access-accepted', function(_) {
                            tanura.eventHandler.fire(
                                    'fallbackmedia_opened', fallbackStreamOpts);
                            join();
                        });
                    tanura
                        .erizo
                        .localStream
                        .addEventListener('access-denied', function(_) {
                            tanura.eventHandler.fire(
                                    'fallbackmedia_failed', fallbackStreamOpts);
                        });
                    tanura.erizo.localStream.init();
                });
            tanura.erizo.localStream.init();
        });
        req.open('POST', tanura.nuve.url + 'createToken/', true);
        req.setRequestHeader('Content-Type', 'application/json');

        // Send the room-token request.
        req.send(JSON.stringify({username: 'user', role: 'presenter'}));
    }

    connect();
}

// Run, if initialisation is done already.
if (tanura.options) { tanura.run(); }
<|endoftext|>


<commit_before>// @flow
import { call, put } from 'redux-saga/effects';
import { takeEvery } from 'redux-saga';
import { fetchWeatherSuccess, fetchWeatherFail } from './../actions/weather';
import actionTypes from './../actions';
import axios from 'axios';
import type WeatherStateType from './../reducers/weather';

const weatherApiUrl = (location: string) => (
  `https://query.yahooapis.com/v1/public/yql?q=select%20item.condition.text%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D"${location}")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys`
);

function* fetchWeather({location}: {location: string}) {
  try {
    const {data: {query: {results: {channel: {item: {condition: { text }}}}}}} = yield axios.get(weatherApiUrl(location));
    yield put(fetchWeatherSuccess(text));
  } catch (error) {
    yield put(fetchWeatherFail(error.message));
  }
}

function* weatherSaga(): Generator<> {
  yield takeEvery(actionTypes.WEATHER_FETCH_START, fetchWeather);
}

export default weatherSaga;
<commit_msg>Update weather.js<commit_after>// @flow
import { call, put } from 'redux-saga/effects';
import { takeEvery } from 'redux-saga';
import { fetchWeatherSuccess, fetchWeatherFail } from './../actions/weather';
import actionTypes from './../actions';
import axios from 'axios';

const weatherApiUrl = (location: string) => (
  `https://query.yahooapis.com/v1/public/yql?q=select%20item.condition.text%20from%20weather.forecast%20where%20woeid%20in%20(select%20woeid%20from%20geo.places(1)%20where%20text%3D"${location}")&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys`
);

function* fetchWeather({location}: {location: string}) {
  try {
    const {data: {query: {results: {channel: {item: {condition: { text }}}}}}} = yield axios.get(weatherApiUrl(location));
    yield put(fetchWeatherSuccess(text));
  } catch (error) {
    yield put(fetchWeatherFail(error.message));
  }
}

function* weatherSaga(): Generator<> {
  yield takeEvery(actionTypes.WEATHER_FETCH_START, fetchWeather);
}

export default weatherSaga;
<|endoftext|>


<commit_before>$(function() {
  var cookieName = '_wheelmap_splash_seen';

  if(!$.cookie(cookieName)) {
    wwidth = $(window).width();
    left = (0.5 - 300/wwidth) * 100 + '%';

    $.blockUI({
      message: $("#splash"),
      css: {
              top: '25%',
              left: left,
              width: '600px'
           }
    });

    $("#splash .unblock-splash").click($.unblockUI)

    $('.blockOverlay').css('cursor', 'auto').click(function() {
      $.unblockUI();
      $.cookie(cookieName, true)
    });
  }

})<commit_msg>Set cookie also if "What is.." is clicked.<commit_after>$(function() {
  var cookieName = '_wheelmap_splash_seen';

  if(!$.cookie(cookieName)) {
    width = 600; // splash width

    // calculate left edge so it is centered
    left = (0.5 - (width / 2)/($(window).width())) * 100 + '%';

    $.blockUI({
      message: $("#splash"),
      css: {
              top: '25%',
              left: left,
              width: width + 'px'
           }
    });

    var clickHandler = function() {
      $.unblockUI();
      $.cookie(cookieName, true);
      return false;
    };

    $("#splash .unblock-splash").click(clickHandler);
    $('.blockOverlay').css('cursor', 'auto').click(clickHandler);

    $('a.whatis').click(function() {
      $.cookie(cookieName, true);
      return true;
    });

  }

})<|endoftext|>


<commit_before>var Activity = Backbone.Model.extend({

    // From activity-streams-mongoose/lib/activityMongoose.js
    defaults: {
        verb: 'post',
        object: null, //ActivityObject
        actor: null, //ActivityObject
        url: '',
        title: '',
        content: '',
        icon: null, // MediaLinkHash
        target: null, //ActivityObject
        published: Date.now,
        updated: Date.now,
        inReplyTo: null, //Activity
        provider: null, //ActivityObject
        generator: null, //ActivityObject
        streams: ['firehose'],
        likes: {},
        likes_count: 0,
        comments: [],
        comments_count: 0
    }
});
var ActivityList = Backbone.Collection.extend({
	model: Activity,
    url : "/activities"
});

var ActivityObject = Backbone.Model.extend({
    defaults : {
        image: null, // MediaLinkHash
        icon: null, // MediaLinkHash
        displayName: '',
        summary: '',
        content: '',
        url: '',
        author: null, //ActivityObject
        published: Date.now,
        objectType: '',
        attachments: [], //ActivityObject
        upstreamDuplicates: [], //string
        downstreamDuplicates: [], //string
        updated: Date.now
    }

});

var ActivityObjectType = Backbone.Model.extend({});

var ActivityObjectTypeList = Backbone.Collection.extend({
	model : ActivityObjectType,
	url : "/objectTypes"
});

var ActivityVerb = Backbone.Model.extend({});
var ActivityVerbList = Backbone.Collection.extend({
	model : ActivityVerb,
	url : "/verbs"
});<commit_msg>Add user friendly date<commit_after>var Activity = Backbone.Model.extend({

    // From activity-streams-mongoose/lib/activityMongoose.js
    defaults: {
        verb: 'post',
        object: null, //ActivityObject
        actor: null, //ActivityObject
        url: '',
        title: '',
        content: '',
        icon: null, // MediaLinkHash
        target: null, //ActivityObject
        published: Date.now,
        updated: Date.now,
        inReplyTo: null, //Activity
        provider: null, //ActivityObject
        generator: null, //ActivityObject
        streams: ['firehose'],
        likes: {},
        likes_count: 0,
        comments: [],
        comments_count: 0,
        userFriendlyDate: 'No idea when'
    }
});
var ActivityList = Backbone.Collection.extend({
	model: Activity,
    url : "/activities"
});

var ActivityObject = Backbone.Model.extend({
    defaults : {
        image: null, // MediaLinkHash
        icon: null, // MediaLinkHash
        displayName: '',
        summary: '',
        content: '',
        url: '',
        author: null, //ActivityObject
        published: Date.now,
        objectType: '',
        attachments: [], //ActivityObject
        upstreamDuplicates: [], //string
        downstreamDuplicates: [], //string
        updated: Date.now
    }

});

var ActivityObjectType = Backbone.Model.extend({});

var ActivityObjectTypeList = Backbone.Collection.extend({
	model : ActivityObjectType,
	url : "/objectTypes"
});

var ActivityVerb = Backbone.Model.extend({});
var ActivityVerbList = Backbone.Collection.extend({
	model : ActivityVerb,
	url : "/verbs"
});

var User = Backbone.Model.extend({
    defaults : {
        signedIn : false,
        displayName : 'User'
    }
});<|endoftext|>


<commit_before>$(document).ready(function () {
    loadMainCategory('category_parent_id');
    ajaxIndex();
});

function ajaxIndex() {
    var get_url = '/person/finance-payment/ajax-index';
    var get_data = $.param($('#formSearch').serializeArray());
    var method = 'get';
    var success_function = function (result) {
        $('#tbl tbody').empty();
        for (var i = 0, len = result.data.length; i < len; i++) {
            $('#tbl tbody').append(
                $('<tr>')
                    .append($('<td>').text(result.start + i + 1))
                    .append($('<td>').text(result.data[i]['fp_payment_date']))
                    .append($('<td>').text(result.data[i]['fp_payment']))
                    .append($('<td>').text(result.data[i]['category']))
                    .append($('<td>').text(result.data[i]['fp_detail']))
                    .append($('<td>').text(result.data[i]['fp_update_time']))
                    .append($('<td>')
                        .append($('<a>', {href: '#', id: 'modify_' + result.data[i]['fp_id'], text: '修改'})
                            .click(function () {
                                modifyBadHistory(this.id);
                            })
                        )
                        .append('  ')
                        .append($('<a>', {href: '#', id: 'delete_' + result.data[i]['fp_id'], text: '删除'})
                            .click(function () {
                                deleteBadHistory(this.id);
                            })
                        )
                    )
            );
        }
        if (result.total == 0) {
            $('#tbl tbody').append($('<tr>')
                .append(
                    $('<td>').text('对不起,没有符合条件的数据').addClass('bill_table_no_data').attr('colspan', 7)
                )
            );
        }
        //init pagination
        initPagination(result.total_pages, result.current_page);
    };
    callAjaxWithFunction(get_url, get_data, success_function, method);
}
/*  --------------------------------------------------------------------------------------------------------  */
var g_selectpicker = $('#finance_payment_fc_id').selectpicker();

$('#btn_add').on('click', function () {
    var get_url = '/person/finance-category/get-finance-main-category';
    var get_data = {

    };
    var method = 'get';
    var success_function = function (result) {
        $('#finance_payment_fc_id').empty();
        for (var fc_id in result) {
            $('#finance_payment_fc_id').append($('<option>', {
                value: fc_id,
                text: result[fc_id]
            }));
        }

        window.FinancePaymentForm.reset();
        $('#finance_payment_payment_date').val(getCurrentDate());
        g_selectpicker.selectpicker('refresh');
        g_selectpicker.selectpicker('val', $("#finance_payment_fc_id option:first").val());
        $('#finance_payment_fp_id').val('');
        $('#btn_submit_finance_payment').attr('disabled', false);
        $('#FinancePaymentModal').modal('show');
    };
    callAjaxWithFunction(get_url, get_data, success_function, method);
});

$('#FinancePaymentForm').on('submit', (function (event) {
    event.preventDefault();

    var fp_id = $('#finance_payment_fp_id').val();
    var type = (fp_id == '') ? 'add' : 'modify';
    var error_num = validInput(type);
    if (error_num == 0) {
        $('#btn_submit_finance_payment').attr('disabled', true);
        var post_url = '/person/finance-payment/' + type + '-finance-payment';
        var post_data = new FormData(this);
        var msg_success = (fp_id == '') ? MESSAGE_ADD_SUCCESS : MESSAGE_MODIFY_SUCCESS;
        var msg_error = (fp_id == '') ? MESSAGE_ADD_ERROR : MESSAGE_MODIFY_ERROR;
        var method = 'post';
        var success_function = function (result) {
            $('#FinancePaymentModal').modal('hide');
            if (parseInt(result) != 0) {
                alert(msg_success);
            } else {
                alert(msg_error);
            }
            ajaxIndex();
        };
        callAjaxWithFormAndFunction(post_url, post_data, success_function, method);
    }
}));

function modifyBadHistory(modify_id) {
    var fp_id = modify_id.substr('modify_'.length);
    var post_url = '/person/finance-payment/get-finance-payment';
    var post_data = {
        'fp_id': fp_id
    };
    var method = 'get';
    var success_function = function (result) {
        $('#finance_payment_payment_date').val(result.fp_payment_date);
        $('#finance_payment_payment').val(result.fp_payment);
        g_selectpicker.selectpicker('val', result.fc_ids);
        $('#finance_payment_intro').val(result.fp_detail);
        $('#finance_payment_fp_id').val(result.fp_id);
        $('#btn_submit_finance_payment').attr('disabled', false);
        $('#FinancePaymentModal').modal('show');
    };
    callAjaxWithFunction(post_url, post_data, success_function, method);
}

function deleteBadHistory(delete_id) {
    if (confirm(MESSAGE_DELETE_CONFIRM)) {
        var fp_id = delete_id.substr('delete_'.length);
        var post_url = '/person/finance-payment/delete-finance-payment';
        var post_data = {
            'fp_id': fp_id
        };
        var method = 'post';
        var success_function = function (result) {
            if (parseInt(result) > 0) {
                alert(MESSAGE_DELETE_SUCCESS);
            } else {
                alert(MESSAGE_DELETE_ERROR);
            }
            ajaxIndex();
        };
        callAjaxWithFunction(post_url, post_data, success_function, method);
    }
}

function validInput(type) {
    var error_num = 0;
    var payment_date = $.trim($('#finance_payment_payment_date').val());
    var payment = $.trim($('#finance_payment_payment').val());
    if (payment_date == '') {
        error_num = error_num + 1;
        alert(MESSAGE_DATE_ERROR);
    } else if (payment === '') {
        error_num = error_num + 1;
        alert(MESSAGE_MONEY_FORMAT_EMPTY_ERROR);
    }

    return error_num;
}<commit_msg>+ rename js method in finance payment<commit_after>$(document).ready(function () {
    loadMainCategory('category_parent_id');
    ajaxIndex();
});

function ajaxIndex() {
    var get_url = '/person/finance-payment/ajax-index';
    var get_data = $.param($('#formSearch').serializeArray());
    var method = 'get';
    var success_function = function (result) {
        $('#tbl tbody').empty();
        for (var i = 0, len = result.data.length; i < len; i++) {
            $('#tbl tbody').append(
                $('<tr>')
                    .append($('<td>').text(result.start + i + 1))
                    .append($('<td>').text(result.data[i]['fp_payment_date']))
                    .append($('<td>').text(result.data[i]['fp_payment']))
                    .append($('<td>').text(result.data[i]['category']))
                    .append($('<td>').text(result.data[i]['fp_detail']))
                    .append($('<td>').text(result.data[i]['fp_update_time']))
                    .append($('<td>')
                        .append($('<a>', {href: '#', id: 'modify_' + result.data[i]['fp_id'], text: '修改'})
                            .click(function () {
                                modifyFinancePayment(this.id);
                            })
                        )
                        .append('  ')
                        .append($('<a>', {href: '#', id: 'delete_' + result.data[i]['fp_id'], text: '删除'})
                            .click(function () {
                                deleteFinancePayment(this.id);
                            })
                        )
                    )
            );
        }
        if (result.total == 0) {
            $('#tbl tbody').append($('<tr>')
                .append(
                    $('<td>').text('对不起,没有符合条件的数据').addClass('bill_table_no_data').attr('colspan', 7)
                )
            );
        }
        //init pagination
        initPagination(result.total_pages, result.current_page);
    };
    callAjaxWithFunction(get_url, get_data, success_function, method);
}
/*  --------------------------------------------------------------------------------------------------------  */
var g_selectpicker = $('#finance_payment_fc_id').selectpicker();

$('#btn_add').on('click', function () {
    var get_url = '/person/finance-category/get-finance-main-category';
    var get_data = {

    };
    var method = 'get';
    var success_function = function (result) {
        $('#finance_payment_fc_id').empty();
        for (var fc_id in result) {
            $('#finance_payment_fc_id').append($('<option>', {
                value: fc_id,
                text: result[fc_id]
            }));
        }

        window.FinancePaymentForm.reset();
        $('#finance_payment_payment_date').val(getCurrentDate());
        g_selectpicker.selectpicker('refresh');
        g_selectpicker.selectpicker('val', $("#finance_payment_fc_id option:first").val());
        $('#finance_payment_fp_id').val('');
        $('#btn_submit_finance_payment').attr('disabled', false);
        $('#FinancePaymentModal').modal('show');
    };
    callAjaxWithFunction(get_url, get_data, success_function, method);
});

$('#FinancePaymentForm').on('submit', (function (event) {
    event.preventDefault();

    var fp_id = $('#finance_payment_fp_id').val();
    var type = (fp_id == '') ? 'add' : 'modify';
    var error_num = validInput(type);
    if (error_num == 0) {
        $('#btn_submit_finance_payment').attr('disabled', true);
        var post_url = '/person/finance-payment/' + type + '-finance-payment';
        var post_data = new FormData(this);
        var msg_success = (fp_id == '') ? MESSAGE_ADD_SUCCESS : MESSAGE_MODIFY_SUCCESS;
        var msg_error = (fp_id == '') ? MESSAGE_ADD_ERROR : MESSAGE_MODIFY_ERROR;
        var method = 'post';
        var success_function = function (result) {
            $('#FinancePaymentModal').modal('hide');
            if (parseInt(result) != 0) {
                alert(msg_success);
            } else {
                alert(msg_error);
            }
            ajaxIndex();
        };
        callAjaxWithFormAndFunction(post_url, post_data, success_function, method);
    }
}));

function modifyFinancePayment(modify_id) {
    var fp_id = modify_id.substr('modify_'.length);
    var post_url = '/person/finance-payment/get-finance-payment';
    var post_data = {
        'fp_id': fp_id
    };
    var method = 'get';
    var success_function = function (result) {
        $('#finance_payment_payment_date').val(result.fp_payment_date);
        $('#finance_payment_payment').val(result.fp_payment);
        g_selectpicker.selectpicker('val', result.fc_ids);
        $('#finance_payment_intro').val(result.fp_detail);
        $('#finance_payment_fp_id').val(result.fp_id);
        $('#btn_submit_finance_payment').attr('disabled', false);
        $('#FinancePaymentModal').modal('show');
    };
    callAjaxWithFunction(post_url, post_data, success_function, method);
}

function deleteFinancePayment(delete_id) {
    if (confirm(MESSAGE_DELETE_CONFIRM)) {
        var fp_id = delete_id.substr('delete_'.length);
        var post_url = '/person/finance-payment/delete-finance-payment';
        var post_data = {
            'fp_id': fp_id
        };
        var method = 'post';
        var success_function = function (result) {
            if (parseInt(result) > 0) {
                alert(MESSAGE_DELETE_SUCCESS);
            } else {
                alert(MESSAGE_DELETE_ERROR);
            }
            ajaxIndex();
        };
        callAjaxWithFunction(post_url, post_data, success_function, method);
    }
}

function validInput(type) {
    var error_num = 0;
    var payment_date = $.trim($('#finance_payment_payment_date').val());
    var payment = $.trim($('#finance_payment_payment').val());
    if (payment_date == '') {
        error_num = error_num + 1;
        alert(MESSAGE_DATE_ERROR);
    } else if (payment === '') {
        error_num = error_num + 1;
        alert(MESSAGE_MONEY_FORMAT_EMPTY_ERROR);
    }

    return error_num;
}<|endoftext|>