<commit_before>'use strict';

angular.module('semdomtrans.edit', ['jsonRpc', 'ui.bootstrap', 'bellows.services',  'ngAnimate', 'palaso.ui.notice', 'semdomtrans.services', 'palaso.ui.sd.term', 'palaso.ui.sd.questions', 'palaso.ui.scroll', 'palaso.ui.typeahead', 'palaso.ui.sd.ws'])
// DBE controller
.controller('editCtrl', ['$scope', '$state', '$stateParams', 'semdomtransEditService', 'semdomtransEditorDataService', 'sessionService', 'modalService', 'silNoticeService', '$rootScope', '$filter', '$timeout',
function($scope, $state, $stateParams, semdomEditApi, editorDataService, sessionService, modal, notice, $rootScope, $filter, $timeout) {

  $scope.selectedTab = 0;
  $scope.control = $scope;
  $scope.currentQuestionPos = 0;
  $scope.tabDisplay = {"val": '0'};
  $scope.state = "edit";
  $scope.filteredByDepthItems = [];
  $scope.filteredByDepthItemsDict = {};
  $scope.displayedItems = [];
  $scope.selectedDepth = 1;
  $scope.searchText = "";
  $scope.isEditingWorkingSet = false;
  $scope.subDomain = "1";
  $scope.hideTranslated = false;

  var api = semdomEditApi;

  $scope.$watch("subDomain", function(newVal) {
    $scope.reloadItems($scope.selectedDepth);
  });

  $scope.selectSubDomain = function(subDomain) {
    $scope.subDomain = subDomain;
  }

  $scope.reloadItems = function reloadItems(depth, delay) {
     if (delay == undefined) {
       delay = 0;
     }
      var query = $scope.selectedText;
      $timeout(function() {
            if (query != $scope.selectedText)
              return;

            $scope.filteredByDepthItems = [];
            var addedToFiltered = {};

            // get all actually included items in
            for (var i in $scope.itemsTree) {
              var node = $scope.itemsTree[i];
              var item = node.content;
              if (isIncluded(item.key) && item.key[0] == $scope.subDomain) {
                if (checkDepth(item.key)) {
                  $scope.filteredByDepthItems.push(item);
                }
              }
            }

            // apply filter
            $scope.filteredByDepthItems = $filter('filter')($scope.filteredByDepthItems, $scope.searchText);

            // check off that items have been added (to avoid duplicates in next step)
            for (var i in $scope.filteredByDepthItems) {
              var item = $scope.filteredByDepthItems[i];
              addedToFiltered[item.key] = true;
            }

            // add ancestors of included items
            for (var i in $scope.filteredByDepthItems) {
              var node = $scope.itemsTree[$scope.filteredByDepthItems[i].key];
              var item = node.content;
              if (isIncluded(item.key) && item.key[0] == $scope.subDomain) {
                while(node.parent != '') {
                  if (checkDepth(node.parent) && (angular.isUndefined(addedToFiltered[node.parent]) || !addedToFiltered[node.parent])) {
                    $scope.filteredByDepthItems.push($scope.itemsTree[node.parent].content);
                    addedToFiltered[node.parent] = true;
                  }

                  node = $scope.itemsTree[node.parent];
                }
              }
            }

            $scope.filteredByDepthItems.sort(function(a, b) {
              if (a.key < b.key) {
                return -1;
              } else {
                return 1;
              }
            });

            $scope.displayedItems = $scope.filteredByDepthItems;
            if (!$scope.$$phase) {
              $scope.$apply()
            }
          }, delay);
  }

  /*
   * Set items to be included
   */
  $scope.setInclusion = function setInclusion(itemsToInclude, v) {
    for (var i in itemsToInclude) {
      $scope.includedItems[itemsToInclude[i].key] = v;
    }

    $scope.reloadItems($scope.selectedDepth);
  }

  /*
   * Determines if a semdom item is completely translated
   */

  function isItemTranslatedCompletely(item) {
    var translated = true;
    translated = translated && (item.name.status == 4);
    translated = translated && (item.description.status == 4);
    for (var i = 0; i < item.searchKeys.length; i++) {
      translated = translated && (item.searchKeys[i].status == 4);
    }

    for (var i = 0; i < item.questions.length; i++) {
      translated = translated && (item.questions[i].question.status == 4);
      translated = translated && (item.questions[i].terms.status == 4);
    }

    return translated;
  }

  $scope.$watch('selectedDepth', function(newVal, oldVal) {
    if (oldVal != newVal) {
      var depth = newVal;
      $timeout(function() {
        if (depth == $scope.selectedDepth) {
            $scope.reloadItems(newVal);
        }
      }, 500);
    }
  });

  function checkDepth(key) {
    if ((key.length + 1) / 2 <= $scope.selectedDepth) {
      return true;
    }
    return false;
  }

  $scope.setTab = function(val) {
    $scope.selectedTab = val;
  }

  $scope.changeTerm = function(key) {
      $scope.currentQuestionPos = 0;
      for (var i = 0; i < $scope.items.length; i++) {
        if ($scope.items[i].key == key) {
          $scope.currentEntry = $scope.items[i];
          $scope.currentEntryIndex = i;
          break;
        }
      }
      $state.go("editor.editItem", { position: $scope.currentEntryIndex});
    }

  $scope.updateItem = function updateItem(v) {
    // update item if we hit the enter key
    v = (v === undefined) ? 13 : v;
    if (v == 13) {
      api.updateTerm($scope.currentEntry, function(result) {
        ;
      });
    }
  }

  $scope.refreshDbeData = function refreshDbeData(state) {
     return editorDataService.refreshEditorData().then(function(result) {
       editorDataService.processEditorDto(result).then(function(resut) {
         ;
       })
     });
  };

  $scope.$watchCollection('items', function(newVal) {
    if (newVal && newVal.length > 0) {

      // reload all items up to appropriate tre depth
      var maxDepth = 0;
      for (var i in $scope.items) {
        var depth = ($scope.items[i].key.length + 1)/2;
        if (depth > maxDepth) {
          maxDepth = depth;
        }

        $scope.includedItems[$scope.items[i].key] = true;
      }

      $scope.maxDepth = maxDepth;
      $scope.reloadItems(1);

      // reload current entry if it is included in lsit
      if ($scope.includedItems[$scope.items[$stateParams.position].key]) {
        $scope.currentEntry = $scope.items[$stateParams.position];
        $scope.currentEntryIndex = angular.isUndefined($stateParams.position) ? 0 : $stateParams.position;
        $scope.changeTerm($scope.currentEntry.key);
      }

      $scope.currentEntry = $scope.items[$scope.currentEntryIndex];
      $scope.translatedItems = {};
      // find all items that are completely translated
      for (var i = 0; i < $scope.items.length; i++) {
        if (isItemTranslatedCompletely($scope.items[i])) {
          $scope.translatedItems[$scope.items[i].key] = true;
        } else {
          $scope.translatedItems[$scope.items[i].key] = false;
        }
      }
    }
  });

  $scope.$watchCollection('workingSets', function(newVal) {
    if (newVal) {
      if (angular.isUndefined($scope.selectedWorkingSet)) {
        $scope.selectedWorkingSet = 0;
      }
      else {
        loadWorkingSet($scope.workingSets[$scope.selectedWorkingSet]);
      }
    }
  });

  //search typeahead
  $scope.typeahead = {
    term: '',
    searchResults: []
  };

  $scope.typeahead.searchEntries = function searchEntries(query) {
    // if query starts with number, include all items whose key begin with that number
    if (!isNaN(parseInt(query[0]))) {
      $scope.typeahead.searchResults = []
      var results = [];
      var ln = query.length;
      for (var i in $scope.items) {
        if ($scope.items[i].key.substring(0, ln) === query) {
          results.push($scope.items[i]);
        }
      }
      $scope.typeahead.searchResults = results;
    } else {
      $scope.typeahead.searchResults = $filter('filter')($scope.items, query);
    }
  };

  $scope.typeahead.searchSelect = function searchSelect(entry) {

  };

  function isIncluded(key) {
    return !angular.isUndefined($scope.includedItems[key]) && $scope.includedItems[key] ;
  }

  $scope.editWorkingSet = function editWorkingSet(wsID) {
    for (var i = 0; i < $scope.workingSets.length; i++) {
      if ($scope.workingSets[i].id == wsID) {
        $scope.selectedWorkingSet = i;
        $scope.isEditingWorkingSet = true;
        break;
      }
    }
  }

  $scope.cancelEditingWorkingSet = function cancelEditingWorkingSet(wsOriginal) {
    loadWorkingSet($scope.workingSets[$scope.selectedWorkingSet]);
    $scope.isEditingWorkingSet = false;
    if (!angular.isUndefined($scope.newWs)) {
      $scope.newWs = undefined;
    }
  }

  $scope.createNewWorkingSet = function createNewWorkingSet() {

    $scope.newWs = { id: '',  name: '', isShared : false, itemKeys : [] }

    for (var i = 0; i < $scope.items.length; i++) {
      $scope.newWs.itemKeys.push($scope.items[i].key);
    }

    $scope.isEditingWorkingSet = true;
    loadWorkingSet($scope.newWs)
  }

  $scope.$watch("selectedWorkingSet", function(newVal, oldVal) {
    if (oldVal != newVal) {
      loadWorkingSet($scope.workingSets[$scope.selectedWorkingSet]);
    }
  })

  function loadWorkingSet(ws) {
    $scope.includedItems = {};
    for (var i = 0; i < ws.itemKeys.length; i++) {
      $scope.includedItems[ws.itemKeys[i]] = true;
    }

    $scope.reloadItems($scope.selectedDepth);
  }

  $scope.saveWorkingSet = function saveWorkingSet(ws) {
    var ik = [];
    for (var i in $scope.includedItems) {
      if ($scope.includedItems[i]) {
        ik.push(i);
      }
    }

    ws.itemKeys = ik;
    api.updateWorkingSet(ws, function(result) {
      if (result.ok) {

      }
    })
    $scope.isEditingWorkingSet = false;
    $scope.refreshDbeData();

  }

  $scope.isItemSelected = function isItemSelected() {
    return !angular.isUndefined($scope.currentEntryIndex);
  }

}]);
<commit_msg>* Check that $stateParams.position is set before we use it<commit_after>'use strict';

angular.module('semdomtrans.edit', ['jsonRpc', 'ui.bootstrap', 'bellows.services',  'ngAnimate', 'palaso.ui.notice', 'semdomtrans.services', 'palaso.ui.sd.term', 'palaso.ui.sd.questions', 'palaso.ui.scroll', 'palaso.ui.typeahead', 'palaso.ui.sd.ws'])
// DBE controller
.controller('editCtrl', ['$scope', '$state', '$stateParams', 'semdomtransEditService', 'semdomtransEditorDataService', 'sessionService', 'modalService', 'silNoticeService', '$rootScope', '$filter', '$timeout',
function($scope, $state, $stateParams, semdomEditApi, editorDataService, sessionService, modal, notice, $rootScope, $filter, $timeout) {

  $scope.selectedTab = 0;
  $scope.control = $scope;
  $scope.currentQuestionPos = 0;
  $scope.tabDisplay = {"val": '0'};
  $scope.state = "edit";
  $scope.filteredByDepthItems = [];
  $scope.filteredByDepthItemsDict = {};
  $scope.displayedItems = [];
  $scope.selectedDepth = 1;
  $scope.searchText = "";
  $scope.isEditingWorkingSet = false;
  $scope.subDomain = "1";
  $scope.hideTranslated = false;

  var api = semdomEditApi;

  $scope.$watch("subDomain", function(newVal) {
    $scope.reloadItems($scope.selectedDepth);
  });

  $scope.selectSubDomain = function(subDomain) {
    $scope.subDomain = subDomain;
  }

  $scope.reloadItems = function reloadItems(depth, delay) {
     if (delay == undefined) {
       delay = 0;
     }
      var query = $scope.selectedText;
      $timeout(function() {
            if (query != $scope.selectedText)
              return;

            $scope.filteredByDepthItems = [];
            var addedToFiltered = {};

            // get all actually included items in
            for (var i in $scope.itemsTree) {
              var node = $scope.itemsTree[i];
              var item = node.content;
              if (isIncluded(item.key) && item.key[0] == $scope.subDomain) {
                if (checkDepth(item.key)) {
                  $scope.filteredByDepthItems.push(item);
                }
              }
            }

            // apply filter
            $scope.filteredByDepthItems = $filter('filter')($scope.filteredByDepthItems, $scope.searchText);

            // check off that items have been added (to avoid duplicates in next step)
            for (var i in $scope.filteredByDepthItems) {
              var item = $scope.filteredByDepthItems[i];
              addedToFiltered[item.key] = true;
            }

            // add ancestors of included items
            for (var i in $scope.filteredByDepthItems) {
              var node = $scope.itemsTree[$scope.filteredByDepthItems[i].key];
              var item = node.content;
              if (isIncluded(item.key) && item.key[0] == $scope.subDomain) {
                while(node.parent != '') {
                  if (checkDepth(node.parent) && (angular.isUndefined(addedToFiltered[node.parent]) || !addedToFiltered[node.parent])) {
                    $scope.filteredByDepthItems.push($scope.itemsTree[node.parent].content);
                    addedToFiltered[node.parent] = true;
                  }

                  node = $scope.itemsTree[node.parent];
                }
              }
            }

            $scope.filteredByDepthItems.sort(function(a, b) {
              if (a.key < b.key) {
                return -1;
              } else {
                return 1;
              }
            });

            $scope.displayedItems = $scope.filteredByDepthItems;
            if (!$scope.$$phase) {
              $scope.$apply()
            }
          }, delay);
  }

  /*
   * Set items to be included
   */
  $scope.setInclusion = function setInclusion(itemsToInclude, v) {
    for (var i in itemsToInclude) {
      $scope.includedItems[itemsToInclude[i].key] = v;
    }

    $scope.reloadItems($scope.selectedDepth);
  }

  /*
   * Determines if a semdom item is completely translated
   */

  function isItemTranslatedCompletely(item) {
    var translated = true;
    translated = translated && (item.name.status == 4);
    translated = translated && (item.description.status == 4);
    for (var i = 0; i < item.searchKeys.length; i++) {
      translated = translated && (item.searchKeys[i].status == 4);
    }

    for (var i = 0; i < item.questions.length; i++) {
      translated = translated && (item.questions[i].question.status == 4);
      translated = translated && (item.questions[i].terms.status == 4);
    }

    return translated;
  }

  $scope.$watch('selectedDepth', function(newVal, oldVal) {
    if (oldVal != newVal) {
      var depth = newVal;
      $timeout(function() {
        if (depth == $scope.selectedDepth) {
            $scope.reloadItems(newVal);
        }
      }, 500);
    }
  });

  function checkDepth(key) {
    if ((key.length + 1) / 2 <= $scope.selectedDepth) {
      return true;
    }
    return false;
  }

  $scope.setTab = function(val) {
    $scope.selectedTab = val;
  }

  $scope.changeTerm = function(key) {
      $scope.currentQuestionPos = 0;
      for (var i = 0; i < $scope.items.length; i++) {
        if ($scope.items[i].key == key) {
          $scope.currentEntry = $scope.items[i];
          $scope.currentEntryIndex = i;
          break;
        }
      }
      $state.go("editor.editItem", { position: $scope.currentEntryIndex});
    }

  $scope.updateItem = function updateItem(v) {
    // update item if we hit the enter key
    v = (v === undefined) ? 13 : v;
    if (v == 13) {
      api.updateTerm($scope.currentEntry, function(result) {
        ;
      });
    }
  }

  $scope.refreshDbeData = function refreshDbeData(state) {
     return editorDataService.refreshEditorData().then(function(result) {
       editorDataService.processEditorDto(result).then(function(resut) {
         ;
       })
     });
  };

  $scope.$watchCollection('items', function(newVal) {
    if (newVal && newVal.length > 0) {

      // reload all items up to appropriate tre depth
      var maxDepth = 0;
      for (var i in $scope.items) {
        var depth = ($scope.items[i].key.length + 1)/2;
        if (depth > maxDepth) {
          maxDepth = depth;
        }

        $scope.includedItems[$scope.items[i].key] = true;
      }

      $scope.maxDepth = maxDepth;
      $scope.reloadItems(1);

      // reload current entry if it is included in lsit
      if (angular.isUndefined($stateParams.position) != "" && $scope.includedItems[$scope.items[$stateParams.position].key]) {
        $scope.currentEntry = $scope.items[$stateParams.position];
        $scope.currentEntryIndex = angular.isUndefined($stateParams.position) ? 0 : $stateParams.position;
        $scope.changeTerm($scope.currentEntry.key);
      }

      $scope.currentEntry = $scope.items[$scope.currentEntryIndex];
      $scope.translatedItems = {};
      // find all items that are completely translated
      for (var i = 0; i < $scope.items.length; i++) {
        if (isItemTranslatedCompletely($scope.items[i])) {
          $scope.translatedItems[$scope.items[i].key] = true;
        } else {
          $scope.translatedItems[$scope.items[i].key] = false;
        }
      }
    }
  });

  $scope.$watchCollection('workingSets', function(newVal) {
    if (newVal) {
      if (angular.isUndefined($scope.selectedWorkingSet)) {
        $scope.selectedWorkingSet = 0;
      }
      else {
        loadWorkingSet($scope.workingSets[$scope.selectedWorkingSet]);
      }
    }
  });

  //search typeahead
  $scope.typeahead = {
    term: '',
    searchResults: []
  };

  $scope.typeahead.searchEntries = function searchEntries(query) {
    // if query starts with number, include all items whose key begin with that number
    if (!isNaN(parseInt(query[0]))) {
      $scope.typeahead.searchResults = []
      var results = [];
      var ln = query.length;
      for (var i in $scope.items) {
        if ($scope.items[i].key.substring(0, ln) === query) {
          results.push($scope.items[i]);
        }
      }
      $scope.typeahead.searchResults = results;
    } else {
      $scope.typeahead.searchResults = $filter('filter')($scope.items, query);
    }
  };

  $scope.typeahead.searchSelect = function searchSelect(entry) {

  };

  function isIncluded(key) {
    return !angular.isUndefined($scope.includedItems[key]) && $scope.includedItems[key] ;
  }

  $scope.editWorkingSet = function editWorkingSet(wsID) {
    for (var i = 0; i < $scope.workingSets.length; i++) {
      if ($scope.workingSets[i].id == wsID) {
        $scope.selectedWorkingSet = i;
        $scope.isEditingWorkingSet = true;
        break;
      }
    }
  }

  $scope.cancelEditingWorkingSet = function cancelEditingWorkingSet(wsOriginal) {
    loadWorkingSet($scope.workingSets[$scope.selectedWorkingSet]);
    $scope.isEditingWorkingSet = false;
    if (!angular.isUndefined($scope.newWs)) {
      $scope.newWs = undefined;
    }
  }

  $scope.createNewWorkingSet = function createNewWorkingSet() {

    $scope.newWs = { id: '',  name: '', isShared : false, itemKeys : [] }

    for (var i = 0; i < $scope.items.length; i++) {
      $scope.newWs.itemKeys.push($scope.items[i].key);
    }

    $scope.isEditingWorkingSet = true;
    loadWorkingSet($scope.newWs)
  }

  $scope.$watch("selectedWorkingSet", function(newVal, oldVal) {
    if (oldVal != newVal) {
      loadWorkingSet($scope.workingSets[$scope.selectedWorkingSet]);
    }
  })

  function loadWorkingSet(ws) {
    $scope.includedItems = {};
    for (var i = 0; i < ws.itemKeys.length; i++) {
      $scope.includedItems[ws.itemKeys[i]] = true;
    }

    $scope.reloadItems($scope.selectedDepth);
  }

  $scope.saveWorkingSet = function saveWorkingSet(ws) {
    var ik = [];
    for (var i in $scope.includedItems) {
      if ($scope.includedItems[i]) {
        ik.push(i);
      }
    }

    ws.itemKeys = ik;
    api.updateWorkingSet(ws, function(result) {
      if (result.ok) {

      }
    })
    $scope.isEditingWorkingSet = false;
    $scope.refreshDbeData();

  }

  $scope.isItemSelected = function isItemSelected() {
    return !angular.isUndefined($scope.currentEntryIndex);
  }

}]);
<|endoftext|>


<commit_before>// A method that takes the id of a requirement (or award) and returns true if it is complete
// returns false if it is not complete

var masterReqirementArray = [
  {id: "a", doPrereqCount: 1, prereqs: ["b", "c"]},
  {id: "b"},
  {id: "c", doPrereqCount: 2, prereqs: ["d", "e"]},
  {id: "d"},
  {id: "e"}
];

var masterReqById = masterRequirementArray.reduce(function(previous, current) {
  previous[current.id] = current;
}, {});

var completedTest1 = ["d", "e"]; // c can be marked complete
var completedTest2 = ["b", "c"]; // a cant' be marked complete - d and e not complete
var completedTest3 = ["b", "c", "d", "e"]; //a can be marked complete

function isComplete(id, completedReqIds) {
  // returns true if the id is found in the list
  return (completedReqIds.indexOf(id) !== -1);
}

// parameters: requirement id, completedReqIds
// returns: boolean
// Checks to see if the prereqs for the listed id are complete
// Not all prereqs are required, so we count to see if we have done enough of them
function prereqsComplete(reqId, completedReqIds) {
  //check only immediate prereqs
  var req = masterReqById[reqId];
  var prereqsCompleteCount = 0;
  for (var i = 0; i < req.prereqs.length; i++) {
    // increase prereqsCompleteCount by 1 each time we find one that is complete
    if (completedReqIds.indexOf(req.prereqs[i]) !== -1) {
      prereqsCompleteCount++;
    }
  }
  // check to make sure we completed enough prereqs
  var result = (prereqsCompleteCount >= req.numReqPrereqs);
  return result;
}

// Method on the scout object
// parameters: reqId - completed requirement id
// returns: true if successful, false if not successful
// Checks to see if the prereqs for the requirement have already been completed by
// the scout. If they have, adds the requirement to the scout's list of completed
// requirements and returns true. Returns false if not.
function markReqComplete(reqId) {
  if (prereqsComplete(reqId, this.reqsCompleted)) {
    // push a new object onto the reqsCompleted array of the scout
    // should include a reqId and the current date
    var completedReq = {
      reqId: reqId,
      dateCompleted: new Date()
    };
    this.reqsCompleted.push(completedReq);
    return true;
  }
  return false;
}

// Method on the scout object
// returns: the current rank of the scout
// Filters through the list of completed requirements for the ranks that are complete
// returns the rank with the highest order value
function currentRank() {

}

function getCompletedReqs();

function addCompletedReq();

function removeCompletedReq();

function setCompletedReqs();
<commit_msg>added currentRank method<commit_after>// A method that takes the id of a requirement (or award) and returns true if it is complete
// returns false if it is not complete

var masterReqirementArray = [
  {id: "a", doPrereqCount: 1, prereqs: ["b", "c"]},
  {id: "b"},
  {id: "c", doPrereqCount: 2, prereqs: ["d", "e"]},
  {id: "d"},
  {id: "e"}
];

var masterReqById = masterRequirementArray.reduce(function(previous, current) {
  previous[current.id] = current;
}, {});

var completedTest1 = ["d", "e"]; // c can be marked complete
var completedTest2 = ["b", "c"]; // a cant' be marked complete - d and e not complete
var completedTest3 = ["b", "c", "d", "e"]; //a can be marked complete

function isComplete(id, completedReqIds) {
  // returns true if the id is found in the list
  return (completedReqIds.indexOf(id) !== -1);
}

// parameters: requirement id, completedReqIds
// returns: boolean
// Checks to see if the prereqs for the listed id are complete
// Not all prereqs are required, so we count to see if we have done enough of them
function prereqsComplete(reqId, completedReqIds) {
  //check only immediate prereqs
  var req = masterReqById[reqId];
  var prereqsCompleteCount = 0;
  for (var i = 0; i < req.prereqs.length; i++) {
    // increase prereqsCompleteCount by 1 each time we find one that is complete
    if (completedReqIds.indexOf(req.prereqs[i]) !== -1) {
      prereqsCompleteCount++;
    }
  }
  // check to make sure we completed enough prereqs
  var result = (prereqsCompleteCount >= req.numReqPrereqs);
  return result;
}

// Method on the scout object
// parameters: reqId - completed requirement id
// returns: true if successful, false if not successful
// Checks to see if the prereqs for the requirement have already been completed by
// the scout. If they have, adds the requirement to the scout's list of completed
// requirements and returns true. Returns false if not.
function markReqComplete(reqId) {
  if (prereqsComplete(reqId, this.reqsCompleted)) {
    // push a new object onto the reqsCompleted array of the scout
    // should include a reqId and the current date
    var completedReq = {
      reqId: reqId,
      dateCompleted: new Date()
    };
    this.reqsCompleted.push(completedReq);
    return true;
  }
  return false;
}

// Method on the scout object
// returns: the current rank of the scout
// Filters through the list of completed requirements for the ranks that are complete
// returns the rank with the highest order value
function currentRank() {
  var completedRanks = this.reqsCompleted.map(function(current) {
    var req = masterReqById[current.reqId];
    // return the requirement if it is a rank
    if (req.type === "rank") {
      return req;
    }
  });
  var highestRank = completedRank[0];
  completedRank.forEach(function(currentRank) {
    // if the order of the current rank is higher than that in highestRank
    // replace the value of highest rank
    if (highestRank.order < currentRank.order) {
      highestRank = currentRank;
    }
  });

  return highestRank;
}

function getCompletedReqs();

function addCompletedReq();

function removeCompletedReq();

function setCompletedReqs();
<|endoftext|>


<commit_before>var testCase = require('nodeunit').testCase,
    swig = require('../../index');

exports.block = testCase({
    setUp: function (callback) {
        swig.init({
            allowErrors: true
        });
        callback();
    },

    basic: function (test) {
        var tpl,
            extends_base = [
                'This is from the "extends_base.html" template.',
                '',
                '{% block one %}',
                '  This is the default content in block \'one\'',
                '{% endblock %}',
                '',
                '{% block two %}',
                '  This is the default content in block \'two\'',
                '{% endblock %}'
            ].join('\n'),
            extends1 = [
                '{% extends "extends_base.html" %}',
                'This is content from "extends_1.html", you should not see it',
                '',
                '{% block one %}',
                '  This is the "extends_1.html" content in block \'one\'',
                '{% endblock %}'
            ].join('\n');

        swig.compile(extends_base, { filename: 'extends_base.html' });
        tpl = swig.compile(extends1, { filename: 'extends1.html' });
        test.strictEqual('This is from the "extends_base.html" template.\n\n\n  This is the "extends_1.html" content in block \'one\'\n\n\n  This is the default content in block \'two\'\n', tpl({}));
        test.done();
    }
});
<commit_msg>Added initial, basic block test.<commit_after>var testCase = require('nodeunit').testCase,
    swig = require('../../index');

exports.block = testCase({
    setUp: function (callback) {
        swig.init({
            allowErrors: true
        });
        callback();
    },

    basic: function (test) {
        var tpl,
            extends_base = [
                'This is from the "extends_base.html" template.',
                '',
                '{% block one %}',
                '  This is the default content in block \'one\'',
                '{% endblock %}',
                '',
                '{% block two %}',
                '  This is the default content in block \'two\'',
                '{% endblock %}'
            ].join('\n'),
            extends1 = [
                '{% extends "extends_base.html" %}',
                'This is content from "extends_1.html", you should not see it',
                '',
                '{% block one %}',
                '  This is the "extends_1.html" content in block \'one\'',
                '{% endblock %}'
            ].join('\n');

        swig.compile(extends_base, { filename: 'extends_base.html' });
        tpl = swig.compile(extends1, { filename: 'extends1.html' });
        test.strictEqual('This is from the "extends_base.html" template.\n\n\n  This is the "extends_1.html" content in block \'one\'\n\n\n  This is the default content in block \'two\'\n', tpl({}));
        test.done();
    },

    nested_basic: function (test) {
        var tpl,
            extends_base = [
                'This is from the "extends_base.html" template.',
                '',
                '{% block one %}',
                '  This is the default content in block \'one\'',
                '{% endblock %}',
                '',
                '{% block two %}',
                '  This is the default content in block \'two\'',
                '{% endblock %}'
            ].join('\n'),
            extends1 = [
                '{% extends "extends_base.html" %}',
                'This is content from "extends_1.html", you should not see it',
                '',
                '{% block one %}',
                '  This is the "extends_1.html" content in block \'one\'',
                '{% endblock %}'
            ].join('\n');
            extends2 = [
                '{% extends "extends1.html" %}',
                'This is content from "extends_1.html", you should not see it',
                '',
                '{% block one %}',
                '  This is the "extends_2.html" content in block \'one\'',
                '{% endblock %}'
            ].join('\n');

        swig.compile(extends_base, { filename: 'extends_base.html' });
        swig.compile(extends1, { filename: 'extends1.html' });
        tpl = swig.compile(extends2, { filename: 'extends2.html' });
        test.strictEqual('This is from the "extends_base.html" template.\n\n\n  This is the "extends_2.html" content in block \'one\'\n\n\n  This is the default content in block \'two\'\n', tpl({}));
        test.done();
    }
});
<|endoftext|>


<commit_before>var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

var pathToModule = function(path) {
  return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};

Object.keys(window.__karma__.files).forEach(function(file) {
  if (TEST_REGEXP.test(file)) {
    allTestFiles.push(pathToModule(file));
  }
});

require.config({
  baseUrl: "/base",

  paths: {
    // Libraries
    "jquery": "libraries/jquery/jquery",
    "hljs": "libraries/highlightjs/highlight.pack",
    // /Libraries

    // Application
    "app": "app/scripts/app",
    "drawer": "app/scripts/components/drawer",
    // /Application

    // Fixtures
    "app-fixture": "tests/fixtures/app-fixture"
    // /Fixtures
  },

  shim: {
  },

  deps: allTestFiles,

  callback: window.__karma__.start
});
<commit_msg>Specify component path in karma-requirejs.<commit_after>var allTestFiles = [];
var TEST_REGEXP = /(spec|test)\.js$/i;

var pathToModule = function(path) {
  return path.replace(/^\/base\//, '').replace(/\.js$/, '');
};

Object.keys(window.__karma__.files).forEach(function(file) {
  if (TEST_REGEXP.test(file)) {
    allTestFiles.push(pathToModule(file));
  }
});

require.config({
  baseUrl: "/base",

  paths: {
    // Libraries
    "jquery": "libraries/jquery/jquery",
    "hljs": "libraries/highlightjs/highlight.pack",
    // /Libraries

    // Application
    "app": "app/scripts/app",
    "components/drawer": "app/scripts/components/drawer",
    // /Application

    // Fixtures
    "app-fixture": "tests/fixtures/app-fixture"
    // /Fixtures
  },

  shim: {
  },

  deps: allTestFiles,

  callback: window.__karma__.start
});
<|endoftext|>


<commit_before>'use strict';

class Modal {

  constructor (settings) {

    // Define an empty options object
    let options = {};

    // Merge the user defined settings with the options object
    Object.assign(options, settings);

    // Define the modal selector
    this.selector = options.selector || '[data-modal]';

    // Define the selector that will close a modal instance
    this.closeSelector = options.closeSelector || '[data-modal-close]';

    // Define the selector that will trigger the modal instance
    this.showSelector = options.showSelector || '[data-modal-id]';

    // Define whether the modal should follow
    // the user down the page when they scroll
    this.isFixed = options.isFixed || true;

    // Define the class that is added to the modal
    // when it is active and visible
    this.activeClass = options.activeClass || 'is-active';

    // Define the class that is added to the <body>
    // when the modal is active and visible
    this.bodyClass = options.bodyClass || 'modal-is-active';

    // Bind `this` to the method so we can use it
    this.onClick = this.onClick.bind(this);
    this.onKeydown = this.onKeydown.bind(this);
    this.onLoad = this.onLoad.bind(this);
    this.show = this.show.bind(this);
    this.hideAll = this.hideAll.bind(this);

    // Add event listeners
    this.addEventListeners();

  }

  addEventListeners () {

    // 1. Add event listeners for touch devices
    document.addEventListener('touchstart', this.onClick);

    // 2. Add event listeners for mouse inputs
    document.addEventListener('mousedown', this.onClick);

    // 3. Add event listeners on keydown
    document.addEventListener('keydown', this.onKeydown);

    // 4. Add event listeners on load
    window.addEventListener('load', this.onLoad);

  }

  onClick (evt) {

    // 1. If the target element matches `this.showSelector`
    if (evt.target.matches(this.showSelector)) {

      // 1. Store the ID of the modal being requested
      let modalId = evt.target.dataset.modalId;

      // 2. If there is a modal ID, show the modal that matches
      if (modalId)
        this.show(modalId);

    // 2. If the target element matches `this.closeSelector`
    } else if (evt.target.matches(this.closeSelector)) {

      // 1. Store the ID of the modal being hidden
      let modalId = evt.target.parentNode.id;

      // 2. If there is a modal ID, hide the modal that matches
      if (modalId)
        this.hide(modalId);

    // 3. If the target element is the `.overlay`
    } else if (evt.target.matches('.overlay')) {

      // 1. Close everything
      this.hideAll();

    // 4. Otherwise it was none of the above, so cancel.
    } else {

      return;

    }

    // 5. Prevent the default functionality of whatever is being clicked
    evt.preventDefault();

  }

  onKeydown (evt) {

    // 1. If user hits `esc` key, close everything
    if(evt.keyCode === 27)
      this.hideAll();

  }

  onLoad (evt) {

    let hash = window.location.hash.substring(1);

    if(hash) {
      let modal = document.getElementById(hash);

      if(modal)
        this.show(modal.id);
    }

  }

  show (id) {

    // 1. Grab the modal that matches the ID
    const modal = document.getElementById(id);

    // 2. Add an overlay to disable the rest of the site
    if (!document.querySelector('.overlay')) {
      let overlay = document.createElement('div');
      overlay.classList.add('overlay');
      overlay.classList.add(this.activeClass);
      document.body.appendChild(overlay);
    }

    // 3. Add an active class to the modal instance
    modal.classList.add(this.activeClass);

    // 4. Add an active class to the <body>
    document.body.classList.add(this.bodyClass);

  }

  hide (id) {

    // 1. Grab the modal that matches the ID
    const modal = document.getElementById(id);

    // 2. Remove the active class to the modal instance
    modal.classList.remove(this.activeClass);

    // 3. If there are no modals active
    if (!document.querySelector(this.selector + '.' + this.activeClass)) {

      // 1. Remove the overlay
      let overlay = document.querySelector('.overlay');
      overlay.parentNode.removeChild(overlay);

      // 2. Remove the active class from the body
      document.body.classList.remove(this.bodyClass);

    }

  }

  hideAll () {

    // 1. Grab all active models
    const modals = document.querySelectorAll(this.selector + '.' + this.activeClass);

    // 2. Hide each active modal
    for (var i = 0; i < modals.length; i++) {
      let modal = modals[i];
      this.hide(modal.id);
    }

  }

}
<commit_msg>Added TODO<commit_after>/**
 * TODO
 *
 * - Auto pause any video that might be included in a modal
 * - Implement pushState to change the URL when opening/closing a modal
 */

'use strict';

class Modal {

  constructor (settings) {

    // Define an empty options object
    let options = {};

    // Merge the user defined settings with the options object
    Object.assign(options, settings);

    // Define the modal selector
    this.selector = options.selector || '[data-modal]';

    // Define the selector that will close a modal instance
    this.closeSelector = options.closeSelector || '[data-modal-close]';

    // Define the selector that will trigger the modal instance
    this.showSelector = options.showSelector || '[data-modal-id]';

    // Define whether the modal should follow
    // the user down the page when they scroll
    this.isFixed = options.isFixed || true;

    // Define the class that is added to the modal
    // when it is active and visible
    this.activeClass = options.activeClass || 'is-active';

    // Define the class that is added to the <body>
    // when the modal is active and visible
    this.bodyClass = options.bodyClass || 'modal-is-active';

    // Bind `this` to the method so we can use it
    this.onClick = this.onClick.bind(this);
    this.onKeydown = this.onKeydown.bind(this);
    this.onLoad = this.onLoad.bind(this);
    this.show = this.show.bind(this);
    this.hideAll = this.hideAll.bind(this);

    // Add event listeners
    this.addEventListeners();

  }

  addEventListeners () {

    // 1. Add event listeners for touch devices
    document.addEventListener('touchstart', this.onClick);

    // 2. Add event listeners for mouse inputs
    document.addEventListener('mousedown', this.onClick);

    // 3. Add event listeners on keydown
    document.addEventListener('keydown', this.onKeydown);

    // 4. Add event listeners on load
    window.addEventListener('load', this.onLoad);

  }

  onClick (evt) {

    // 1. If the target element matches `this.showSelector`
    if (evt.target.matches(this.showSelector)) {

      // 1. Store the ID of the modal being requested
      let modalId = evt.target.dataset.modalId;

      // 2. If there is a modal ID, show the modal that matches
      if (modalId)
        this.show(modalId);

    // 2. If the target element matches `this.closeSelector`
    } else if (evt.target.matches(this.closeSelector)) {

      // 1. Store the ID of the modal being hidden
      let modalId = evt.target.parentNode.id;

      // 2. If there is a modal ID, hide the modal that matches
      if (modalId)
        this.hide(modalId);

    // 3. If the target element is the `.overlay`
    } else if (evt.target.matches('.overlay')) {

      // 1. Close everything
      this.hideAll();

    // 4. Otherwise it was none of the above, so cancel.
    } else {

      return;

    }

    // 5. Prevent the default functionality of whatever is being clicked
    evt.preventDefault();

  }

  onKeydown (evt) {

    // 1. If user hits `esc` key, close everything
    if(evt.keyCode === 27)
      this.hideAll();

  }

  onLoad (evt) {

    let hash = window.location.hash.substring(1);

    if(hash) {
      let modal = document.getElementById(hash);

      if(modal)
        this.show(modal.id);
    }

  }

  show (id) {

    // 1. Grab the modal that matches the ID
    const modal = document.getElementById(id);

    // 2. Add an overlay to disable the rest of the site
    if (!document.querySelector('.overlay')) {
      let overlay = document.createElement('div');
      overlay.classList.add('overlay');
      overlay.classList.add(this.activeClass);
      document.body.appendChild(overlay);
    }

    // 3. Add an active class to the modal instance
    modal.classList.add(this.activeClass);

    // 4. Add an active class to the <body>
    document.body.classList.add(this.bodyClass);

  }

  hide (id) {

    // 1. Grab the modal that matches the ID
    const modal = document.getElementById(id);

    // 2. Remove the active class to the modal instance
    modal.classList.remove(this.activeClass);

    // 3. If there are no modals active
    if (!document.querySelector(this.selector + '.' + this.activeClass)) {

      // 1. Remove the overlay
      let overlay = document.querySelector('.overlay');
      overlay.parentNode.removeChild(overlay);

      // 2. Remove the active class from the body
      document.body.classList.remove(this.bodyClass);

    }

  }

  hideAll () {

    // 1. Grab all active models
    const modals = document.querySelectorAll(this.selector + '.' + this.activeClass);

    // 2. Hide each active modal
    for (var i = 0; i < modals.length; i++) {
      let modal = modals[i];
      this.hide(modal.id);
    }

  }

}
<|endoftext|>


<commit_before>/**
 * @properties={typeid:24,uuid:"679E98F4-990B-4543-9FDC-8A65A0047E7B"}
 */
function SNIPPET_states_us(selected) {

	function isSelected(state) {
		if (state == selected) {
			return ' selected="selected"'
		}
		else {
			return ''
		}
	}

	var html = '<option' + isSelected("AL") + ' value="AL">Alabama</option>\n\
  	<option' + isSelected("AK") + ' value="AK">Alaska</option>\n\
  	<option' + isSelected("AZ") + ' value="AZ">Arizona</option>\n\
	<option' + isSelected("AR") + ' value="AR">Arkansas</option>\n\
	<option' + isSelected("CA") + ' value="CA">California</option>\n\
	<option' + isSelected("CO") + ' value="CO">Colorado</option>\n\
	<option' + isSelected("CT") + ' value="CT">Connecticut</option>\n\
	<option' + isSelected("DE") + ' value="DE">Delaware</option>\n\
	<option' + isSelected("DC") + ' value="DC">Dist of Columbia</option>\n\
	<option' + isSelected("FL") + ' value="FL">Florida</option>\n\
	<option' + isSelected("GA") + ' value="GA">Georgia</option>\n\
	<option' + isSelected("HI") + ' value="HI">Hawaii</option>\n\
	<option' + isSelected("ID") + ' value="ID">Idaho</option>\n\
	<option' + isSelected("IL") + ' value="IL">Illinois</option>\n\
	<option' + isSelected("IN") + ' value="IN">Indiana</option>\n\
	<option' + isSelected("IA") + ' value="IA">Iowa</option>\n\
	<option' + isSelected("KS") + ' value="KS">Kansas</option>\n\
	<option' + isSelected("KY") + ' value="KY">Kentucky</option>\n\
	<option' + isSelected("LA") + ' value="LA">Louisiana</option>\n\
	<option' + isSelected("ME") + ' value="ME">Maine</option>\n\
	<option' + isSelected("MD") + ' value="MD">Maryland</option>\n\
	<option' + isSelected("MA") + ' value="MA">Massachusetts</option>\n\
	<option' + isSelected("MI") + ' value="MI">Michigan</option>\n\
	<option' + isSelected("MN") + ' value="MN">Minnesota</option>\n\
	<option' + isSelected("MS") + ' value="MS">Mississippi</option>\n\
	<option' + isSelected("MO") + ' value="MO">Missouri</option>\n\
	<option' + isSelected("MT") + ' value="MT">Montana</option>\n\
	<option' + isSelected("NE") + ' value="NE">Nebraska</option>\n\
	<option' + isSelected("NV") + ' value="NV">Nevada</option>\n\
	<option' + isSelected("NH") + ' value="NH">New Hampshire</option>\n\
	<option' + isSelected("NJ") + ' value="NJ">New Jersey</option>\n\
	<option' + isSelected("NM") + ' value="NM">New Mexico</option>\n\
	<option' + isSelected("NY") + ' value="NY">New York</option>\n\
	<option' + isSelected("NC") + ' value="NC">North Carolina</option>\n\
	<option' + isSelected("ND") + ' value="ND">North Dakota</option>\n\
	<option' + isSelected("OH") + ' value="OH">Ohio</option>\n\
	<option' + isSelected("OK") + ' value="OK">Oklahoma</option>\n\
	<option' + isSelected("OR") + ' value="OR">Oregon</option>\n\
	<option' + isSelected("PA") + ' value="PA">Pennsylvania</option>\n\
	<option' + isSelected("RI") + ' value="RI">Rhode Island</option>\n\
	<option' + isSelected("SC") + ' value="SC">South Carolina</option>\n\
	<option' + isSelected("SD") + ' value="SD">South Dakota</option>\n\
	<option' + isSelected("TN") + ' value="TN">Tennessee</option>\n\
	<option' + isSelected("TX") + ' value="TX">Texas</option>\n\
	<option' + isSelected("UT") + ' value="UT">Utah</option>\n\
	<option' + isSelected("VT") + ' value="VT">Vermont</option>\n\
	<option' + isSelected("VA") + ' value="VA">Virginia</option>\n\
	<option' + isSelected("WA") + ' value="WA">Washington</option>\n\
	<option' + isSelected("WV") + ' value="WV">West Virginia</option>\n\
	<option' + isSelected("WI") + ' value="WI">Wisconsin</option>\n\
	<option' + isSelected("WY") + ' value="WY">Wyoming</option>\n'

	return html
}

/**
 * @properties={typeid:24,uuid:"689E98F4-990B-4543-9FDC-8A65A0047E7B"}
 */
function SNIPPET_countries_short(selected) {

	function isSelected(country) {
		if (country == selected) {
			return ' selected="selected"'
		}
		else {
			return ''
		}
	}

	var html = '<option' + isSelected("usa") + ' value="AL">United States</option>\n\
  	<option' + isSelected("ca") + ' value="AK">Canada</option>\n\
	<option' + isSelected("mx") + ' value="WI">Mexico</option>\n'

	return html
}

/**
 * @properties={typeid:24,uuid:"B96A5D9D-B6CA-4785-B4EB-03BD34B11FD2"}
 */
function SNIPPET_credit_card_month(selected) {

	function isSelected(month) {
		if (month == selected) {
			return ' selected="selected"'
		}
		else {
			return ''
		}
	}

	var html = '<option' + isSelected("01") + ' value="01">1</option>\n\
  				<option' + isSelected("02") + ' value="02">2</option>\n\
  				<option' + isSelected("03") + ' value="03">3</option>\n\
				<option' + isSelected("04") + ' value="04">4</option>\n\
				<option' + isSelected("05") + ' value="05">5</option>\n\
				<option' + isSelected("06") + ' value="06">6</option>\n\
				<option' + isSelected("07") + ' value="07">7</option>\n\
				<option' + isSelected("08") + ' value="08">8</option>\n\
				<option' + isSelected("09") + ' value="09">9</option>\n\
				<option' + isSelected("10") + ' value="10">10</option>\n\
				<option' + isSelected("11") + ' value="11">11</option>\n\
				<option' + isSelected("12") + ' value="12">12</option>\n'
	return html
}

/**
 * @properties={typeid:24,uuid:"5AD0C261-20CA-4EAB-BDAD-BC675C223D1E"}
 */
function SNIPPET_credit_card_year(selected) {
	var html =''
	var today = new Date()
	var thisYear = today.getFullYear()

	for (var i=thisYear; i<thisYear+11; i++) {
		if (utils.numberFormat(i,'####') == selected) {
			html += '<option selected="selected" value="'+i+'">'+i+'</option>\n'
		}
		else {
			html += '<option value="'+i+'">'+i+'</option>\n'
		}
	}

	return html
}
<commit_msg>stage 1 jquery UI stuff<commit_after>/**
 * @properties={typeid:24,uuid:"679E98F4-990B-4543-9FDC-8A65A0047E7B"}
 */
function SNIPPET_states_us(selected) {

	function isSelected(state) {
		if (state == selected) {
			return ' selected="selected"'
		}
		else {
			return ''
		}
	}

	var html = '<option' + isSelected("AL") + ' value="AL">Alabama</option>\n\
  	<option' + isSelected("AK") + ' value="AK">Alaska</option>\n\
  	<option' + isSelected("AZ") + ' value="AZ">Arizona</option>\n\
	<option' + isSelected("AR") + ' value="AR">Arkansas</option>\n\
	<option' + isSelected("CA") + ' value="CA">California</option>\n\
	<option' + isSelected("CO") + ' value="CO">Colorado</option>\n\
	<option' + isSelected("CT") + ' value="CT">Connecticut</option>\n\
	<option' + isSelected("DE") + ' value="DE">Delaware</option>\n\
	<option' + isSelected("DC") + ' value="DC">Dist of Columbia</option>\n\
	<option' + isSelected("FL") + ' value="FL">Florida</option>\n\
	<option' + isSelected("GA") + ' value="GA">Georgia</option>\n\
	<option' + isSelected("HI") + ' value="HI">Hawaii</option>\n\
	<option' + isSelected("ID") + ' value="ID">Idaho</option>\n\
	<option' + isSelected("IL") + ' value="IL">Illinois</option>\n\
	<option' + isSelected("IN") + ' value="IN">Indiana</option>\n\
	<option' + isSelected("IA") + ' value="IA">Iowa</option>\n\
	<option' + isSelected("KS") + ' value="KS">Kansas</option>\n\
	<option' + isSelected("KY") + ' value="KY">Kentucky</option>\n\
	<option' + isSelected("LA") + ' value="LA">Louisiana</option>\n\
	<option' + isSelected("ME") + ' value="ME">Maine</option>\n\
	<option' + isSelected("MD") + ' value="MD">Maryland</option>\n\
	<option' + isSelected("MA") + ' value="MA">Massachusetts</option>\n\
	<option' + isSelected("MI") + ' value="MI">Michigan</option>\n\
	<option' + isSelected("MN") + ' value="MN">Minnesota</option>\n\
	<option' + isSelected("MS") + ' value="MS">Mississippi</option>\n\
	<option' + isSelected("MO") + ' value="MO">Missouri</option>\n\
	<option' + isSelected("MT") + ' value="MT">Montana</option>\n\
	<option' + isSelected("NE") + ' value="NE">Nebraska</option>\n\
	<option' + isSelected("NV") + ' value="NV">Nevada</option>\n\
	<option' + isSelected("NH") + ' value="NH">New Hampshire</option>\n\
	<option' + isSelected("NJ") + ' value="NJ">New Jersey</option>\n\
	<option' + isSelected("NM") + ' value="NM">New Mexico</option>\n\
	<option' + isSelected("NY") + ' value="NY">New York</option>\n\
	<option' + isSelected("NC") + ' value="NC">North Carolina</option>\n\
	<option' + isSelected("ND") + ' value="ND">North Dakota</option>\n\
	<option' + isSelected("OH") + ' value="OH">Ohio</option>\n\
	<option' + isSelected("OK") + ' value="OK">Oklahoma</option>\n\
	<option' + isSelected("OR") + ' value="OR">Oregon</option>\n\
	<option' + isSelected("PA") + ' value="PA">Pennsylvania</option>\n\
	<option' + isSelected("RI") + ' value="RI">Rhode Island</option>\n\
	<option' + isSelected("SC") + ' value="SC">South Carolina</option>\n\
	<option' + isSelected("SD") + ' value="SD">South Dakota</option>\n\
	<option' + isSelected("TN") + ' value="TN">Tennessee</option>\n\
	<option' + isSelected("TX") + ' value="TX">Texas</option>\n\
	<option' + isSelected("UT") + ' value="UT">Utah</option>\n\
	<option' + isSelected("VT") + ' value="VT">Vermont</option>\n\
	<option' + isSelected("VA") + ' value="VA">Virginia</option>\n\
	<option' + isSelected("WA") + ' value="WA">Washington</option>\n\
	<option' + isSelected("WV") + ' value="WV">West Virginia</option>\n\
	<option' + isSelected("WI") + ' value="WI">Wisconsin</option>\n\
	<option' + isSelected("WY") + ' value="WY">Wyoming</option>\n'

	return html
}

/**
 * @properties={typeid:24,uuid:"689E98F4-990B-4543-9FDC-8A65A0047E7B"}
 */
function SNIPPET_countries_short(selected) {

	function isSelected(country) {
		if (country == selected) {
			return ' selected="selected"'
		}
		else {
			return ''
		}
	}

	var html = '<option' + isSelected("usa") + ' value="AL">United States</option>\n\
  	<option' + isSelected("ca") + ' value="AK">Canada</option>\n'

	return html
}

/**
 * @properties={typeid:24,uuid:"B96A5D9D-B6CA-4785-B4EB-03BD34B11FD2"}
 */
function SNIPPET_credit_card_month(selected) {

	function isSelected(month) {
		if (month == selected) {
			return ' selected="selected"'
		}
		else {
			return ''
		}
	}

	var html = '<option' + isSelected("01") + ' value="01">1</option>\n\
  				<option' + isSelected("02") + ' value="02">2</option>\n\
  				<option' + isSelected("03") + ' value="03">3</option>\n\
				<option' + isSelected("04") + ' value="04">4</option>\n\
				<option' + isSelected("05") + ' value="05">5</option>\n\
				<option' + isSelected("06") + ' value="06">6</option>\n\
				<option' + isSelected("07") + ' value="07">7</option>\n\
				<option' + isSelected("08") + ' value="08">8</option>\n\
				<option' + isSelected("09") + ' value="09">9</option>\n\
				<option' + isSelected("10") + ' value="10">10</option>\n\
				<option' + isSelected("11") + ' value="11">11</option>\n\
				<option' + isSelected("12") + ' value="12">12</option>\n'
	return html
}

/**
 * @properties={typeid:24,uuid:"5AD0C261-20CA-4EAB-BDAD-BC675C223D1E"}
 */
function SNIPPET_credit_card_year(selected) {
	var html =''
	var today = new Date()
	var thisYear = today.getFullYear()

	for (var i=thisYear; i<thisYear+11; i++) {
		if (utils.numberFormat(i,'####') == selected) {
			html += '<option selected="selected" value="'+i+'">'+i+'</option>\n'
		}
		else {
			html += '<option value="'+i+'">'+i+'</option>\n'
		}
	}

	return html
}
<|endoftext|>


<commit_before>import 'native-promise-only'
import page from 'page'
import './timeago-fix'
import timeago from 'democracyos-timeago'
import debug from 'debug'
import config from '../../config/config'

import '../../translations/translations.js'

/**
 * Enable client-side debug messages
 */

import '../../debug'

/**
 * Initialize debug for DemocracyOS
 */

let log = debug('democraycos:boot')

/**
 * Mount applications.
 */

import '../../analytics'
import '../../body-classes/body'
import '../../content-lock/locker'
import '../../header/header/header'
import '../../error-pages/error-pages'
import '../../logout/logout'
import '../../site/auth-facebook/auth-facebook'
import '../../settings/settings/settings'
import '../../settings/forum-new/forum-new'
// import '../../forum/forum'
// import '../../404/404'

/**
 * Init `timeago` component with parameter locale
 */

timeago('.ago', { lang: config.locale, interval: 1000 })

/**
 * Init page.js
 */

page()

if (config.googleAnalyticsTrackingId) {
  require('democracyos-ga')(config.googleAnalyticsTrackingId)
}
<commit_msg>fix settings to admin<commit_after>import 'native-promise-only'
import page from 'page'
import './timeago-fix'
import timeago from 'democracyos-timeago'
import debug from 'debug'
import config from '../../config/config'

import '../../translations/translations.js'

/**
 * Enable client-side debug messages
 */

import '../../debug'

/**
 * Initialize debug for DemocracyOS
 */

let log = debug('democraycos:boot')

/**
 * Mount applications.
 */
import '../../site-routes'
import '../../analytics'
import '../../body-classes/body'
import '../../content-lock/locker'
import '../../header/header/header'
import '../../error-pages/error-pages'
import '../../logout/logout'
import '../../site/auth-facebook/auth-facebook'
import '../../settings/settings/settings'
import '../../settings/forum-new/forum-new'
// import '../../forum/forum'
// import '../../404/404'

/**
 * Init `timeago` component with parameter locale
 */

timeago('.ago', { lang: config.locale, interval: 1000 })

/**
 * Init page.js
 */

page()

if (config.googleAnalyticsTrackingId) {
  require('democracyos-ga')(config.googleAnalyticsTrackingId)
}
<|endoftext|>


<commit_before>// nS - No Space
// lC - Lowercase

export function filesToModifyContent(currentAppName, newName) {
  const nS_CurrentAppName = currentAppName.replace(/\s/g, '');
  const nS_NewName = newName.replace(/\s/g, '');

  return [
    {
      regex: `<string name="app_name">${currentAppName}</string>`,
      replacement: `<string name="app_name">${newName}</string>`,
      paths: ['./android/app/src/main/res/values/strings.xml'],
    },
    {
      regex: nS_CurrentAppName,
      replacement: nS_NewName,
      paths: [
        './index.android.js',
        './index.ios.js',
        `./ios/${nS_NewName}.xcodeproj/project.pbxproj`,
        `./ios/${nS_NewName}.xcworkspace/contents.xcworkspacedata`,
        `./ios/${nS_NewName}.xcodeproj/xcshareddata/xcschemes/${nS_NewName}-tvOS.xcscheme`,
        `./ios/${nS_NewName}.xcodeproj/xcshareddata/xcschemes/${nS_NewName}.xcscheme`,
        `./ios/${nS_NewName}/AppDelegate.m`,
        './android/settings.gradle',
        `./ios/${nS_NewName}Tests/${nS_NewName}Tests.m`,
        './ios/build/info.plist',
        './ios/Podfile',
        './app.json',
      ],
    },
    {
      regex: `text="${currentAppName}"`,
      replacement: `text="${newName}"`,
      paths: [`./ios/${nS_NewName}/Base.lproj/LaunchScreen.xib`],
    },
    {
      regex: currentAppName,
      replacement: newName,
      paths: [`./ios/${nS_NewName}/Info.plist`],
    },
    {
      regex: `"name": "${nS_CurrentAppName}"`,
      replacement: `"name": "${nS_NewName}"`,
      paths: ['./package.json'],
    },
    {
      regex: `"displayName": "${currentAppName}"`,
      replacement: `"displayName": "${newName}"`,
      paths: ['./app.json'],
    },
  ];
}
<commit_msg>Add index.js (for RN49+)<commit_after>// nS - No Space
// lC - Lowercase

export function filesToModifyContent(currentAppName, newName) {
  const nS_CurrentAppName = currentAppName.replace(/\s/g, '');
  const nS_NewName = newName.replace(/\s/g, '');

  return [
    {
      regex: `<string name="app_name">${currentAppName}</string>`,
      replacement: `<string name="app_name">${newName}</string>`,
      paths: ['./android/app/src/main/res/values/strings.xml'],
    },
    {
      regex: nS_CurrentAppName,
      replacement: nS_NewName,
      paths: [
        './index.js',
        './index.android.js',
        './index.ios.js',
        `./ios/${nS_NewName}.xcodeproj/project.pbxproj`,
        `./ios/${nS_NewName}.xcworkspace/contents.xcworkspacedata`,
        `./ios/${nS_NewName}.xcodeproj/xcshareddata/xcschemes/${nS_NewName}-tvOS.xcscheme`,
        `./ios/${nS_NewName}.xcodeproj/xcshareddata/xcschemes/${nS_NewName}.xcscheme`,
        `./ios/${nS_NewName}/AppDelegate.m`,
        './android/settings.gradle',
        `./ios/${nS_NewName}Tests/${nS_NewName}Tests.m`,
        './ios/build/info.plist',
        './ios/Podfile',
        './app.json',
      ],
    },
    {
      regex: `text="${currentAppName}"`,
      replacement: `text="${newName}"`,
      paths: [`./ios/${nS_NewName}/Base.lproj/LaunchScreen.xib`],
    },
    {
      regex: currentAppName,
      replacement: newName,
      paths: [`./ios/${nS_NewName}/Info.plist`],
    },
    {
      regex: `"name": "${nS_CurrentAppName}"`,
      replacement: `"name": "${nS_NewName}"`,
      paths: ['./package.json'],
    },
    {
      regex: `"displayName": "${currentAppName}"`,
      replacement: `"displayName": "${newName}"`,
      paths: ['./app.json'],
    },
  ];
}
<|endoftext|>


<commit_before>angular.module('ng-transloadit', []).factory('Transloadit', ['$http', function($http) {
  var TRANSLOADIT_API = 'http://api2.transloadit.com/assemblies';

  function getExpiryDate() {
    var date = new Date();
    date.setHours(date.getHours() + 12);

    var year = date.getUTCFullYear();
    var month = zeroFill(date.getUTCMonth() + 1, 2);
    var day = zeroFill(date.getUTCDate(), 2);

    var hours = zeroFill(date.getUTCHours(), 2);
    var minutes = zeroFill(date.getUTCMinutes(), 2);
    var seconds = zeroFill(date.getUTCSeconds(), 2);

    return year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds + '+00:00';
  }

  function zeroFill(number, width) {
    width -= number.toString().length;
    if (width > 0) {
      return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
    }

    return number + ""; // always return a string
  }

  return {
    upload: function(file, options) {
      this._validateBrowser();
      this._validateOptions(options);
      this._addExpiryDate(options);

      function check(assemblyUrl) {
        setTimeout(function() {
          $http.get(assemblyUrl).success(function(results) {
            if (results.ok === 'ASSEMBLY_COMPLETED') {
              options.uploaded(results);
            } else {
              check(results.assembly_url);
            }
          }).error(options.error);
        }, 2000);
      }

      options.signature(function(signatureValue) {
        var paramsValue = angular.toJson(options.params);

        var formData = new FormData();
        formData.append('params', paramsValue);
        formData.append('signature', signatureValue);
        formData.append(file.name, file);

        var xhr = new XMLHttpRequest();
        xhr.open('POST', TRANSLOADIT_API, true);
        xhr.onload = function(response) {
          var results = angular.fromJson(this.response);

          $scope.$apply(function() {
            options.processing();
          });

          check(results.assembly_url);
        };

        xhr.upload.onprogress = function(e) {
          if (e.lengthComputable) {

            $scope.$apply(function() {
              options.progress(e.loaded, e.total);
            });
          }
        };

        xhr.send(formData);
      });
    },

    _validateBrowser: function() {
      var isXHR2 = new XMLHttpRequest().hasOwnProperty('upload');

      if (!isXHR2) {
        throw new Error('Transloadit will only work with XMLHttpRequest 2');
      }
    },

    _validateOptions: function(options) {
      // mandatory fields
      if (!options.signature) {
        throw new Error('must supply a signature function');
      }

      if (!options.uploaded) {
        throw new Error('must supply an uploaded callback');
      }

      if (!options.params) {
        throw new Error('must supply params');
      }

      if (!options.params.auth.key) {
        throw new Error('must supply a key');
      }

      // optional fields
      options.processing = options.processing || function() {};
      options.progress = options.progress || function() {};
      options.error = options.error || function() {};
    },

    _addExpiryDate: function(options) {
      options.params.auth.expires = getExpiryDate();
    }
  };
}]);

<commit_msg>Added missing scope<commit_after>angular.module('ng-transloadit', []).factory('Transloadit', ['$http', '$rootScope', function($http, $rootScope) {
  $scope = $rootScope.$new();
  var TRANSLOADIT_API = 'http://api2.transloadit.com/assemblies';

  function getExpiryDate() {
    var date = new Date();
    date.setHours(date.getHours() + 12);

    var year = date.getUTCFullYear();
    var month = zeroFill(date.getUTCMonth() + 1, 2);
    var day = zeroFill(date.getUTCDate(), 2);

    var hours = zeroFill(date.getUTCHours(), 2);
    var minutes = zeroFill(date.getUTCMinutes(), 2);
    var seconds = zeroFill(date.getUTCSeconds(), 2);

    return year + '/' + month + '/' + day + ' ' + hours + ':' + minutes + ':' + seconds + '+00:00';
  }

  function zeroFill(number, width) {
    width -= number.toString().length;
    if (width > 0) {
      return new Array( width + (/\./.test( number ) ? 2 : 1) ).join( '0' ) + number;
    }

    return number + ""; // always return a string
  }

  return {
    upload: function(file, options) {
      this._validateBrowser();
      this._validateOptions(options);
      this._addExpiryDate(options);

      function check(assemblyUrl) {
        setTimeout(function() {
          $http.get(assemblyUrl).success(function(results) {
            if (results.ok === 'ASSEMBLY_COMPLETED') {
              options.uploaded(results);
            } else {
              check(results.assembly_url);
            }
          }).error(options.error);
        }, 2000);
      }

      options.signature(function(signatureValue) {
        var paramsValue = angular.toJson(options.params);

        var formData = new FormData();
        formData.append('params', paramsValue);
        formData.append('signature', signatureValue);
        formData.append(file.name, file);

        var xhr = new XMLHttpRequest();
        xhr.open('POST', TRANSLOADIT_API, true);
        xhr.onload = function(response) {
          var results = angular.fromJson(this.response);

          $scope.$apply(function() {
            options.processing();
          });

          check(results.assembly_url);
        };

        xhr.upload.onprogress = function(e) {
          if (e.lengthComputable) {

            $scope.$apply(function() {
              options.progress(e.loaded, e.total);
            });
          }
        };

        xhr.send(formData);
      });
    },

    _validateBrowser: function() {
      var isXHR2 = new XMLHttpRequest().hasOwnProperty('upload');

      if (!isXHR2) {
        throw new Error('Transloadit will only work with XMLHttpRequest 2');
      }
    },

    _validateOptions: function(options) {
      // mandatory fields
      if (!options.signature) {
        throw new Error('must supply a signature function');
      }

      if (!options.uploaded) {
        throw new Error('must supply an uploaded callback');
      }

      if (!options.params) {
        throw new Error('must supply params');
      }

      if (!options.params.auth.key) {
        throw new Error('must supply a key');
      }

      // optional fields
      options.processing = options.processing || function() {};
      options.progress = options.progress || function() {};
      options.error = options.error || function() {};
    },

    _addExpiryDate: function(options) {
      options.params.auth.expires = getExpiryDate();
    }
  };
}]);

<|endoftext|>


<commit_before>// ==UserScript==
// @id             iitc-plugin-keys-list@isnot
// @name           IITC plugin: Keys List
// @category       Keys
// @version        0.3.20160818
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @author         isnot
// @updateURL      none
// @downloadURL    none
// @description    [iitc-plugins] Export the manually entered key counts from the 'keys' plugin.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// ==/UserScript==

function wrapper(plugin_info) {
  // ensure plugin framework is there, even if iitc is not yet loaded
  if (typeof window.plugin !== 'function') window.plugin = function() {};

  // PLUGIN START ////////////////////////////////////////////////////////

  // if the Keys/Cache plugin is not available, quit now
  if (!window.plugin.keys) {
    return console.warn("[KeysList] This plugin is dependent on the Keys plugin being present.");
  }
  if (!window.plugin.cachePortalDetailsOnMap) {
    return console.warn("[KeysList] This plugin is dependent on the Cache plugin being present.");
  }

  // Expand Cache BEGIN //////////////////////////////////////////////////////////
  var cache = window.plugin.cachePortalDetailsOnMap;
  cache.KEY_LOCALSTRAGE = 'plugin-cache-local-v1';

  cache.getPortalByGuid = function (guid) {
    var portal_cache = cache.cache[guid];
    console.log('==KeysList gpbg ' + portal_cache + typeof portal_cache);
    if (typeof portal_cache === 'function') {

      return JSON.parse(portal_cache.ent);
    }
  };

  cache.storeToLocal = function () {
    localStorage.setItem(cache.KEY_LOCALSTRAGE, JSON.stringify(cache.cache));
  };

  cache.loadFromLocal = function () {
    // if an existing portal cache, load it
    var raw = window.localStorage[cache.KEY_LOCALSTRAGE];
    if (typeof raw === 'function') {
      cache.merge(JSON.parse(raw));
    } else {
      // make a new cache
      window.localStorage[cache.KEY_LOCALSTRAGE] = "{}";
    }
  };

  cache.merge = function (inbound) {
    if (cache.cache.length < 1) {
      cache.cache = inbound;
      return inbound.length;
    }

    for (var x in Object.keys(inbound)) {
      cache.cache[x] = inbound[x];
    }
    return cache.cache.length;
  };

  // Expand Cache END //////////////////////////////////////////////////////////

  // use own namespace for plugin
  window.plugin.keysList = function() {};
  var self = window.plugin.keysList;
  self.listAll = [];

  // fetch a portal name from a cached list if available
  self.getPortalDetails = function getPortalDetails(key) {
    var name = "(not detected)";
    var latLng = '0,0';
    var imageUrl = '';

    // try plugin cache
    var portal_cache = cache.getPortalByGuid(key.guid);
    if (typeof portal_cache === 'function') {
      //name = portal_cache.name;
      console.log('==KsysList pc ' + portal_cache + Object.keys(portal_cache).join(' '));
    }

    var data = (window.portals[key.guid] && window.portals[key.guid].options.data) || window.portalDetail.get(key.guid) || null;
    if (data) {
      console.log('==KsysList pd ' + data.title);
      if (data.title) name = data.title;
      imageUrl = window.fixPortalImageUrl(data.image);
      if (imageUrl.indexOf('//') === 1) {
        imageUrl = 'http:' + imageUrl;
      }
      if (imageUrl.indexOf(DEFAULT_PORTAL_IMG) !== -1) {
        imageUrl = '';
      }
    }

    var hLatLng = window.findPortalLatLng(key.guid);
    if (hLatLng) {
      latLng = hLatLng.lat + ',' + hLatLng.lng;
    }

    key.name = name;
    key.latLng = latLng;
    key.imageUrl = imageUrl;
    if (latLng === '0,0') {
      key.intelMapUrl = '';
    } else {
      key.intelMapUrl = 'https://www.ingress.com/intel?ll=' + latLng + '&z=17&pll=' + latLng;
    }

    return key;
  };

  self.csvValue = function(str) {
    if (str) {
      return '"' + str.replace("/\"/g", '""') + '"';
    } else {
      return '';
    }
  };

  self.eachKey = function(key) {
    if (key.count > 0) {
      key = self.getPortalDetails(key);
      var csvline = [
        self.csvValue(key.name),
        parseInt(key.count, 10),
        self.csvValue(key.latLng),
        self.csvValue(key.intelMapUrl),
        self.csvValue(key.imageUrl),
        key.guid
      ];
      self.listAll.push(csvline.join(","));
    }
  };

  self.renderList = function() {
    self.listAll = [];

    $.each(plugin.keys.keys, function(key, count) {
      self.eachKey({"guid": key, "count": count});
    });

    var html = '
KeysList for ' + window.PLAYER.nickname + ' ' + self.listAll.length + 'portals of keys. ' + new Date().toISOString() +
        '
<textarea cols="78" rows="20">name,count,latlng,url,image,guid' + "\n" + self.listAll.join("\n") + '</textarea>';
    dialog({
      title: 'KeysList',
      html: html,
      width: 600,
      position: {my: 'right center', at: 'center-60 center', of: window, collision: 'fit'}
    });
    console.log("==KeysList " + window.PLAYER.nickname + " " + self.listAll.length + " " + new Date().toISOString());

    cache.storeToLocal();
  };

  var setup = function() {
    // console.log("==KeysList setup ");
    $('#toolbox').append('KeysListCsv');
    cache.loadFromLocal();
  };

  // PLUGIN END //////////////////////////////////////////////////////////

  setup.info = plugin_info; //add the script info data to the function as a property
  if(!window.bootPlugins) window.bootPlugins = [];
  window.bootPlugins.push(setup);
  // if IITC has already booted, immediately run the 'setup' function
  if(window.iitcLoaded && typeof setup === 'function') setup();
} // wrapper end
// inject code into site context
var script = document.createElement('script');
var info = {};
if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) info.script = { version: GM_info.script.version, name: GM_info.script.name, description: GM_info.script.description };
script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));
(document.body || document.head || document.documentElement).appendChild(script);
<commit_msg>fix cache<commit_after>// ==UserScript==
// @id             iitc-plugin-keys-list@isnot
// @name           IITC plugin: Keys List
// @category       Keys
// @version        0.3.20160818
// @namespace      https://github.com/jonatkins/ingress-intel-total-conversion
// @author         isnot
// @updateURL      none
// @downloadURL    none
// @description    [iitc-plugins] Export the manually entered key counts from the 'keys' plugin.
// @include        https://www.ingress.com/intel*
// @include        http://www.ingress.com/intel*
// @match          https://www.ingress.com/intel*
// @match          http://www.ingress.com/intel*
// @include        https://www.ingress.com/mission/*
// @include        http://www.ingress.com/mission/*
// @match          https://www.ingress.com/mission/*
// @match          http://www.ingress.com/mission/*
// @grant          none
// ==/UserScript==

function wrapper(plugin_info) {
  // ensure plugin framework is there, even if iitc is not yet loaded
  if (typeof window.plugin !== 'function') window.plugin = function() {};

  // PLUGIN START ////////////////////////////////////////////////////////

  // if the Keys/Cache plugin is not available, quit now
  if (!window.plugin.keys) {
    return console.warn("[KeysList] This plugin is dependent on the Keys plugin being present.");
  }
  if (!window.plugin.cachePortalDetailsOnMap) {
    return console.warn("[KeysList] This plugin is dependent on the Cache plugin being present.");
  }

  // Expand Cache BEGIN //////////////////////////////////////////////////////////
  var cache = window.plugin.cachePortalDetailsOnMap;
  cache.KEY_LOCALSTRAGE = 'plugin-cache-local-v1';

  cache.getPortalByGuid = function (guid) {
    var portal_cache = cache.cache[guid];
    console.log('==KeysList gpbg ' + portal_cache + typeof portal_cache);
    if (typeof portal_cache === 'object') {
      return JSON.parse(portal_cache.ent);
    }
  };

  cache.storeToLocal = function () {
    localStorage.setItem(cache.KEY_LOCALSTRAGE, JSON.stringify(cache.cache));
    console.log('plugin-cache-local: storeToLocal ' + cache.cache.length);
  };

  cache.loadFromLocal = function () {
    // if an existing portal cache, load it
    var raw = window.localStorage[cache.KEY_LOCALSTRAGE];
    console.log('plugin-cache-local: loadFromLocal ' + typeof raw);
    if (typeof raw === 'object') {
      cache.merge(JSON.parse(raw));
      console.log('plugin-cache-local: loadFromLocal ' + cache.cache.length);
    } else {
      // make a new cache
      window.localStorage[cache.KEY_LOCALSTRAGE] = "{}";
      console.log('plugin-cache-local: init');
    }
  };

  cache.merge = function (inbound) {
    if (cache.cache.length < 1) {
      cache.cache = inbound;
      return inbound.length;
    }

    for (var x in Object.keys(inbound)) {
      cache.cache[x] = inbound[x];
    }
    return cache.cache.length;
  };

  // Expand Cache END //////////////////////////////////////////////////////////

  // use own namespace for plugin
  window.plugin.keysList = function() {};
  var self = window.plugin.keysList;
  self.listAll = [];

  // fetch a portal name from a cached list if available
  self.getPortalDetails = function getPortalDetails(key) {
    var name = "(not detected)";
    var latLng = '0,0';
    var imageUrl = '';

    // try plugin cache
    var portal_cache = cache.getPortalByGuid(key.guid);
    if (typeof portal_cache === 'object') {
      //name = portal_cache.name;
      console.log('==KsysList pc ' + portal_cache + Object.keys(portal_cache).join(' '));
    }

    var data = (window.portals[key.guid] && window.portals[key.guid].options.data) || window.portalDetail.get(key.guid) || null;
    if (data) {
      console.log('==KsysList pd ' + data.title);
      if (data.title) name = data.title;
      imageUrl = window.fixPortalImageUrl(data.image);
      if (imageUrl.indexOf('//') === 1) {
        imageUrl = 'http:' + imageUrl;
      }
      if (imageUrl.indexOf(DEFAULT_PORTAL_IMG) !== -1) {
        imageUrl = '';
      }
    }

    var hLatLng = window.findPortalLatLng(key.guid);
    if (hLatLng) {
      latLng = hLatLng.lat + ',' + hLatLng.lng;
    }

    key.name = name;
    key.latLng = latLng;
    key.imageUrl = imageUrl;
    if (latLng === '0,0') {
      key.intelMapUrl = '';
    } else {
      key.intelMapUrl = 'https://www.ingress.com/intel?ll=' + latLng + '&z=17&pll=' + latLng;
    }

    return key;
  };

  self.csvValue = function(str) {
    if (str) {
      return '"' + str.replace("/\"/g", '""') + '"';
    } else {
      return '';
    }
  };

  self.eachKey = function(key) {
    if (key.count > 0) {
      key = self.getPortalDetails(key);
      var csvline = [
        self.csvValue(key.name),
        parseInt(key.count, 10),
        self.csvValue(key.latLng),
        self.csvValue(key.intelMapUrl),
        self.csvValue(key.imageUrl),
        key.guid
      ];
      self.listAll.push(csvline.join(","));
    }
  };

  self.renderList = function() {
    self.listAll = [];

    $.each(plugin.keys.keys, function(key, count) {
      self.eachKey({"guid": key, "count": count});
    });

    var html = '
KeysList for ' + window.PLAYER.nickname + ' ' + self.listAll.length + 'portals of keys. ' + new Date().toISOString() +
        '
<textarea cols="78" rows="20">name,count,latlng,url,image,guid' + "\n" + self.listAll.join("\n") + '</textarea>';
    dialog({
      title: 'KeysList',
      html: html,
      width: 600,
      position: {my: 'right center', at: 'center-60 center', of: window, collision: 'fit'}
    });
    console.log("==KeysList " + window.PLAYER.nickname + " " + self.listAll.length + " " + new Date().toISOString());
  };

  var setup = function() {
    // console.log("==KeysList setup ");
    $('#toolbox').append('KeysListCsv');
    addHook('iitcLoaded',        window.plugin.cachePortalDetailsOnMap.loadFromLocal());
    addHook('mapDataRefreshEnd', window.plugin.cachePortalDetailsOnMap.storeToLocal());
  };

  // PLUGIN END //////////////////////////////////////////////////////////

  setup.info = plugin_info; //add the script info data to the function as a property
  if(!window.bootPlugins) window.bootPlugins = [];
  window.bootPlugins.push(setup);
  // if IITC has already booted, immediately run the 'setup' function
  if(window.iitcLoaded && typeof setup === 'function') setup();
} // wrapper end
// inject code into site context
var script = document.createElement('script');
var info = {};
if (typeof GM_info !== 'undefined' && GM_info && GM_info.script) info.script = { version: GM_info.script.version, name: GM_info.script.name, description: GM_info.script.description };
script.appendChild(document.createTextNode('('+ wrapper +')('+JSON.stringify(info)+');'));
(document.body || document.head || document.documentElement).appendChild(script);
<|endoftext|>


<commit_before>window.FactsView = Backbone.CollectionView.extend({
  tagName: "div",
  className: "facts",
  containerSelector: ".facts",
  modelView: FactView,
  _loading: true,
  _timestamp: undefined,
  _previousLength: -1,
  views: {},
  events: {
    "submit #create_fact_for_channel": "createFact",
    "focus #create_fact_for_channel textarea": "openCreateFactForm",
    "click #create_fact_for_channel .create_factlink .close": "closeCreateFactForm",
    "click #create_fact_for_channel": "focusCreateFactlink",
    "click #create_fact_for_channel .inset-icon.icon-pen": "toggleTitleField",
    "click #create_fact_for_channel .inset-icon.icon-chain": "toggleURLField",
    "click #create_fact_for_channel .input-box": "focusField"
  },

  initialize: function(options) {
    this.useTemplate("channels", "_facts");

    var self = this;

    this.collection.bind('add', this.add, this);
    this.collection.bind('reset', this.reset, this);
    this.collection.bind('remove', this.removeOne, this);

    //TODO split this into two views, one for channels, one for searchresults
    if(options.channel !== undefined ) {
      this.$el.html(Mustache.to_html(this.tmpl,options.channel.toJSON(), this.partials));
    } else {
      this.$el.html(Mustache.to_html(this.tmpl, {}, this.partials));
    }

    this.$el.find('.icon-pen').tooltip({ title: 'Add a title to this Factlink'});
    this.$el.find('.icon-chain').tooltip({ title: 'Add a source (url) to this Factlink'});

    this.bindScroll();
  },

  createFact: function (e) {
    var self = this;
    var $form = this.$el.find('form');

    var $textarea = $form.find('textarea[name=fact]');
    var $url = $form.find('input[name=url]');
    var $title = $form.find('input[name=title]');
    var $submit = $form.find('button');

    e.preventDefault();

    $form.find(':input').prop('disabled', true);

    $.ajax({
      url: this.collection.url(),
      type: "POST",
      data: {
        displaystring: $textarea.val(),
        title: $title.val(),
        url: $url.val()
      },
      success: function(data) {
        var fact = new Fact(data);

        var a = self.collection.unshift(fact);

        self.views[fact.cid].highlight();

        $form.find(':input').val('').prop('disabled',false);

        self.closeCreateFactForm();
      }
    });
  },

  focusField: function (e) {
    $(e.target).closest('input-box').find(':input').focus();
  },

  openCreateFactForm: function () {  this.$el.find('form').addClass('active'); },

  closeCreateFactForm: function (e) {
    this.$el.find('form')
      .removeClass('active show-url show-title')
      .filter(':input').val('');

    e && e.stopPropagation();
  },

  toggleTitleField: function (e) {
    var $form = this.$el.find('form');

    $form.toggleClass('show-title');

    $form.hasClass('show-title') && $form.addClass('active').find('.add-title>input').focus();

    e.stopPropagation();
  },

  toggleURLField: function (e) {
    var $form = this.$el.find('form');

    $form.toggleClass('show-url');

    $form.hasClass('show-url') && $form.addClass('active').find('.add-url>input').focus();

    e.stopPropagation();
  },

  focusCreateFactlink: function (e) {
    var $target = $(e.target);

    ! $target.is(':input') && $(e.target).closest('form').find('textarea').focus();
  },

  removeOne: function (fact) {
    this.views[fact.cid].remove();
  },

  render: function() {
    var self = this;

    if (this.collection.length === 0 && !this._loading) {
      this.showNoFacts();
    } else {
      this.collection.forEach(function(fact) {
        self.add(fact);
      });
    }

    if ( this._previousLength === this.collection.length ) {
      this.hasMore = false;
    } else {
      this._previousLength = this.collection.length;
    }

    this.loadMore();

    return this;
  },

  remove: function() {
    Backbone.View.prototype.remove.apply(this);

    this.unbindScroll();
  },

  beforeReset: function(e){
    this.stopLoading();
  },

  moreNeeded: function() {
    var bottomOfTheViewport = window.pageYOffset + window.innerHeight;
    var bottomOfEl = this.$el.offset().top + this.$el.outerHeight();

    if ( this.hasMore ) {
      if ( bottomOfEl < bottomOfTheViewport ) {
        return true;
      } else if ($(document).height() - ($(window).scrollTop() + $(window).height()) < 700) {
        return true;
      }
    }

    return false;
  },

  loadMore: function() {
    var self = this;
    var lastModel = self.collection.models[(self.collection.length - 1) || 0];
    var new_timestamp = (lastModel ? lastModel.get('timestamp') : 0);

     if ( self.moreNeeded() && ! self._loading && self._timestamp !== new_timestamp ) {
      self.setLoading();

      self._timestamp = new_timestamp;

      self.collection.fetch({
        add: true,
        data: {
          timestamp: self._timestamp
        },
        success: function() {
          self.stopLoading();
          self.loadMore();
        },
        error: function() {
          self.stopLoading();
          self.hasMore = false;
        }
      });
    }
  },

  hasMore: true,

  showNoFacts: function() {
    this.$el.find('div.no_facts').show();
  },

  hideNoFacts: function() {
    this.$el.find('div.no_facts').hide();
  },

  setLoading: function() {
    this._loading = true;
    this.$el.find('div.loading').show();
  },

  stopLoading: function() {
    this._loading = false;
    this.$el.find('div.loading').hide();
  },

  bindScroll: function() {
    var self = this;
    $(window).bind('scroll.' + this.cid, function MCBiggah() {
      self.loadMore.apply(self);
    });
  },

  unbindScroll: function() {
    $(window).unbind('scroll.' + this.cid);
  }
});
<commit_msg>Hide empty message when there is a fact added<commit_after>window.FactsView = Backbone.CollectionView.extend({
  tagName: "div",
  className: "facts",
  containerSelector: ".facts",
  modelView: FactView,
  _loading: true,
  _timestamp: undefined,
  _previousLength: -1,
  views: {},
  events: {
    "submit #create_fact_for_channel": "createFact",
    "focus #create_fact_for_channel textarea": "openCreateFactForm",
    "click #create_fact_for_channel .create_factlink .close": "closeCreateFactForm",
    "click #create_fact_for_channel": "focusCreateFactlink",
    "click #create_fact_for_channel .inset-icon.icon-pen": "toggleTitleField",
    "click #create_fact_for_channel .inset-icon.icon-chain": "toggleURLField",
    "click #create_fact_for_channel .input-box": "focusField"
  },

  initialize: function(options) {
    this.useTemplate("channels", "_facts");

    var self = this;

    this.collection.bind('add', this.add, this);
    this.collection.bind('reset', this.reset, this);
    this.collection.bind('remove', this.removeOne, this);

    //TODO split this into two views, one for channels, one for searchresults
    if(options.channel !== undefined ) {
      this.$el.html(Mustache.to_html(this.tmpl,options.channel.toJSON(), this.partials));
    } else {
      this.$el.html(Mustache.to_html(this.tmpl, {}, this.partials));
    }

    this.$el.find('.icon-pen').tooltip({ title: 'Add a title to this Factlink'});
    this.$el.find('.icon-chain').tooltip({ title: 'Add a source (url) to this Factlink'});

    this.bindScroll();
  },

  createFact: function (e) {
    var self = this;
    var $form = this.$el.find('form');

    var $textarea = $form.find('textarea[name=fact]');
    var $url = $form.find('input[name=url]');
    var $title = $form.find('input[name=title]');
    var $submit = $form.find('button');

    e.preventDefault();

    $form.find(':input').prop('disabled', true);

    $.ajax({
      url: this.collection.url(),
      type: "POST",
      data: {
        displaystring: $textarea.val(),
        title: $title.val(),
        url: $url.val()
      },
      success: function(data) {
        var fact = new Fact(data);

        var a = self.collection.unshift(fact);

        self.views[fact.cid].highlight();

        $form.find(':input').val('').prop('disabled',false);

        self.closeCreateFactForm();
      }
    });
  },

  focusField: function (e) {
    $(e.target).closest('input-box').find(':input').focus();
  },

  openCreateFactForm: function () {  this.$el.find('form').addClass('active'); },

  closeCreateFactForm: function (e) {
    this.$el.find('form')
      .removeClass('active show-url show-title')
      .filter(':input').val('');

    e && e.stopPropagation();
  },

  toggleTitleField: function (e) {
    var $form = this.$el.find('form');

    $form.toggleClass('show-title');

    $form.hasClass('show-title') && $form.addClass('active').find('.add-title>input').focus();

    e.stopPropagation();
  },

  toggleURLField: function (e) {
    var $form = this.$el.find('form');

    $form.toggleClass('show-url');

    $form.hasClass('show-url') && $form.addClass('active').find('.add-url>input').focus();

    e.stopPropagation();
  },

  focusCreateFactlink: function (e) {
    var $target = $(e.target);

    ! $target.is(':input') && $(e.target).closest('form').find('textarea').focus();
  },

  removeOne: function (fact) {
    this.views[fact.cid].remove();
  },

  render: function() {
    var self = this;

    if (this.collection.length === 0 && !this._loading) {
      this.showNoFacts();
    } else {
      this.collection.forEach(function(fact) {
        self.add(fact);
      });
    }

    if ( this._previousLength === this.collection.length ) {
      this.hasMore = false;
    } else {
      this._previousLength = this.collection.length;
    }

    this.loadMore();

    return this;
  },

  remove: function() {
    Backbone.View.prototype.remove.apply(this);

    this.unbindScroll();
  },

  beforeReset: function(e){
    this.stopLoading();
  },

  moreNeeded: function() {
    var bottomOfTheViewport = window.pageYOffset + window.innerHeight;
    var bottomOfEl = this.$el.offset().top + this.$el.outerHeight();

    if ( this.hasMore ) {
      if ( bottomOfEl < bottomOfTheViewport ) {
        return true;
      } else if ($(document).height() - ($(window).scrollTop() + $(window).height()) < 700) {
        return true;
      }
    }

    return false;
  },

  loadMore: function() {
    var self = this;
    var lastModel = self.collection.models[(self.collection.length - 1) || 0];
    var new_timestamp = (lastModel ? lastModel.get('timestamp') : 0);

     if ( self.moreNeeded() && ! self._loading && self._timestamp !== new_timestamp ) {
      self.setLoading();

      self._timestamp = new_timestamp;

      self.collection.fetch({
        add: true,
        data: {
          timestamp: self._timestamp
        },
        success: function() {
          self.stopLoading();
          self.loadMore();
        },
        error: function() {
          self.stopLoading();
          self.hasMore = false;
        }
      });
    }
  },

  hasMore: true,

  showNoFacts: function() {
    this.$el.find('div.no_facts').show();
  },

  hideNoFacts: function() {
    this.$el.find('div.no_facts').hide();
  },

  afterAdd: function () {
    this.hideNoFacts();
  },

  setLoading: function() {
    this._loading = true;
    this.$el.find('div.loading').show();
  },

  stopLoading: function() {
    this._loading = false;
    this.$el.find('div.loading').hide();
  },

  bindScroll: function() {
    var self = this;
    $(window).bind('scroll.' + this.cid, function MCBiggah() {
      self.loadMore.apply(self);
    });
  },

  unbindScroll: function() {
    $(window).unbind('scroll.' + this.cid);
  }
});
<|endoftext|>


<commit_before>/* FileSaver.js
 * A saveAs() FileSaver implementation.
 * 1.3.2
 * 2016-06-16 18:25:19
 *
 * By Eli Grey, http://eligrey.com
 * License: MIT
 *   See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
 */

/*global self */
/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */

/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */

var saveAs = saveAs || (function(view) {
	"use strict";
	// IE <10 is explicitly unsupported
	if (typeof view === "undefined" || typeof navigator !== "undefined" && /MSIE [1-9]\./.test(navigator.userAgent)) {
		return;
	}
	var
		  doc = view.document
		  // only get URL when necessary in case Blob.js hasn't overridden it yet
		, get_URL = function() {
			return view.URL || view.webkitURL || view;
		}
		, save_link = doc.createElementNS("http://www.w3.org/1999/xhtml", "a")
		, can_use_save_link = "download" in save_link
		, click = function(node) {
			var event = new MouseEvent("click");
			node.dispatchEvent(event);
		}
		, is_safari = /constructor/i.test(view.HTMLElement) || view.safari
		, is_chrome_ios =/CriOS\/[\d]+/.test(navigator.userAgent)
		, throw_outside = function(ex) {
			(view.setImmediate || view.setTimeout)(function() {
				throw ex;
			}, 0);
		}
		, force_saveable_type = "application/octet-stream"
		// the Blob API is fundamentally broken as there is no "downloadfinished" event to subscribe to
		, arbitrary_revoke_timeout = 1000 * 40 // in ms
		, revoke = function(file) {
			var revoker = function() {
				if (typeof file === "string") { // file is an object URL
					get_URL().revokeObjectURL(file);
				} else { // file is a File
					file.remove();
				}
			};
			setTimeout(revoker, arbitrary_revoke_timeout);
		}
		, dispatch = function(filesaver, event_types, event) {
			event_types = [].concat(event_types);
			var i = event_types.length;
			while (i--) {
				var listener = filesaver["on" + event_types[i]];
				if (typeof listener === "function") {
					try {
						listener.call(filesaver, event || filesaver);
					} catch (ex) {
						throw_outside(ex);
					}
				}
			}
		}
		, auto_bom = function(blob) {
			// prepend BOM for UTF-8 XML and text/* types (including HTML)
			// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
			if (/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
				return new Blob([String.fromCharCode(0xFEFF), blob], {type: blob.type});
			}
			return blob;
		}
		, FileSaver = function(blob, name, no_auto_bom) {
			if (!no_auto_bom) {
				blob = auto_bom(blob);
			}
			// First try a.download, then web filesystem, then object URLs
			var
				  filesaver = this
				, type = blob.type
				, force = type === force_saveable_type
				, object_url
				, dispatch_all = function() {
					dispatch(filesaver, "writestart progress write writeend".split(" "));
				}
				// on any filesys errors revert to saving with object URLs
				, fs_error = function() {
					if ((is_chrome_ios || (force && is_safari)) && view.FileReader) {
						// Safari doesn't allow downloading of blob urls
						var reader = new FileReader();
						reader.onloadend = function() {
							var url = is_chrome_ios ? reader.result : reader.result.replace(/^data:[^;]*;/, 'data:attachment/file;');
							var popup = view.open(url, '_blank');
							if(!popup) view.location.href = url;
							url=undefined; // release reference before dispatching
							filesaver.readyState = filesaver.DONE;
							dispatch_all();
						};
						reader.readAsDataURL(blob);
						filesaver.readyState = filesaver.INIT;
						return;
					}
					// don't create more object URLs than needed
					if (!object_url) {
						object_url = get_URL().createObjectURL(blob);
					}
					if (force) {
						view.location.href = object_url;
					} else {
						var opened = view.open(object_url, "_blank");
						if (!opened) {
							// Apple does not allow window.open, see https://developer.apple.com/library/safari/documentation/Tools/Conceptual/SafariExtensionGuide/WorkingwithWindowsandTabs/WorkingwithWindowsandTabs.html
							view.location.href = object_url;
						}
					}
					filesaver.readyState = filesaver.DONE;
					dispatch_all();
					revoke(object_url);
				}
			;
			filesaver.readyState = filesaver.INIT;

			if (can_use_save_link) {
				object_url = get_URL().createObjectURL(blob);
				setTimeout(function() {
					save_link.href = object_url;
					save_link.download = name;
					click(save_link);
					dispatch_all();
					revoke(object_url);
					filesaver.readyState = filesaver.DONE;
				});
				return;
			}

			fs_error();
		}
		, FS_proto = FileSaver.prototype
		, saveAs = function(blob, name, no_auto_bom) {
			return new FileSaver(blob, name || blob.name || "download", no_auto_bom);
		}
	;
	// IE 10+ (native saveAs)
	if (typeof navigator !== "undefined" && navigator.msSaveOrOpenBlob) {
		return function(blob, name, no_auto_bom) {
			name = name || blob.name || "download";

			if (!no_auto_bom) {
				blob = auto_bom(blob);
			}
			return navigator.msSaveOrOpenBlob(blob, name);
		};
	}

	FS_proto.abort = function(){};
	FS_proto.readyState = FS_proto.INIT = 0;
	FS_proto.WRITING = 1;
	FS_proto.DONE = 2;

	FS_proto.error =
	FS_proto.onwritestart =
	FS_proto.onprogress =
	FS_proto.onwrite =
	FS_proto.onabort =
	FS_proto.onerror =
	FS_proto.onwriteend =
		null;

	return saveAs;
}(
	   typeof self !== "undefined" && self
	|| typeof window !== "undefined" && window
	|| this.content
));
// `self` is undefined in Firefox for Android content script context
// while `this` is nsIContentFrameMessageManager
// with an attribute `content` that corresponds to the window

if (typeof module !== "undefined" && module.exports) {
  module.exports.saveAs = saveAs;
} else if ((typeof define !== "undefined" && define !== null) && (define.amd !== null)) {
  define("FileSaver.js", function() {
    return saveAs;
  });
}
<commit_msg>Removed duplicate FileServer library.<commit_after><|endoftext|>