<commit_before>/*
 * Copyright (C) 2015 Actor LLC. <https://actor.im>
 */

export default {

  // Auth

  requestSms(phone) {
    return new Promise((resolve, reject) => {
      window.messenger.requestSms(phone, resolve, reject);
    });
  },

  requestCodeEmail(email) {
    return new Promise((resolve, reject) => {
      window.messenger.requestCodeEmail(email, resolve, reject);
    });
  },

  sendCode(code) {
    return new Promise((resolve, reject) => {
      window.messenger.sendCode(code, resolve, reject);
    });
  },

  signUp(name) {
    return new Promise((resolve, reject) => {
      window.messenger.signUp(name, resolve, reject);
    });
  },

  isLoggedIn() {
    return window.messenger.isLoggedIn();
  },

  // Bindings

  bindDialogs(callback) {
    window.messenger.bindDialogs(callback);
  },

  unbindDialogs(callback) {
    window.messenger.unbindDialogs(callback);
  },

  bindGroupDialogs(callback) {
    window.messenger.bindGroupDialogs(callback);
  },

  unbindGroupDialogs(callback) {
    window.messenger.unbindGroupDialogs(callback);
  },

  bindChat(peer, callback) {
    window.messenger.bindChat(peer, callback);
  },

  unbindChat(peer, callback) {
    window.messenger.unbindChat(peer, callback);
  },

  bindGroup(gid, callback) {
    window.messenger.bindGroup(gid, callback);
  },

  unbindGroup(gid, callback) {
    window.messenger.unbindGroup(gid, callback);
  },

  bindUser(uid, callback) {
    window.messenger.bindUser(uid, callback);
  },

  unbindUser(uid, callback) {
    window.messenger.unbindUser(uid, callback);
  },

  bindTyping(peer, callback) {
    window.messenger.bindTyping(peer, callback);
  },

  unbindTyping(peer, callback) {
    window.messenger.unbindTyping(peer, callback);
  },

  bindContacts(peer, callback) {
    window.messenger.bindContacts(peer, callback);
  },

  unbindContacts(peer, callback) {
    window.messenger.unbindContacts(peer, callback);
  },

  bindConnectState(callback) {
    window.messenger.bindConnectState(callback);
  },

  unbindConnectState(callback) {
    window.messenger.unbindConnectState(callback);
  },

  bindGlobalCounter(callback) {
    window.messenger.bindGlobalCounter(callback);
  },

  unbindGlobalCounter(callback) {
    window.messenger.unbindGlobalCounter(callback);
  },

  bindTempGlobalCounter(callback) {
    window.messenger.bindTempGlobalCounter(callback);
  },

  unbindTempGlobalCounter(callback) {
    window.messenger.unbindTempGlobalCounter(callback);
  },

  getUser(uid) {
    return window.messenger.getUser(uid);
  },

  getUid() {
    return window.messenger.getUid();
  },

  getGroup(gid) {
    return window.messenger.getGroup(gid);
  },

  getInviteUrl(gid) {
    return window.messenger.getInviteLink(gid);
  },

  sendTextMessage(peer, text) {
    window.messenger.sendMessage(peer, text);
  },

  sendFileMessage(peer, file) {
    window.messenger.sendFile(peer, file);
  },

  sendPhotoMessage(peer, photo) {
    window.messenger.sendPhoto(peer, photo);
  },

  sendClipboardPhotoMessage(peer, photo) {
    window.messenger.sendClipboardPhoto(peer, photo);
  },

  onMessageShown(peer, message) {
    window.messenger.onMessageShown(peer, message);
  },

  onChatEnd (peer) {
    window.messenger.onChatEnd(peer);
  },

  onDialogsEnd () {
    window.messenger.onDialogsEnd();
  },

  onConversationOpen(peer) {
    window.messenger.onConversationOpen(peer);
  },

  onConversationClosed(peer) {
    window.messenger.onConversationClosed(peer);
  },

  onTyping(peer) {
    window.messenger.onTyping(peer);
  },

  onAppHidden() {
    window.messenger.onAppHidden();
  },

  onAppVisible() {
    window.messenger.onAppVisible();
  },

  editMyName(string) {
    window.messenger.editMyName(string);
  },

  addContact(uid) {
    window.messenger.addContact(uid);
  },

  removeContact(uid) {
    window.messenger.removeContact(uid);
  },

  // Groups

  joinGroupViaLink (url) {
    return window.messenger.joinGroupViaLink(url);
  },

  leaveGroup(gid) {
    return window.messenger.leaveGroup(gid);
  },

  createGroup(title, avatar, userIds) {
    return window.messenger.createGroup(title, avatar, userIds);
  },

  kickMember(gid, uid) {
    return window.messenger.kickMember(gid, uid);
  },

  inviteMember(gid, uid) {
    return window.messenger.inviteMember(gid, uid);
  },

  getIntegrationToken(gid) {
    return window.messenger.getIntegrationToken(gid);
  },

  loadDraft(peer) {
    return window.messenger.loadDraft(peer);
  },

  saveDraft(peer, draft) {
    if (draft !== null) {
      window.messenger.saveDraft(peer, draft);
    }
  },

  getUserPeer(uid) {
    return window.messenger.getUserPeer(uid);
  },

  getGroupPeer(gid) {
    return window.messenger.getGroupPeer(gid);
  },

  hideChat(peer) {
    return window.messenger.hideChat(peer);
  },

  // Mentions

  findMentions(gid, query = '') {
    return window.messenger.findMentions(gid, query);
  },

  // Nickname

  editMyNick(string) {
    window.messenger.editMyNick(string)
  },

  deleteChat(peer) {
    return window.messenger.deleteChat(peer);
  },

  clearChat(peer) {
    return window.messenger.clearChat(peer);
  },

  editMyAbout(about) {
    return window.messenger.editMyAbout(about);
  },

  editGroupTitle(gid, title) {
    return window.messenger.editGroupTitle(gid, title);
  },

  editGroupAbout(gid, title) {
    return window.messenger.editGroupAbout(gid, title);
  },

  renderMarkdown(markdownText) {
    return window.messenger.renderMarkdown(markdownText);
  },

  // Settings

  changeNotificationsEnabled(peer, isEnabled) {
    window.messenger.changeNotificationsEnabled(peer, isEnabled);
  },

  isNotificationsEnabled(peer) {
    return window.messenger.isNotificationsEnabled(peer);
  },

  isSendByEnterEnabled() {
    return window.messenger.isSendByEnterEnabled();
  },

  changeSendByEnter(isEnabled) {
    window.messenger.changeSendByEnter(isEnabled);
  },

  isGroupsNotificationsEnabled() {
    return window.messenger.isGroupsNotificationsEnabled();
  },

  changeGroupNotificationsEnabled(isEnabled) {
    window.messenger.changeGroupNotificationsEnabled(isEnabled);
  },

  isOnlyMentionNotifications() {
    return window.messenger.isOnlyMentionNotifications();
  },

  changeIsOnlyMentionNotifications(isEnabled) {
    window.messenger.changeIsOnlyMentionNotifications(isEnabled);
  },

  isSoundEffectsEnabled() {
    return window.messenger.isSoundEffectsEnabled();
  },

  changeSoundEffectsEnabled(isEnabled) {
    window.messenger.changeSoundEffectsEnabled(isEnabled);
  },

  isShowNotificationsTextEnabled() {
    return window.messenger.isShowNotificationsTextEnabled();
  },

  changeIsShowNotificationTextEnabled(isEnabled) {
    window.messenger.changeIsShowNotificationTextEnabled(isEnabled);
  },

  loadSessions() {
    return window.messenger.loadSessions();
  },

  terminateSession(id) {
    return window.messenger.terminateSession(id);
  },

  terminateAllSessions() {
    return window.messenger.terminateAllSessions();
  },

  changeMyAvatar(avatar) {
    window.messenger.changeMyAvatar(avatar);
  },

  changeGroupAvatar(gid, avatar) {
    window.messenger.changeGroupAvatar(gid, avatar);
  },

  removeMyAvatar() {
    window.messenger.removeMyAvatar();
  },

  removeGroupAvatar(gid) {
    window.messenger.removeGroupAvatar(gid);
  },

  // Search

  findGroups(query) {
    return window.messenger.findGroups(query);
  },

  findUsers(phone) {
    return window.messenger.findUsers(phone.toString());
  },

  // Messages

  deleteMessage(peer, rid) {
    return window.messenger.deleteMessage(peer, rid);
  },

  addLike(peer, rid) {
    return window.messenger.addLike(peer, rid);
  },

  removeLike(peer, rid) {
    return window.messenger.removeLike(peer, rid);
  },

  // Search

  bindSearch(callback) {
    window.messenger.bindSearch(callback);
  },

  unbindSearch(callback) {
    window.messenger.unbindSearch(callback);
  },

  findAllText(peer, query) {
    return window.messenger.findAllText(peer, query);
  },

  findAllDocs(peer) {
    return window.messenger.findAllDocs(peer);
  },

  findAllLinks(peer) {
    return window.messenger.findAllLinks(peer);
  },

  findAllPhotos(peer) {
    return window.messenger.findAllPhotos(peer);
  },

  handleLinkClick(event) {
    messenger.handleLinkClick(event)
  },

  isElectron() {
    return window.messenger.isElectron();
  },

  favoriteChat(peer) {
    return window.messenger.favoriteChat(peer);
  },

  unfavoriteChat(peer) {
    return window.messenger.unfavoriteChat(peer);
  }
}
<commit_msg>wip(web): add online bindings to library wrapper<commit_after>/*
 * Copyright (C) 2015 Actor LLC. <https://actor.im>
 */

export default {

  // Auth

  requestSms(phone) {
    return new Promise((resolve, reject) => {
      window.messenger.requestSms(phone, resolve, reject);
    });
  },

  requestCodeEmail(email) {
    return new Promise((resolve, reject) => {
      window.messenger.requestCodeEmail(email, resolve, reject);
    });
  },

  sendCode(code) {
    return new Promise((resolve, reject) => {
      window.messenger.sendCode(code, resolve, reject);
    });
  },

  signUp(name) {
    return new Promise((resolve, reject) => {
      window.messenger.signUp(name, resolve, reject);
    });
  },

  isLoggedIn() {
    return window.messenger.isLoggedIn();
  },

  // Bindings

  bindDialogs(callback) {
    window.messenger.bindDialogs(callback);
  },

  unbindDialogs(callback) {
    window.messenger.unbindDialogs(callback);
  },

  bindGroupDialogs(callback) {
    window.messenger.bindGroupDialogs(callback);
  },

  unbindGroupDialogs(callback) {
    window.messenger.unbindGroupDialogs(callback);
  },

  bindChat(peer, callback) {
    window.messenger.bindChat(peer, callback);
  },

  unbindChat(peer, callback) {
    window.messenger.unbindChat(peer, callback);
  },

  bindGroup(gid, callback) {
    window.messenger.bindGroup(gid, callback);
  },

  unbindGroup(gid, callback) {
    window.messenger.unbindGroup(gid, callback);
  },

  bindUser(uid, callback) {
    window.messenger.bindUser(uid, callback);
  },

  unbindUser(uid, callback) {
    window.messenger.unbindUser(uid, callback);
  },

  bindTyping(peer, callback) {
    window.messenger.bindTyping(peer, callback);
  },

  unbindTyping(peer, callback) {
    window.messenger.unbindTyping(peer, callback);
  },

  bindContacts(peer, callback) {
    window.messenger.bindContacts(peer, callback);
  },

  unbindContacts(peer, callback) {
    window.messenger.unbindContacts(peer, callback);
  },

  bindConnectState(callback) {
    window.messenger.bindConnectState(callback);
  },

  unbindConnectState(callback) {
    window.messenger.unbindConnectState(callback);
  },

  bindGlobalCounter(callback) {
    window.messenger.bindGlobalCounter(callback);
  },

  unbindGlobalCounter(callback) {
    window.messenger.unbindGlobalCounter(callback);
  },

  bindTempGlobalCounter(callback) {
    window.messenger.bindTempGlobalCounter(callback);
  },

  unbindTempGlobalCounter(callback) {
    window.messenger.unbindTempGlobalCounter(callback);
  },

  bindUserOnline(uid, callback) {
    window.messenger.bindUserOnline(uid, callback);
  },

  unbindUserOnline(uid, callback) {
    window.messenger.unbindUserOnline(uid, callback);
  },

  bindGroupOnline(gid, callback) {
    window.messenger.bindGroupOnline(gid, callback);
  },

  unbindGroupOnline(gid, callback) {
    window.messenger.unbindGroupOnline(gid, callback);
  },

  getUser(uid) {
    return window.messenger.getUser(uid);
  },

  getUid() {
    return window.messenger.getUid();
  },

  getGroup(gid) {
    return window.messenger.getGroup(gid);
  },

  getInviteUrl(gid) {
    return window.messenger.getInviteLink(gid);
  },

  sendTextMessage(peer, text) {
    window.messenger.sendMessage(peer, text);
  },

  sendFileMessage(peer, file) {
    window.messenger.sendFile(peer, file);
  },

  sendPhotoMessage(peer, photo) {
    window.messenger.sendPhoto(peer, photo);
  },

  sendClipboardPhotoMessage(peer, photo) {
    window.messenger.sendClipboardPhoto(peer, photo);
  },

  onMessageShown(peer, message) {
    window.messenger.onMessageShown(peer, message);
  },

  onChatEnd (peer) {
    window.messenger.onChatEnd(peer);
  },

  onDialogsEnd () {
    window.messenger.onDialogsEnd();
  },

  onConversationOpen(peer) {
    window.messenger.onConversationOpen(peer);
  },

  onConversationClosed(peer) {
    window.messenger.onConversationClosed(peer);
  },

  onTyping(peer) {
    window.messenger.onTyping(peer);
  },

  onAppHidden() {
    window.messenger.onAppHidden();
  },

  onAppVisible() {
    window.messenger.onAppVisible();
  },

  editMyName(string) {
    window.messenger.editMyName(string);
  },

  addContact(uid) {
    window.messenger.addContact(uid);
  },

  removeContact(uid) {
    window.messenger.removeContact(uid);
  },

  // Groups

  joinGroupViaLink (url) {
    return window.messenger.joinGroupViaLink(url);
  },

  leaveGroup(gid) {
    return window.messenger.leaveGroup(gid);
  },

  createGroup(title, avatar, userIds) {
    return window.messenger.createGroup(title, avatar, userIds);
  },

  kickMember(gid, uid) {
    return window.messenger.kickMember(gid, uid);
  },

  inviteMember(gid, uid) {
    return window.messenger.inviteMember(gid, uid);
  },

  getIntegrationToken(gid) {
    return window.messenger.getIntegrationToken(gid);
  },

  loadDraft(peer) {
    return window.messenger.loadDraft(peer);
  },

  saveDraft(peer, draft) {
    if (draft !== null) {
      window.messenger.saveDraft(peer, draft);
    }
  },

  getUserPeer(uid) {
    return window.messenger.getUserPeer(uid);
  },

  getGroupPeer(gid) {
    return window.messenger.getGroupPeer(gid);
  },

  hideChat(peer) {
    return window.messenger.hideChat(peer);
  },

  // Mentions

  findMentions(gid, query = '') {
    return window.messenger.findMentions(gid, query);
  },

  // Nickname

  editMyNick(string) {
    window.messenger.editMyNick(string)
  },

  deleteChat(peer) {
    return window.messenger.deleteChat(peer);
  },

  clearChat(peer) {
    return window.messenger.clearChat(peer);
  },

  editMyAbout(about) {
    return window.messenger.editMyAbout(about);
  },

  editGroupTitle(gid, title) {
    return window.messenger.editGroupTitle(gid, title);
  },

  editGroupAbout(gid, title) {
    return window.messenger.editGroupAbout(gid, title);
  },

  renderMarkdown(markdownText) {
    return window.messenger.renderMarkdown(markdownText);
  },

  // Settings

  changeNotificationsEnabled(peer, isEnabled) {
    window.messenger.changeNotificationsEnabled(peer, isEnabled);
  },

  isNotificationsEnabled(peer) {
    return window.messenger.isNotificationsEnabled(peer);
  },

  isSendByEnterEnabled() {
    return window.messenger.isSendByEnterEnabled();
  },

  changeSendByEnter(isEnabled) {
    window.messenger.changeSendByEnter(isEnabled);
  },

  isGroupsNotificationsEnabled() {
    return window.messenger.isGroupsNotificationsEnabled();
  },

  changeGroupNotificationsEnabled(isEnabled) {
    window.messenger.changeGroupNotificationsEnabled(isEnabled);
  },

  isOnlyMentionNotifications() {
    return window.messenger.isOnlyMentionNotifications();
  },

  changeIsOnlyMentionNotifications(isEnabled) {
    window.messenger.changeIsOnlyMentionNotifications(isEnabled);
  },

  isSoundEffectsEnabled() {
    return window.messenger.isSoundEffectsEnabled();
  },

  changeSoundEffectsEnabled(isEnabled) {
    window.messenger.changeSoundEffectsEnabled(isEnabled);
  },

  isShowNotificationsTextEnabled() {
    return window.messenger.isShowNotificationsTextEnabled();
  },

  changeIsShowNotificationTextEnabled(isEnabled) {
    window.messenger.changeIsShowNotificationTextEnabled(isEnabled);
  },

  loadSessions() {
    return window.messenger.loadSessions();
  },

  terminateSession(id) {
    return window.messenger.terminateSession(id);
  },

  terminateAllSessions() {
    return window.messenger.terminateAllSessions();
  },

  changeMyAvatar(avatar) {
    window.messenger.changeMyAvatar(avatar);
  },

  changeGroupAvatar(gid, avatar) {
    window.messenger.changeGroupAvatar(gid, avatar);
  },

  removeMyAvatar() {
    window.messenger.removeMyAvatar();
  },

  removeGroupAvatar(gid) {
    window.messenger.removeGroupAvatar(gid);
  },

  // Search

  findGroups(query) {
    return window.messenger.findGroups(query);
  },

  findUsers(phone) {
    return window.messenger.findUsers(phone.toString());
  },

  // Messages

  deleteMessage(peer, rid) {
    return window.messenger.deleteMessage(peer, rid);
  },

  addLike(peer, rid) {
    return window.messenger.addLike(peer, rid);
  },

  removeLike(peer, rid) {
    return window.messenger.removeLike(peer, rid);
  },

  // Search

  bindSearch(callback) {
    window.messenger.bindSearch(callback);
  },

  unbindSearch(callback) {
    window.messenger.unbindSearch(callback);
  },

  findAllText(peer, query) {
    return window.messenger.findAllText(peer, query);
  },

  findAllDocs(peer) {
    return window.messenger.findAllDocs(peer);
  },

  findAllLinks(peer) {
    return window.messenger.findAllLinks(peer);
  },

  findAllPhotos(peer) {
    return window.messenger.findAllPhotos(peer);
  },

  handleLinkClick(event) {
    messenger.handleLinkClick(event)
  },

  isElectron() {
    return window.messenger.isElectron();
  },

  favoriteChat(peer) {
    return window.messenger.favoriteChat(peer);
  },

  unfavoriteChat(peer) {
    return window.messenger.unfavoriteChat(peer);
  }
}
<|endoftext|>


<commit_before>angular.module('app').controller('createEventCtrl', function($scope, $http, $filter, $route, ngNotifier,$location,$interval,$animate,ngIdentity, ngUser,$log) {
$scope.identity = ngIdentity;

$animate.enabled(false, "div");
  // var draftInstance = $scope.draftInstance;
  // $log.debug("draftInstance", draftInstance);
$scope.allowSaveDrafts=false;
  var secondUnit = 1000;
  var autoSave;

  autoSave = $interval(function() {
    //$scope.checkDirty();
  }, 60 * secondUnit);

  $scope.$on('$destroy', function() {
    $log.debug($scope.eventdoc );
    if($scope.eventdoc.draftStatus)
    {
      if($scope.allowSaveDrafts)
      {
        $log.debug("saving");
        $scope.saveDraftEvent();
      }

    }
    $interval.cancel(autoSave);

  });

  $scope.topicValue = {};
  $scope.subTopicValue = {};
  $scope.userAssigned = {};

  $scope.users = [];

  $scope.eventdoc = {
    "eventName": "",
    "eventType": "",
    "eventInstanceId": "",
    "userCreated": "",
    "dateCreated": "",
    "draftStatus": true,
    "archiveStatus": false,
    categories: [{
      name: 'Web',
      "userAssigned": "",
      "statusCompleted": false,
      "dateCompleted": "",
      topics: [

      ]
    }, {
      name: 'TV',
      "userAssigned": "",
      "statusCompleted": false,
      "dateCompleted": "",
      topics: [

      ]
    }, {
      name: 'Print',
      "userAssigned": "",
      "statusCompleted": false,
      "dateCompleted": "",
      topics: [

      ]
    }, ]
  };

  if ($scope.draftInstance) {
    $scope.eventdoc = $scope.draftInstance;
  }

  $scope.eventTypes = ['Earthquake', 'Hurricane', 'Flood', 'Infectious Disease', 'Famine'] //hardcoded placeholder
    //$scope.date = new Date().getTime();
  $scope.date = new Date().getTime(); // need both date and time

  $scope.eventdoc.userCreated = {id:$scope.identity.currentUser._id, displayName: $scope.identity.currentUser.displayName};
  var previousData = angular.toJson($scope.eventdoc);

  $http.get('/api/users/analysts').then(function(res) {
  var analysts = res.data;
  for(var i=0; i < analysts.length; i++) {
    $scope.users.push({'id':analysts[i]._id, 'displayName':analysts[i].displayName });
    // $scope.users.push(analysts[i].displayName);
  }
  });

  $log.debug($scope.date);

  $scope.addTopic = function(category) {
    $log.debug(category);
    // if ($scope.eventdoc.categories.indexOf(category).topics.length > 10) {
    //   window.alert('You can\'t add more than 10 topics!');
    //   return;
    // }
    //var topicName = document.getElementById('topicName').value;
    var topicName = $scope.topicValue[category.name];
    if (topicName.length > 0) {
      category.topics.push({
        name: topicName,
        type: 'topic',
        subTopics: [],
        sortOrder: category.topics.length
      });

    }
    $scope.topicValue = {};
  };

  $scope.editTopic = function(topic) {
    topic.editing = true;
  };

  $scope.cancelEditingTopic = function(topic) {
    topic.editing = false;
  };

  $scope.saveTopic = function(topic) {
    // topic.save();
    topic.editing = false;
  };

  $scope.removeTopic = function(category, topic) {
    // if (window.confirm('Are you sure to remove this topic?')) {
    //   //topic.destroy();  //TODO
    // }
    $log.debug(category);
    $log.debug(topic);
    var index = category.topics.indexOf(topic);
    if (index > -1) {
      category.topics.splice(index, 1)[0];
    }
  };

  $scope.saveTopics = function() {
    for (var i = $scope.eventdoc.categories[0].topics.length - 1; i >= 0; i--) {
      var topic = $scope.eventdoc.categories[0].topics[i];
      topic.sortOrder = i + 1;
      // topic.save();
    }
  };

  $scope.addSubTopic = function(topic) {
    $log.debug(topic);
    if (!topic.newSubTopicName || topic.newSubTopicName.length === 0) {
      return;
    }
    topic.subTopics.push({
      name: topic.newSubTopicName,
      sortOrder: topic.subTopics.length,
      type: 'subTopic',
      bullets: []
    });
    topic.newSubTopicName = '';
    // topic.save();
  };

  $scope.removeSubTopic = function(topic, subTopic) {
    //if (window.confirm('Are you sure to remove this subTopic?')) {
    var index = topic.subTopics.indexOf(subTopic);
    if (index > -1) {
      topic.subTopics.splice(index, 1)[0];
    }
    // topic.save();
    //}
  };

  $scope.editSubTopic = function(subTopic) {
    $log.debug("edit sub topic");
    subTopic.editing = true;
  };

  // $scope.cancelEditingSubTopic = function(topic) {
  //   topic.editing = false;
  // };

  $scope.saveSubTopic = function(subTopic) {
    // topic.save();
    subTopic.editing = false;
  };

  $scope.options = {
    accept: function(sourceNode, destNodes, destIndex) {
      var data = sourceNode.$modelValue;
      var destType = destNodes.$element.attr('data-type');
      return (data.type == destType); // only accept the same type
    },
    dropped: function(event) {
      $log.debug(event);
      var sourceNode = event.source.nodeScope;
      var destNodes = event.dest.nodesScope;
      // update changes to server
      if (destNodes.isParent(sourceNode) && destNodes.$element.attr('data-type') == 'subTopic') { // If it moves in the same topic, then only update topic
        var topic = destNodes.$nodeScope.$modelValue;
        // topic.save();
      } else { // save all
        $scope.saveTopics();
      }
    },
    beforeDrop: function(event) {
      // if (!window.confirm('Are you sure you want to drop it here?')) {
      //   event.source.nodeScope.$$apply = false;
      // }
    }
  };

  $scope.createEvent = function() {
    $log.debug($scope.eventdoc.eventInstanceId);
    var minimumAssign = false;
    //var formattedEventInstanceId = 'EQSA-01'; //TODO: Create actual eventInstanceId do this on server-side?
    for(var i=0; i < $scope.eventdoc.categories.length; i++){
      if($scope.eventdoc.categories[i].userAssigned != '') {
        minimumAssign = true;
      }
    }
    $scope.eventdoc.dateCreated = $scope.date;
    $http.get('/api/events/duplicate/' + $scope.eventdoc.eventName).then(function(res) {
      //$log.debug(res.data.duplicate);
      if ($scope.eventdoc.eventName.trim() === '') {
        ngNotifier.notifyError('Event name cannot be blank');
      } else if ($scope.eventdoc.eventName.replace(/ /g, '').match(/^[0-9]+$/) != null) {
        ngNotifier.notifyError('Event name cannot contain only numbers');
      } else if (res.data.duplicate) {
        ngNotifier.notifyError('Cannot create event. Duplicate name');
      } else if ($scope.eventdoc.eventType === '') {
        ngNotifier.notifyError('Please select an event type');
      } else if (minimumAssign === false){
        ngNotifier.notifyError('You must assign atleast one category to an analyst');
      } else {

        $scope.eventdoc.dateCreated = $scope.date;
        $scope.eventdoc.draftStatus = false;
        // if (draftInstance)
        //   $scope.eventdoc._id = draftInstance._id;

        var partialId = genInstanceId($scope.eventdoc.eventName);

        $http.get('/api/events/getAvailEventId/' + partialId).then(function(res) {
          //       	$log.debug(partialId);
          //        $log.debug(res.data);
          if (res.data) {
            //var eventInstanceIdParts = res.data.eventInstanceId.split("-");
            //$scope.eventInstanceId= eventInstanceIdParts[0] + '-' + String('0'+(Number(eventInstanceIdParts[1]) + 1));
            if (res.data.length > 0) {
              //                $log.debug("ID alreADy prsent");
              $scope.eventdoc.eventInstanceId = partialId + "xx";
            } else {
              //                $log.debug("id available to be used");
              //                $log.debug(partialId);
              $scope.eventdoc.eventInstanceId = partialId;
            }

            //			$log.debug("eventIDNew",$scope.eventdoc.eventInstanceId);

            //			$log.debug($scope.eventdoc);
            //			$log.debug($scope.eventdoc.eventInstanceId);
            $http.post('/api/events', $scope.eventdoc).then(function(res) {

              if (res.data.success) {
                ngNotifier.notify("Event has been created!");
                $location.path('/dashboard/');

              } else {
                alert('there was an error');
              }
            });

            $scope.ok();

          } else {
            alert('no data received, assign new id');
          }

        });

      }
    });

  };

  $scope.saveDraftEvent = function(clicked) {

      $log.debug($scope.date);
      $scope.eventdoc.dateCreated = $scope.date;

    $http.post('/api/events/drafts', $scope.eventdoc).then(function(res) {

      $log.debug(res.data);
      if (res.data.type=="update") {

        //

        if (clicked=="clicked") {
          ngNotifier.notify("Your event has been saved under drafts");
          //$location.path("/dashboard/drafts");
          //$scope.ok();

        } else {
          // if (res.data.newId) {

          //   previousData = angular.toJson($scope.eventdoc);
          // }
          ngNotifier.notify("Your event has been saved under drafts automatically.");
        }

      }
      else if(res.data.type=="insert")
      {
        ngNotifier.notify("Your event has been saved under drafts");
        $scope.eventdoc = res.data.eventdoc;
      }

       else {
        alert('A problem was encountered with saving this event. Please contact the admistrator.');
      }
    });

  };

  function getLatestInstance(partialId) {
    $log.debug(partialId);

    $http.get('/api/events/getAvailEventId/' + partialId).then(function(res) {
      $log.debug(partialId);
      $log.debug(res.data);
      if (res.data) {
        //var eventInstanceIdParts = res.data.eventInstanceId.split("-");
        //$scope.eventInstanceId= eventInstanceIdParts[0] + '-' + String('0'+(Number(eventInstanceIdParts[1]) + 1));
        if (res.data.length > 0) {
          $log.debug("ID alreADy prsent");
          return partialId + "xx";
        } else {
          $log.debug("id available to be used");
          $log.debug(partialId);
          return partialId;
        }

      } else {
        alert('no data received, assign new id');
      }
    });

  }

  function genInstanceId(eventName) {
    var nameComponent = eventName.toUpperCase().split(' ');
    var instanceId;
    if (nameComponent.length > 1)
      instanceId = nameComponent[0].substr(0, 2) + nameComponent[1].substr(0, 2) + '-' + '01';
    else
      instanceId = nameComponent[0].substr(0, 4) + '-' + '01';
    return instanceId;
  }

  // $scope.checkDirty = function() {
  //   $log.debug('check dirty fired');
  //   if (previousData !== angular.toJson($scope.eventdoc)) {
  //     $scope.saveDraftEvent('Yes');
  //     previousData = angular.toJson($scope.eventdoc);
  //   }

  // };

var unregister=$scope.$watch('eventdoc', function(newVal, oldVal){
   $log.debug("watching");
    if(newVal!=oldVal)
    {
      $log.debug('changed');
      $scope.allowSaveDrafts=true;
      unregister();
    }

}, true);

});<commit_msg>reactivate auto save.  set for 2.5 minutes (150 seconds)<commit_after>angular.module('app').controller('createEventCtrl', function($scope, $http, $filter, $route, ngNotifier,$location,$interval,$animate,ngIdentity, ngUser,$log) {
$scope.identity = ngIdentity;

$animate.enabled(false, "div");
  // var draftInstance = $scope.draftInstance;
  // $log.debug("draftInstance", draftInstance);
$scope.allowSaveDrafts=false;
  var secondUnit = 1000;
  var autoSave;

  autoSave = $interval(function() {
    $scope.checkDirty();
  }, 150 * secondUnit);

  $scope.$on('$destroy', function() {
    $log.debug($scope.eventdoc );
    if($scope.eventdoc.draftStatus)
    {
      if($scope.allowSaveDrafts)
      {
        $log.debug("saving");
        $scope.saveDraftEvent();
      }

    }
    $interval.cancel(autoSave);

  });

  $scope.topicValue = {};
  $scope.subTopicValue = {};
  $scope.userAssigned = {};

  $scope.users = [];

  $scope.eventdoc = {
    "eventName": "",
    "eventType": "",
    "eventInstanceId": "",
    "userCreated": "",
    "dateCreated": "",
    "draftStatus": true,
    "archiveStatus": false,
    categories: [{
      name: 'Web',
      "userAssigned": "",
      "statusCompleted": false,
      "dateCompleted": "",
      topics: [

      ]
    }, {
      name: 'TV',
      "userAssigned": "",
      "statusCompleted": false,
      "dateCompleted": "",
      topics: [

      ]
    }, {
      name: 'Print',
      "userAssigned": "",
      "statusCompleted": false,
      "dateCompleted": "",
      topics: [

      ]
    }, ]
  };

  if ($scope.draftInstance) {
    $scope.eventdoc = $scope.draftInstance;
  }

  $scope.eventTypes = ['Earthquake', 'Hurricane', 'Flood', 'Infectious Disease', 'Famine'] //hardcoded placeholder
    //$scope.date = new Date().getTime();
  $scope.date = new Date().getTime(); // need both date and time

  $scope.eventdoc.userCreated = {id:$scope.identity.currentUser._id, displayName: $scope.identity.currentUser.displayName};
  var previousData = angular.toJson($scope.eventdoc);

  $http.get('/api/users/analysts').then(function(res) {
  var analysts = res.data;
  for(var i=0; i < analysts.length; i++) {
    $scope.users.push({'id':analysts[i]._id, 'displayName':analysts[i].displayName });
    // $scope.users.push(analysts[i].displayName);
  }
  });

  $log.debug($scope.date);

  $scope.addTopic = function(category) {
    $log.debug(category);
    // if ($scope.eventdoc.categories.indexOf(category).topics.length > 10) {
    //   window.alert('You can\'t add more than 10 topics!');
    //   return;
    // }
    //var topicName = document.getElementById('topicName').value;
    var topicName = $scope.topicValue[category.name];
    if (topicName.length > 0) {
      category.topics.push({
        name: topicName,
        type: 'topic',
        subTopics: [],
        sortOrder: category.topics.length
      });

    }
    $scope.topicValue = {};
  };

  $scope.editTopic = function(topic) {
    topic.editing = true;
  };

  $scope.cancelEditingTopic = function(topic) {
    topic.editing = false;
  };

  $scope.saveTopic = function(topic) {
    // topic.save();
    topic.editing = false;
  };

  $scope.removeTopic = function(category, topic) {
    // if (window.confirm('Are you sure to remove this topic?')) {
    //   //topic.destroy();  //TODO
    // }
    $log.debug(category);
    $log.debug(topic);
    var index = category.topics.indexOf(topic);
    if (index > -1) {
      category.topics.splice(index, 1)[0];
    }
  };

  $scope.saveTopics = function() {
    for (var i = $scope.eventdoc.categories[0].topics.length - 1; i >= 0; i--) {
      var topic = $scope.eventdoc.categories[0].topics[i];
      topic.sortOrder = i + 1;
      // topic.save();
    }
  };

  $scope.addSubTopic = function(topic) {
    $log.debug(topic);
    if (!topic.newSubTopicName || topic.newSubTopicName.length === 0) {
      return;
    }
    topic.subTopics.push({
      name: topic.newSubTopicName,
      sortOrder: topic.subTopics.length,
      type: 'subTopic',
      bullets: []
    });
    topic.newSubTopicName = '';
    // topic.save();
  };

  $scope.removeSubTopic = function(topic, subTopic) {
    //if (window.confirm('Are you sure to remove this subTopic?')) {
    var index = topic.subTopics.indexOf(subTopic);
    if (index > -1) {
      topic.subTopics.splice(index, 1)[0];
    }
    // topic.save();
    //}
  };

  $scope.editSubTopic = function(subTopic) {
    $log.debug("edit sub topic");
    subTopic.editing = true;
  };

  // $scope.cancelEditingSubTopic = function(topic) {
  //   topic.editing = false;
  // };

  $scope.saveSubTopic = function(subTopic) {
    // topic.save();
    subTopic.editing = false;
  };

  $scope.options = {
    accept: function(sourceNode, destNodes, destIndex) {
      var data = sourceNode.$modelValue;
      var destType = destNodes.$element.attr('data-type');
      return (data.type == destType); // only accept the same type
    },
    dropped: function(event) {
      $log.debug(event);
      var sourceNode = event.source.nodeScope;
      var destNodes = event.dest.nodesScope;
      // update changes to server
      if (destNodes.isParent(sourceNode) && destNodes.$element.attr('data-type') == 'subTopic') { // If it moves in the same topic, then only update topic
        var topic = destNodes.$nodeScope.$modelValue;
        // topic.save();
      } else { // save all
        $scope.saveTopics();
      }
    },
    beforeDrop: function(event) {
      // if (!window.confirm('Are you sure you want to drop it here?')) {
      //   event.source.nodeScope.$$apply = false;
      // }
    }
  };

  $scope.createEvent = function() {
    $log.debug($scope.eventdoc.eventInstanceId);
    var minimumAssign = false;
    //var formattedEventInstanceId = 'EQSA-01'; //TODO: Create actual eventInstanceId do this on server-side?
    for(var i=0; i < $scope.eventdoc.categories.length; i++){
      if($scope.eventdoc.categories[i].userAssigned != '') {
        minimumAssign = true;
      }
    }
    $scope.eventdoc.dateCreated = $scope.date;
    $http.get('/api/events/duplicate/' + $scope.eventdoc.eventName).then(function(res) {
      //$log.debug(res.data.duplicate);
      if ($scope.eventdoc.eventName.trim() === '') {
        ngNotifier.notifyError('Event name cannot be blank');
      } else if ($scope.eventdoc.eventName.replace(/ /g, '').match(/^[0-9]+$/) != null) {
        ngNotifier.notifyError('Event name cannot contain only numbers');
      } else if (res.data.duplicate) {
        ngNotifier.notifyError('Cannot create event. Duplicate name');
      } else if ($scope.eventdoc.eventType === '') {
        ngNotifier.notifyError('Please select an event type');
      } else if (minimumAssign === false){
        ngNotifier.notifyError('You must assign atleast one category to an analyst');
      } else {

        $scope.eventdoc.dateCreated = $scope.date;
        $scope.eventdoc.draftStatus = false;
        // if (draftInstance)
        //   $scope.eventdoc._id = draftInstance._id;

        var partialId = genInstanceId($scope.eventdoc.eventName);

        $http.get('/api/events/getAvailEventId/' + partialId).then(function(res) {
          //       	$log.debug(partialId);
          //        $log.debug(res.data);
          if (res.data) {
            //var eventInstanceIdParts = res.data.eventInstanceId.split("-");
            //$scope.eventInstanceId= eventInstanceIdParts[0] + '-' + String('0'+(Number(eventInstanceIdParts[1]) + 1));
            if (res.data.length > 0) {
              //                $log.debug("ID alreADy prsent");
              $scope.eventdoc.eventInstanceId = partialId + "xx";
            } else {
              //                $log.debug("id available to be used");
              //                $log.debug(partialId);
              $scope.eventdoc.eventInstanceId = partialId;
            }

            //			$log.debug("eventIDNew",$scope.eventdoc.eventInstanceId);

            //			$log.debug($scope.eventdoc);
            //			$log.debug($scope.eventdoc.eventInstanceId);
            $http.post('/api/events', $scope.eventdoc).then(function(res) {

              if (res.data.success) {
                ngNotifier.notify("Event has been created!");
                $location.path('/dashboard/');

              } else {
                alert('there was an error');
              }
            });

            $scope.ok();

          } else {
            alert('no data received, assign new id');
          }

        });

      }
    });

  };

  $scope.saveDraftEvent = function(clicked) {

      $log.debug($scope.date);
      $scope.eventdoc.dateCreated = $scope.date;

    $http.post('/api/events/drafts', $scope.eventdoc).then(function(res) {

      $log.debug(res.data);
      if (res.data.type=="update") {

        //

        if (clicked=="clicked") {
          ngNotifier.notify("Your event has been saved under drafts");
          //$location.path("/dashboard/drafts");
          //$scope.ok();

        } else {
          // if (res.data.newId) {

          //   previousData = angular.toJson($scope.eventdoc);
          // }
          ngNotifier.notify("Your event has been saved under drafts automatically.");
        }

      }
      else if(res.data.type=="insert")
      {
        ngNotifier.notify("Your event has been saved under drafts");
        $scope.eventdoc = res.data.eventdoc;
        previousData = angular.toJson($scope.eventdoc);
      }

       else {
        alert('A problem was encountered with saving this event. Please contact the admistrator.');
      }
    });

  };

  function getLatestInstance(partialId) {
    $log.debug(partialId);

    $http.get('/api/events/getAvailEventId/' + partialId).then(function(res) {
      $log.debug(partialId);
      $log.debug(res.data);
      if (res.data) {
        //var eventInstanceIdParts = res.data.eventInstanceId.split("-");
        //$scope.eventInstanceId= eventInstanceIdParts[0] + '-' + String('0'+(Number(eventInstanceIdParts[1]) + 1));
        if (res.data.length > 0) {
          $log.debug("ID alreADy prsent");
          return partialId + "xx";
        } else {
          $log.debug("id available to be used");
          $log.debug(partialId);
          return partialId;
        }

      } else {
        alert('no data received, assign new id');
      }
    });

  }

  function genInstanceId(eventName) {
    var nameComponent = eventName.toUpperCase().split(' ');
    var instanceId;
    if (nameComponent.length > 1)
      instanceId = nameComponent[0].substr(0, 2) + nameComponent[1].substr(0, 2) + '-' + '01';
    else
      instanceId = nameComponent[0].substr(0, 4) + '-' + '01';
    return instanceId;
  }

   $scope.checkDirty = function() {
     $log.debug('check dirty fired');
     if (previousData !== angular.toJson($scope.eventdoc)) {
     $scope.saveDraftEvent('Yes');
      previousData = angular.toJson($scope.eventdoc);
   }

  };

var unregister=$scope.$watch('eventdoc', function(newVal, oldVal){
   $log.debug("watching");
    if(newVal!=oldVal)
    {
      $log.debug('changed');
      $scope.allowSaveDrafts=true;
      unregister();
    }

}, true);

});<|endoftext|>


<commit_before>let d = new Date();
var x = document.createElement("P");
var t = document.createTextNode("Todays date is " + d + " and hey Nick!");
x.appendChild(t);
document.body.appendChild(x);
<commit_msg>Update main.js<commit_after>let d = new Date();
var x = document.createElement("h1");
var t = document.createTextNode("Todays date is " + d + " and hey Nick!");
x.appendChild(t);
document.body.appendChild(x);
<|endoftext|>


<commit_before>const clipboard = require('clipboard'),
      contextMenu = require('context-menu'),
      data = require('self').data,
      notify = require('simple-notify').notify,
      prefs = require('sdk/simple-prefs').prefs,
      xhr = require('xhr'),

      aboutconfig = require('preferences-service');  // Deprecated

// about:config preferences, deprecated
const serviceurl_pref = 'extensions.copyshorturl.serviceURL';

// Service defaults.
const default_service = 'isgd',
      serviceurl_docs = 'http://copy-shorturl.readthedocs.org/en/latest/serviceurl.html';

// Specify 'url' for plain-text GET APIs, or request/result for more complex
// variants.
var serviceurls = {
  isgd: {
    url: 'http://is.gd/api.php?longurl=%URL%'
  },
  tinyurl: {
    url: 'http://tinyurl.com/api-create.php?url=%URL%'
  },
  googl: {
    // https://developers.google.com/url-shortener/v1/getting_started
    request: function(url) {
      let req = new xhr.XMLHttpRequest();
      req.open("POST", 'https://www.googleapis.com/urlshortener/v1/url', false);
      req.setRequestHeader('Content-Type', 'application/json');
      req.send(JSON.stringify({ longUrl: url }));
      return req;
    },
    result: function(req) {
      console.log('ohai');
      let shortened = JSON.parse(req.responseText);
      return shortened.id;
    }
  }
};
// Hook up pref button to service URL docs.
require('sdk/simple-prefs').on('serviceurl_docs', function() {
  require('sdk/tabs').open(serviceurl_docs);
});

/** Determine service URL */
function getShorteningService() {
  if (prefs.service === 'custom') {
    if (prefs.customurl) {
      return {
        url: prefs.customurl
      };
    } else {
      // Restore default.
      prefs.service = default_service;
    }
  }
  return serviceurls[prefs.service];
}

/** Create a short URL from is.gd, tinyurl, etc. */
function createShortUrl(url) {
    let req,
        service = getShorteningService();

    try {
      if (service.request) {
        req = service.request(url);
      } else {
        req = new xhr.XMLHttpRequest();
        req.open("GET", service.url.replace(
          '%URL%', encodeURIComponent(url)), false);
        req.send(null);
      }
      if (req.status === 200) {
          let result = service.result ? service.result(req) : req.responseText.trim();
          notify("No short URL found. Created alternative URL instead:\n" +
                 url + ' --> ' + result);
          return result;
      } else {
        throw new Error('ZOMG, error creating short URL.');
      }
    } catch (e) {
      notify(e.message);
      return false;
    }
}

exports.main = function(options, callbacks) {
    /* Set URL from preference if set in old version of add-on. */
    if (aboutconfig.has(serviceurl_pref)) {
      prefs.service = 'custom';
      prefs.customurl = aboutconfig.get(serviceurl_pref);
      aboutconfig.reset(serviceurl_pref);
    }

    /* Add and hook up context menu */
    var item = contextMenu.Item({
        label: 'Copy ShortURL',
        contentScriptFile: data.url('js/find-short-url.js'),
        onMessage: function(found_url) {
            let url = found_url['url'];

            if (found_url['short']) {
                notify("Short URL found:\n" + url);
            } else {
                url = createShortUrl(url);
            }

            if (url) clipboard.set(url);
        }
    });
}
<commit_msg>added hotkey support for shortening urls<commit_after>const clipboard = require('clipboard'),
      contextMenu = require('context-menu'),
      data = require('self').data,
      notify = require('simple-notify').notify,
      prefs = require('sdk/simple-prefs').prefs,
      xhr = require('xhr'),
      tabs = require('tabs'),
      aboutconfig = require('preferences-service');  // Deprecated

const { Hotkey } = require('hotkeys');

// about:config preferences, deprecated
const serviceurl_pref = 'extensions.copyshorturl.serviceURL';

// Service defaults.
const default_service = 'isgd',
      serviceurl_docs = 'http://copy-shorturl.readthedocs.org/en/latest/serviceurl.html';

// Specify 'url' for plain-text GET APIs, or request/result for more complex
// variants.
var serviceurls = {
  isgd: {
    url: 'http://is.gd/api.php?longurl=%URL%'
  },
  tinyurl: {
    url: 'http://tinyurl.com/api-create.php?url=%URL%'
  },
  googl: {
    // https://developers.google.com/url-shortener/v1/getting_started
    request: function(url) {
      let req = new xhr.XMLHttpRequest();
      req.open("POST", 'https://www.googleapis.com/urlshortener/v1/url', false);
      req.setRequestHeader('Content-Type', 'application/json');
      req.send(JSON.stringify({ longUrl: url }));
      return req;
    },
    result: function(req) {
      console.log('ohai');
      let shortened = JSON.parse(req.responseText);
      return shortened.id;
    }
  }
};
// Hook up pref button to service URL docs.
require('sdk/simple-prefs').on('serviceurl_docs', function() {
  require('sdk/tabs').open(serviceurl_docs);
});

/** Determine service URL */
function getShorteningService() {
  if (prefs.service === 'custom') {
    if (prefs.customurl) {
      return {
        url: prefs.customurl
      };
    } else {
      // Restore default.
      prefs.service = default_service;
    }
  }
  return serviceurls[prefs.service];
}

/** Create a short URL from is.gd, tinyurl, etc. */
function createShortUrl(url) {
    let req,
        service = getShorteningService();

    try {
      if (service.request) {
        req = service.request(url);
      } else {
        req = new xhr.XMLHttpRequest();
        let _uri = service.url.replace('%URL%', encodeURIComponent(url));
        req.open("GET", _uri, false);
        req.send(null);
      }
      if (req.status === 200) {
          let result = service.result ? service.result(req) : req.responseText.trim();
          notify("No short URL found. Created alternative URL instead:\n" +
                 url + ' --> ' + result);
          return result;
      } else {
        throw new Error('ZOMG, error creating short URL.');
      }
    } catch (e) {
      notify(e.message);
      return false;
    }
}

exports.main = function(options, callbacks) {
    /* Set URL from preference if set in old version of add-on. */
    if (aboutconfig.has(serviceurl_pref)) {
      prefs.service = 'custom';
      prefs.customurl = aboutconfig.get(serviceurl_pref);
      aboutconfig.reset(serviceurl_pref);
    }

    /* Add and hook up context menu */
    var item = contextMenu.Item({
        label: 'Copy ShortURL',
        contentScriptFile: data.url('js/find-short-url.js'),
        onMessage: function(found_url) {
            let url = found_url['url'];

            if (found_url['short']) {
                notify("Short URL found:\n" + url);
            } else {
                url = createShortUrl(url);
            }

            if (url) clipboard.set(url);
        }
    });

    Hotkey({
        combo: "accel-shift-l",
        onPress: function() {
            let shortened = createShortUrl(tabs.activeTab.url);
            if (shortened) clipboard.set(shortened);
        }
    });
}
<|endoftext|>


<commit_before>(function() {

    'use strict';

    angular.module('Core')
        .service('commonService', commonService);

    commonService.$inject = ['$document', '$state', '$stateParams', '$q', '$timeout', '$window'];

    function commonService($document, $state, $stateParams, $q, $timeout, $window) {
        var service = this;
        service.resetForm = resetForm;
        service.getDateInDDMMMMYYYY = getDateInDDMMMMYYYY;
        service.isObjPresent = isObjPresent;
        service.getObjType = getObjType;
        service.getUUID = getUUID;
        service.isEpochTimeInMs = isEpochTimeInMs;
        service.getValInNumber = getValInNumber;
        service.loadingMode = loadingMode;
        service.goToPage = goToPage;
        service.getCurrentState = getCurrentState;
        service.getStateParam = getStateParam;

        /* ======================================== Var ==================================================== */
        service.$q = $q;
        service.$timeout = $timeout;
        service.$window = $window;

        /* ======================================== Services =============================================== */
        var stateParam = $stateParams;

        /* ======================================== Public Methods ========================================= */
        function getStateParam() {
            return stateParam.data;
        }

        function getCurrentState() {
            return $state.current;
        }

        function goToPage(stateName, hasRoot, toReload, stateParam) {
            var stateObj = {};

            if (isObjPresent(stateName)) {
                if (isObjPresent(hasRoot)) {
                    stateName = 'root.' + stateName;
                }

                if (isObjPresent(stateParam)) {
                    stateObj = $state.go(stateName, { data: stateParam });
                } else {
                    stateObj = $state.go(stateName);
                }
            } else {
                if (toReload) {
                    $state.reload();
                }
            }

            return stateObj.$$state;
        }

        function loadingMode(isLoading, containerIdToAddThisLoader) {
            if(isLoading === true || isLoading === false) {
                if(isLoading == true) {
                    if(isObjPresent(containerIdToAddThisLoader) == true) {
                        if(!isObjPresent(document.getElementById('loadingContainer'))) {
                            var loadingHtml = angular.element('

');
                            var dom = angular.element(document.getElementById(containerIdToAddThisLoader));
                            dom.css("position", "relative"); // This has to be double "" as '' does not work.
                            dom.append(loadingHtml);

                            var opts = {
                                lines: 13, // The number of lines to draw
                                length: 28, // The length of each line
                                width: 14, // The line thickness
                                radius: 50, // The radius of the inner circle
                                scale: 1, // Scales overall size of the spinner
                                corners: 1, // Corner roundness (0..1)
                                color: '#FFF', // #rgb or #rrggbb or array of colors
                                opacity: 0, // Opacity of the lines
                                rotate: 0, // The rotation offset
                                direction: 1, // 1: clockwise, -1: counterclockwise
                                speed: 1, // Rounds per second
                                trail: 100, // Afterglow percentage
                                fps: 20, // Frames per second when using setTimeout() as a fallback for CSS
                                zIndex: 2e9, // The z-index (defaults to 2000000000)
                                className: 'spinner', // The CSS class to assign to the spinner
                                top: '50%', // Top position relative to parent
                                left: '50%', // Left position relative to parent
                                shadow: false, // Whether to render a shadow
                                hwaccel: false, // Whether to use hardware acceleration
                                position: 'absolute' // Element positioning
                            }
                            var target = document.getElementById('spinner')
                            spinner = new Spinner(opts).spin(target);
                        }
                    } else {
                        if(!isObjPresent(document.getElementById('loadingContainer'))) {
                            var loadingHtml = '

';
                            var body = $document.find('body').eq(0);
                            body.append(loadingHtml);

                            var opts = {
                                lines: 13, // The number of lines to draw
                                length: 28, // The length of each line
                                width: 14, // The line thickness
                                radius: 50, // The radius of the inner circle
                                scale: 1, // Scales overall size of the spinner
                                corners: 1, // Corner roundness (0..1)
                                color: '#FFF', // #rgb or #rrggbb or array of colors
                                opacity: 0, // Opacity of the lines
                                rotate: 0, // The rotation offset
                                direction: 1, // 1: clockwise, -1: counterclockwise
                                speed: 1, // Rounds per second
                                trail: 100, // Afterglow percentage
                                fps: 20, // Frames per second when using setTimeout() as a fallback for CSS
                                zIndex: 2e9, // The z-index (defaults to 2000000000)
                                className: 'spinner', // The CSS class to assign to the spinner
                                top: '50%', // Top position relative to parent
                                left: '50%', // Left position relative to parent
                                shadow: false, // Whether to render a shadow
                                hwaccel: false, // Whether to use hardware acceleration
                                position: 'absolute' // Element positioning
                            }
                            var target = document.getElementById('spinner')
                            spinner = new Spinner(opts).spin(target);
                        }
                    }
                } else {
                    if(isObjPresent(spinner)) {
                        spinner.stop();
                        angular.element(document.getElementById('loadingContainer')).remove();
                    }
                }
            } else {
                throw new Error ('Parameter can only be TRUE or FALSE');
            }
        }

        // This function will return the following:
        //      - 111 => return 100
        //      - 1111 => return 1000
        //      - 53 => 50
        //      - 9987 => 9000
        //      - Less than 10 will return the number itself
        function getValInNumber(num) {
            if (getObjType(num) == number) {
                return num.toString()
                    .split('')
                    .map(function(char, index) {
                        return (index == 0) ? char : '0';
                    })
                    .join('') - 0; // -0 Will convert the entire string to a number
            } else {
                throw new Error(num + ' must be a number!');
            }
        }

        function isEpochTimeInMs(epochDateTime) {
            var totalNoOfCharForCurrentTimeInSeconds = Number(Math.floor(Date.now() / 1000)).toString().length;
            var totalNoOfCharForCurrentTimeInMilliseconds = Number(Date.now()).toString().length;
            if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInMilliseconds) {
                return true;
            } else if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInSeconds) {
                return false;
            } else {
                throw new TypeError('Parameter passed in is not in seconds or milliseconds');
            }
        }

        /**
         * Fast UUID generator, RFC4122 version 4 compliant.
         *
         * Don't understand how it works? Please visit the link as shown below. Its not meant to be readable as much as its meant to be fast
         *
         * @author Jeff Ward (jcward.com).
         * @license MIT license
         * @link http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
         **/
        function getUUID() {
            var lut = [];
            for (var i = 0; i < 256; i++) {
                lut[i] = (i < 16 ? '0' : '') + (i).toString(16);
            }
            var d0 = Math.random() * 0xffffffff | 0;
            var d1 = Math.random() * 0xffffffff | 0;
            var d2 = Math.random() * 0xffffffff | 0;
            var d3 = Math.random() * 0xffffffff | 0;
            return lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +
                lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +
                lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
                lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];
        }

        function getObjType(object) { // Would really appreciate a unit test to test all for this as manual testing didn't cover everything
            var prop = {
                '[object Object]': 'object',
                '[object Array]': 'array',
                '[object String]': 'string',
                '[object Boolean]': 'boolean',
                '[object Number]': 'number',
                '[object Null]': 'null',
                '[object Undefined]': 'undefined',
                '[object Function]': 'function',
                '[object Date]': 'date',
                '[object HTMLDivElement]': 'htmlDivElement',
                '[object Blob]': 'blob',
                '[object File]': 'file',
                '[object MouseEvent]': 'mouse_event'
            }

            return prop[Object.prototype.toString.call(object)];
        }

        /**
         * Thie method is inspired by rails .blank? method. This method check for is present (opposite of is blank)
         *     Rails .blank? method:
         *         - null.blank? => true
         *         - false.blank? => true
         *         - [].blank? => true
         *         - {}.blank? => true
         *         - ''.blank? => true
         *         - 5.blank? => false
         *         - 0.blank? => false
         *     Added another check is to check for function.
         *     An empty function is:
         *         - function () { }
         *         - function(param1, param2, param3) { }
         *     A non empty function is:
         *         - function() { console.log(); }
         *     An invalid date will return false for this function
         *     A valid date will return true for this function
         *     This will just check if its empty or not and not check if its syntatically correct or not
         * @param  {object}  obj [Since everything in javascript is considered an object, just pass in anything]
         * @return {Boolean}     [If its not blank, then will return true. Else, it will return false]
         */
        function isObjPresent(obj) {
            var type = getObjType(obj);
            if (type === 'object') {
                // The code below uses the Object.keys() function from ECMA Script 5+ specification. However, to ensure it can run for < ECMA Script 5, this is commented out
                // var objLength = Object.keys(obj).length;
                // if(objLength > 0) {
                //     return true;
                // } else if (objLength == 0) {
                //     return false;
                // } else {
                //     throw new Error(obj + ' comes to object if-else but the length is neither 0 or more than 0');
                // }

                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        return true;
                    }
                }
                return false;
            } else if (type === 'array') {
                if (obj.length > 0) {
                    return true;
                } else if (obj.length == 0) {
                    return false;
                } else {
                    throw new Error(obj + ' comes to array if-else but the length is neither 0 or more than 0');
                }
            } else if (type === 'string') {
                if (obj.length > 0) {
                    return true;
                } else if (obj.length == 0) {
                    return false
                } else {
                    throw new Error(obj + ' comes to string if-else but the length its not 0 or more than 0');
                }
            } else if (type === 'boolean') {
                if (obj === true) {
                    return true
                } else if (obj === false) {
                    return false;
                } else {
                    throw new Error(obj + ' comes to boolean if-else but is neither true or false');
                }
            } else if (type === 'number') {
                return true; // We assume if the obj passed in is a number, that means it has a value and thus present (either negative or positive value)
            } else if (type === 'null') {
                return false;
            } else if (type === 'undefined') {
                return false;
            } else if (type === 'function') {
                var tmpStr = obj.toString();
                var tmpStr2 = tmpStr.substring(tmpStr.indexOf('{') + 1, tmpStr.indexOf('}')).trim().replace(/\r?\n|\r/g, ""); // The RegEx here is to check for: arriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS)
                if (isObjPresent(tmpStr2)) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'date') {
                if (isNaN(obj.getTime())) {
                    return false; // Date is invalid
                } else {
                    return true; // Date is valid
                }
            } else if (type === 'htmlDivElement') {
                if(type.toString().length > 0) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'blob') {
                if(obj.size > 0) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'file') {
                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        return true;
                    }
                }
                return false;
            } else if (type === 'mouse_event') {
                return true;
            } else {
                throw new Error(obj + ' is not an array, string, boolean or number. This fn only work with those for now');
            }
        }

        function getDateInDDMMMMYYYY(dateTimeInEpoch) { // Will return dd MMMM YYYY : 01 Jan 2012
            try {
                var dateTimeInNumber = Number(dateTimeInEpoch);
                var month = new Date(Number(dateTimeInEpoch)).getMonth();
                var monthInString = '';

                if (month == 0) {
                    monthInString = 'Jan';
                } else if (month == 1) {
                    monthInString = 'Feb';
                } else if (month == 2) {
                    monthInString = 'Mac';
                } else if (month == 3) {
                    monthInString = 'Apr';
                } else if (month == 4) {
                    monthInString = 'May';
                } else if (month == 5) {
                    monthInString = 'Jun';
                } else if (month == 6) {
                    monthInString = 'Jul';
                } else if (month == 7) {
                    monthInString = 'Aug';
                } else if (month == 8) {
                    monthInString = 'Sept';
                } else if (month == 9) {
                    monthInString = 'Oct';
                } else if (month == 10) {
                    monthInString = 'Nov';
                } else if (month == 11) {
                    monthInString = 'Dec';
                }

                return new Date(Number(dateTimeInEpoch)).getDay() + ' ' + monthInString + ' ' + new Date(Number(dateTimeInEpoch)).getFullYear();
            } catch (e) {
                throw new Error('date time is not in number');
            }
        }

        function resetForm(formName, formObj) {
            formName.$setPristine();
            angular.copy({}, formObj);
        }

        /* ======================================== Private Methods ======================================== */
        function init() {

        }

        init();
    }
})();<commit_msg>Do a check for keyboard events<commit_after>(function() {

    'use strict';

    angular.module('Core')
        .service('commonService', commonService);

    commonService.$inject = ['$document', '$state', '$stateParams', '$q', '$timeout', '$window'];

    function commonService($document, $state, $stateParams, $q, $timeout, $window) {
        var service = this;
        service.resetForm = resetForm;
        service.getDateInDDMMMMYYYY = getDateInDDMMMMYYYY;
        service.isObjPresent = isObjPresent;
        service.getObjType = getObjType;
        service.getUUID = getUUID;
        service.isEpochTimeInMs = isEpochTimeInMs;
        service.getValInNumber = getValInNumber;
        service.loadingMode = loadingMode;
        service.goToPage = goToPage;
        service.getCurrentState = getCurrentState;
        service.getStateParam = getStateParam;

        /* ======================================== Var ==================================================== */
        service.$q = $q;
        service.$timeout = $timeout;
        service.$window = $window;

        /* ======================================== Services =============================================== */
        var stateParam = $stateParams;

        /* ======================================== Public Methods ========================================= */
        function getStateParam() {
            return stateParam.data;
        }

        function getCurrentState() {
            return $state.current;
        }

        function goToPage(stateName, hasRoot, toReload, stateParam) {
            var stateObj = {};

            if (isObjPresent(stateName)) {
                if (isObjPresent(hasRoot)) {
                    stateName = 'root.' + stateName;
                }

                if (isObjPresent(stateParam)) {
                    stateObj = $state.go(stateName, { data: stateParam });
                } else {
                    stateObj = $state.go(stateName);
                }
            } else {
                if (toReload) {
                    $state.reload();
                }
            }

            return stateObj.$$state;
        }

        function loadingMode(isLoading, containerIdToAddThisLoader) {
            if(isLoading === true || isLoading === false) {
                if(isLoading == true) {
                    if(isObjPresent(containerIdToAddThisLoader) == true) {
                        if(!isObjPresent(document.getElementById('loadingContainer'))) {
                            var loadingHtml = angular.element('

');
                            var dom = angular.element(document.getElementById(containerIdToAddThisLoader));
                            dom.css("position", "relative"); // This has to be double "" as '' does not work.
                            dom.append(loadingHtml);

                            var opts = {
                                lines: 13, // The number of lines to draw
                                length: 28, // The length of each line
                                width: 14, // The line thickness
                                radius: 50, // The radius of the inner circle
                                scale: 1, // Scales overall size of the spinner
                                corners: 1, // Corner roundness (0..1)
                                color: '#FFF', // #rgb or #rrggbb or array of colors
                                opacity: 0, // Opacity of the lines
                                rotate: 0, // The rotation offset
                                direction: 1, // 1: clockwise, -1: counterclockwise
                                speed: 1, // Rounds per second
                                trail: 100, // Afterglow percentage
                                fps: 20, // Frames per second when using setTimeout() as a fallback for CSS
                                zIndex: 2e9, // The z-index (defaults to 2000000000)
                                className: 'spinner', // The CSS class to assign to the spinner
                                top: '50%', // Top position relative to parent
                                left: '50%', // Left position relative to parent
                                shadow: false, // Whether to render a shadow
                                hwaccel: false, // Whether to use hardware acceleration
                                position: 'absolute' // Element positioning
                            }
                            var target = document.getElementById('spinner')
                            spinner = new Spinner(opts).spin(target);
                        }
                    } else {
                        if(!isObjPresent(document.getElementById('loadingContainer'))) {
                            var loadingHtml = '

';
                            var body = $document.find('body').eq(0);
                            body.append(loadingHtml);

                            var opts = {
                                lines: 13, // The number of lines to draw
                                length: 28, // The length of each line
                                width: 14, // The line thickness
                                radius: 50, // The radius of the inner circle
                                scale: 1, // Scales overall size of the spinner
                                corners: 1, // Corner roundness (0..1)
                                color: '#FFF', // #rgb or #rrggbb or array of colors
                                opacity: 0, // Opacity of the lines
                                rotate: 0, // The rotation offset
                                direction: 1, // 1: clockwise, -1: counterclockwise
                                speed: 1, // Rounds per second
                                trail: 100, // Afterglow percentage
                                fps: 20, // Frames per second when using setTimeout() as a fallback for CSS
                                zIndex: 2e9, // The z-index (defaults to 2000000000)
                                className: 'spinner', // The CSS class to assign to the spinner
                                top: '50%', // Top position relative to parent
                                left: '50%', // Left position relative to parent
                                shadow: false, // Whether to render a shadow
                                hwaccel: false, // Whether to use hardware acceleration
                                position: 'absolute' // Element positioning
                            }
                            var target = document.getElementById('spinner')
                            spinner = new Spinner(opts).spin(target);
                        }
                    }
                } else {
                    if(isObjPresent(spinner)) {
                        spinner.stop();
                        angular.element(document.getElementById('loadingContainer')).remove();
                    }
                }
            } else {
                throw new Error ('Parameter can only be TRUE or FALSE');
            }
        }

        // This function will return the following:
        //      - 111 => return 100
        //      - 1111 => return 1000
        //      - 53 => 50
        //      - 9987 => 9000
        //      - Less than 10 will return the number itself
        function getValInNumber(num) {
            if (getObjType(num) == number) {
                return num.toString()
                    .split('')
                    .map(function(char, index) {
                        return (index == 0) ? char : '0';
                    })
                    .join('') - 0; // -0 Will convert the entire string to a number
            } else {
                throw new Error(num + ' must be a number!');
            }
        }

        function isEpochTimeInMs(epochDateTime) {
            var totalNoOfCharForCurrentTimeInSeconds = Number(Math.floor(Date.now() / 1000)).toString().length;
            var totalNoOfCharForCurrentTimeInMilliseconds = Number(Date.now()).toString().length;
            if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInMilliseconds) {
                return true;
            } else if (Number(epochDateTime).toString().length == totalNoOfCharForCurrentTimeInSeconds) {
                return false;
            } else {
                throw new TypeError('Parameter passed in is not in seconds or milliseconds');
            }
        }

        /**
         * Fast UUID generator, RFC4122 version 4 compliant.
         *
         * Don't understand how it works? Please visit the link as shown below. Its not meant to be readable as much as its meant to be fast
         *
         * @author Jeff Ward (jcward.com).
         * @license MIT license
         * @link http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
         **/
        function getUUID() {
            var lut = [];
            for (var i = 0; i < 256; i++) {
                lut[i] = (i < 16 ? '0' : '') + (i).toString(16);
            }
            var d0 = Math.random() * 0xffffffff | 0;
            var d1 = Math.random() * 0xffffffff | 0;
            var d2 = Math.random() * 0xffffffff | 0;
            var d3 = Math.random() * 0xffffffff | 0;
            return lut[d0 & 0xff] + lut[d0 >> 8 & 0xff] + lut[d0 >> 16 & 0xff] + lut[d0 >> 24 & 0xff] + '-' +
                lut[d1 & 0xff] + lut[d1 >> 8 & 0xff] + '-' + lut[d1 >> 16 & 0x0f | 0x40] + lut[d1 >> 24 & 0xff] + '-' +
                lut[d2 & 0x3f | 0x80] + lut[d2 >> 8 & 0xff] + '-' + lut[d2 >> 16 & 0xff] + lut[d2 >> 24 & 0xff] +
                lut[d3 & 0xff] + lut[d3 >> 8 & 0xff] + lut[d3 >> 16 & 0xff] + lut[d3 >> 24 & 0xff];
        }

        function getObjType(object) { // Would really appreciate a unit test to test all for this as manual testing didn't cover everything
            var prop = {
                '[object Object]': 'object',
                '[object Array]': 'array',
                '[object String]': 'string',
                '[object Boolean]': 'boolean',
                '[object Number]': 'number',
                '[object Null]': 'null',
                '[object Undefined]': 'undefined',
                '[object Function]': 'function',
                '[object Date]': 'date',
                '[object HTMLDivElement]': 'htmlDivElement',
                '[object Blob]': 'blob',
                '[object File]': 'file',
                '[object MouseEvent]': 'mouse_event',
                '[object KeyboardEvent]': 'keyboard_event'
            }

            return prop[Object.prototype.toString.call(object)];
        }

        /**
         * Thie method is inspired by rails .blank? method. This method check for is present (opposite of is blank)
         *     Rails .blank? method:
         *         - null.blank? => true
         *         - false.blank? => true
         *         - [].blank? => true
         *         - {}.blank? => true
         *         - ''.blank? => true
         *         - 5.blank? => false
         *         - 0.blank? => false
         *     Added another check is to check for function.
         *     An empty function is:
         *         - function () { }
         *         - function(param1, param2, param3) { }
         *     A non empty function is:
         *         - function() { console.log(); }
         *     An invalid date will return false for this function
         *     A valid date will return true for this function
         *     This will just check if its empty or not and not check if its syntatically correct or not
         * @param  {object}  obj [Since everything in javascript is considered an object, just pass in anything]
         * @return {Boolean}     [If its not blank, then will return true. Else, it will return false]
         */
        function isObjPresent(obj) {
            var type = getObjType(obj);
            if (type === 'object') {
                // The code below uses the Object.keys() function from ECMA Script 5+ specification. However, to ensure it can run for < ECMA Script 5, this is commented out
                // var objLength = Object.keys(obj).length;
                // if(objLength > 0) {
                //     return true;
                // } else if (objLength == 0) {
                //     return false;
                // } else {
                //     throw new Error(obj + ' comes to object if-else but the length is neither 0 or more than 0');
                // }

                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        return true;
                    }
                }
                return false;
            } else if (type === 'array') {
                if (obj.length > 0) {
                    return true;
                } else if (obj.length == 0) {
                    return false;
                } else {
                    throw new Error(obj + ' comes to array if-else but the length is neither 0 or more than 0');
                }
            } else if (type === 'string') {
                if (obj.length > 0) {
                    return true;
                } else if (obj.length == 0) {
                    return false
                } else {
                    throw new Error(obj + ' comes to string if-else but the length its not 0 or more than 0');
                }
            } else if (type === 'boolean') {
                if (obj === true) {
                    return true
                } else if (obj === false) {
                    return false;
                } else {
                    throw new Error(obj + ' comes to boolean if-else but is neither true or false');
                }
            } else if (type === 'number') {
                return true; // We assume if the obj passed in is a number, that means it has a value and thus present (either negative or positive value)
            } else if (type === 'null') {
                return false;
            } else if (type === 'undefined') {
                return false;
            } else if (type === 'function') {
                var tmpStr = obj.toString();
                var tmpStr2 = tmpStr.substring(tmpStr.indexOf('{') + 1, tmpStr.indexOf('}')).trim().replace(/\r?\n|\r/g, ""); // The RegEx here is to check for: arriage Return (CR, \r, on older Macs), Line Feed (LF, \n, on Unices incl. Linux) or CR followed by LF (\r\n, on WinDOS)
                if (isObjPresent(tmpStr2)) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'date') {
                if (isNaN(obj.getTime())) {
                    return false; // Date is invalid
                } else {
                    return true; // Date is valid
                }
            } else if (type === 'htmlDivElement') {
                if(type.toString().length > 0) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'blob') {
                if(obj.size > 0) {
                    return true;
                } else {
                    return false;
                }
            } else if (type === 'file') {
                for (var key in obj) {
                    if (obj.hasOwnProperty(key)) {
                        return true;
                    }
                }
                return false;
            } else if (type === 'mouse_event') {
                return true;
            } else if (type === 'keyboard_event') {
                return true;
            } else {
                throw new Error(obj + ' is not an array, string, boolean or number. This fn only work with those for now');
            }
        }

        function getDateInDDMMMMYYYY(dateTimeInEpoch) { // Will return dd MMMM YYYY : 01 Jan 2012
            try {
                var dateTimeInNumber = Number(dateTimeInEpoch);
                var month = new Date(Number(dateTimeInEpoch)).getMonth();
                var monthInString = '';

                if (month == 0) {
                    monthInString = 'Jan';
                } else if (month == 1) {
                    monthInString = 'Feb';
                } else if (month == 2) {
                    monthInString = 'Mac';
                } else if (month == 3) {
                    monthInString = 'Apr';
                } else if (month == 4) {
                    monthInString = 'May';
                } else if (month == 5) {
                    monthInString = 'Jun';
                } else if (month == 6) {
                    monthInString = 'Jul';
                } else if (month == 7) {
                    monthInString = 'Aug';
                } else if (month == 8) {
                    monthInString = 'Sept';
                } else if (month == 9) {
                    monthInString = 'Oct';
                } else if (month == 10) {
                    monthInString = 'Nov';
                } else if (month == 11) {
                    monthInString = 'Dec';
                }

                return new Date(Number(dateTimeInEpoch)).getDay() + ' ' + monthInString + ' ' + new Date(Number(dateTimeInEpoch)).getFullYear();
            } catch (e) {
                throw new Error('date time is not in number');
            }
        }

        function resetForm(formName, formObj) {
            formName.$setPristine();
            angular.copy({}, formObj);
        }

        /* ======================================== Private Methods ======================================== */
        function init() {

        }

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


<commit_before>import Ember from 'ember';
import canUseDOM from '../utils/can-use-dom';
import objectTransforms from '../utils/object-transforms';
import BaseAdapter from './base';

const {
  isPresent,
  copy,
  assert,
  merge,
  get,
  $,
  String: { capitalize },
} = Ember;
const { compact } = objectTransforms;

export default BaseAdapter.extend({
  toStringExtension() {
    return 'GoogleAnalytics';
  },

  init() {
    const config = copy(get(this, 'config'));
    const { id } = config;

    assert(`[ember-metrics] You must pass a valid \`id\` to the ${this.toString()} adapter`, id);

    delete config.id;

    const hasOptions = isPresent(Object.keys(config));

    if (canUseDOM) {
      /* jshint ignore:start */
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      /* jshint ignore:end */

      if (hasOptions) {
        window.ga('create', id, config);
      } else {
        window.ga('create', id, 'auto');
      }
    }
  },

  identify(options = {}) {
    const compactedOptions = compact(options);
    const { distinctId } = compactedOptions;

    window.ga('set', 'userId', distinctId);
  },

  trackEvent(options = {}) {
    const compactedOptions = compact(options);
    const sendEvent = { hitType: 'event' };
    let gaEvent = {};

    for (let key in compactedOptions) {
      const capitalizedKey = capitalize(key);
      gaEvent[`event${capitalizedKey}`] = compactedOptions[key];
    }

    const event = merge(sendEvent, gaEvent);
    window.ga('send', event);

    return event;
  },

  trackPage(options = {}) {
    const compactedOptions = compact(options);
    const sendEvent = { hitType: 'pageview' };

    const event = merge(sendEvent, compactedOptions);
    window.ga('send', event);

    return event;
  },

  willDestroy() {
    $('script[src*="google-analytics"]').remove();
    delete window.ga;
  }
});
<commit_msg>GA nonInteraction field<commit_after>import Ember from 'ember';
import canUseDOM from '../utils/can-use-dom';
import objectTransforms from '../utils/object-transforms';
import BaseAdapter from './base';

const {
  isPresent,
  copy,
  assert,
  merge,
  get,
  $,
  String: { capitalize },
} = Ember;
const { compact } = objectTransforms;

export default BaseAdapter.extend({
  toStringExtension() {
    return 'GoogleAnalytics';
  },

  init() {
    const config = copy(get(this, 'config'));
    const { id } = config;

    assert(`[ember-metrics] You must pass a valid \`id\` to the ${this.toString()} adapter`, id);

    delete config.id;

    const hasOptions = isPresent(Object.keys(config));

    if (canUseDOM) {
      /* jshint ignore:start */
      (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga');
      /* jshint ignore:end */

      if (hasOptions) {
        window.ga('create', id, config);
      } else {
        window.ga('create', id, 'auto');
      }
    }
  },

  identify(options = {}) {
    const compactedOptions = compact(options);
    const { distinctId } = compactedOptions;

    window.ga('set', 'userId', distinctId);
  },

  trackEvent(options = {}) {
    const compactedOptions = compact(options);
    const sendEvent = { hitType: 'event' };
    let gaEvent = {};

    if (compactedOptions.nonInteraction) {
      gaEvent.nonInteraction = compactedOptions.nonInteraction;
      delete compactedOptions.nonInteraction;
    }

    for (let key in compactedOptions) {
      const capitalizedKey = capitalize(key);
      gaEvent[`event${capitalizedKey}`] = compactedOptions[key];
    }

    const event = merge(sendEvent, gaEvent);
    window.ga('send', event);

    return event;
  },

  trackPage(options = {}) {
    const compactedOptions = compact(options);
    const sendEvent = { hitType: 'pageview' };

    const event = merge(sendEvent, compactedOptions);
    window.ga('send', event);

    return event;
  },

  willDestroy() {
    $('script[src*="google-analytics"]').remove();
    delete window.ga;
  }
});
<|endoftext|>


<commit_before>// localization
var _ = require("l10n").get;

// open configuration tab if network_url is still the default value
simplePrefs = require("simple-prefs")
if (simplePrefs.prefs.network_url=="http://example.com/network") {
  require("tabs").open({
    url: require("self").data.url("configuration.html"),
    onReady: function onReady(tab) {
      // attach content script only one time
      if (tab._done) return;
      tab._done = true;

      worker = tab.attach({
        contentScriptFile: require("self").data.url("configuration.js")
      });

      // register callbacks
      worker.port.on("configure", function(configuration) {
        for (prop in configuration) {
          simplePrefs.prefs[prop] = configuration[prop];
        }

        worker.port.emit("done");
      });

      worker.port.on("close", function(data) {
        tab.close();
      });

      // send localize message
      worker.port.emit("localize", {
        "configuration_title": _("configuration_title"),
        "configuration_header": _("configuration_header"),
        "configuration_text": _("configuration_text"),
        "network_url_caption": _("network_url_caption"),
        "submit": _("submit"),
        "configuration_successful": _("configuration_successful")
      });
    }
  });
}

// opens a new tab with friendica, attaches a content script and sends the data to it
function post2friendica(data) {
  require("tabs").open({
    url: simplePrefs.prefs.network_url,
    onReady: function onReady(tab) {
      if (tab._done) return;

      worker = tab.attach({
        contentScriptFile: require("self").data.url("contentscript.js")
      });

      worker.port.on("error", function(error_type) {
        if (error_type=="text_field") require("notifications").notify({
          title: _("text_field_error_title"),
          text: _("text_field_error_text")
        });
        else if (error_type=="generator") require("notifications").notify({
          title: _("generator_error_title"),
          text: _("generator_error_text")
        });
      });

      worker.port.on("done", function(success) {
        tab._done = true;
      });

      worker.port.emit("post", data);
    }
  });
}

// add context menu items
var contextMenu = require("context-menu");

contextMenu.Item({
  label: _("share_page"),
  context: contextMenu.PageContext(),
  contentScript: 'self.on("click", function (node, data) { self.postMessage({"type":"url", "href":document.URL}); });',
  onMessage: post2friendica
});

contextMenu.Item({
  label: _("share_image"),
  context: contextMenu.SelectorContext("img"),
  contentScript: 'self.on("click", function (node, data) { self.postMessage({"type":"img", "src":node.src, "alt":node.alt}); });',
  onMessage: post2friendica
});

contextMenu.Item({
  label: _("share_link"),
  context: contextMenu.SelectorContext("a[href]"),
  contentScript: 'self.on("click", function (node, data) { self.postMessage({"type":"url", "href": node.href}); });',
  onMessage: post2friendica
});

contextMenu.Item({
  label: _("share_selection"),
  context: contextMenu.SelectionContext(),
  contentScript: 'self.on("click", function (node, data) { self.postMessage({"type":"quote", "source": document.URL, "title":document.title, "text":window.getSelection().toString()}); });',
  onMessage: post2friendica
});
<commit_msg>add missing semicolon<commit_after>// localization
var _ = require("l10n").get;

// open configuration tab if network_url is still the default value
simplePrefs = require("simple-prefs");
if (simplePrefs.prefs.network_url=="http://example.com/network") {
  require("tabs").open({
    url: require("self").data.url("configuration.html"),
    onReady: function onReady(tab) {
      // attach content script only one time
      if (tab._done) return;
      tab._done = true;

      worker = tab.attach({
        contentScriptFile: require("self").data.url("configuration.js")
      });

      // register callbacks
      worker.port.on("configure", function(configuration) {
        for (prop in configuration) {
          simplePrefs.prefs[prop] = configuration[prop];
        }

        worker.port.emit("done");
      });

      worker.port.on("close", function(data) {
        tab.close();
      });

      // send localize message
      worker.port.emit("localize", {
        "configuration_title": _("configuration_title"),
        "configuration_header": _("configuration_header"),
        "configuration_text": _("configuration_text"),
        "network_url_caption": _("network_url_caption"),
        "submit": _("submit"),
        "configuration_successful": _("configuration_successful")
      });
    }
  });
}

// opens a new tab with friendica, attaches a content script and sends the data to it
function post2friendica(data) {
  require("tabs").open({
    url: simplePrefs.prefs.network_url,
    onReady: function onReady(tab) {
      if (tab._done) return;

      worker = tab.attach({
        contentScriptFile: require("self").data.url("contentscript.js")
      });

      worker.port.on("error", function(error_type) {
        if (error_type=="text_field") require("notifications").notify({
          title: _("text_field_error_title"),
          text: _("text_field_error_text")
        });
        else if (error_type=="generator") require("notifications").notify({
          title: _("generator_error_title"),
          text: _("generator_error_text")
        });
      });

      worker.port.on("done", function(success) {
        tab._done = true;
      });

      worker.port.emit("post", data);
    }
  });
}

// add context menu items
var contextMenu = require("context-menu");

contextMenu.Item({
  label: _("share_page"),
  context: contextMenu.PageContext(),
  contentScript: 'self.on("click", function (node, data) { self.postMessage({"type":"url", "href":document.URL}); });',
  onMessage: post2friendica
});

contextMenu.Item({
  label: _("share_image"),
  context: contextMenu.SelectorContext("img"),
  contentScript: 'self.on("click", function (node, data) { self.postMessage({"type":"img", "src":node.src, "alt":node.alt}); });',
  onMessage: post2friendica
});

contextMenu.Item({
  label: _("share_link"),
  context: contextMenu.SelectorContext("a[href]"),
  contentScript: 'self.on("click", function (node, data) { self.postMessage({"type":"url", "href": node.href}); });',
  onMessage: post2friendica
});

contextMenu.Item({
  label: _("share_selection"),
  context: contextMenu.SelectionContext(),
  contentScript: 'self.on("click", function (node, data) { self.postMessage({"type":"quote", "source": document.URL, "title":document.title, "text":window.getSelection().toString()}); });',
  onMessage: post2friendica
});
<|endoftext|>


<commit_before>'use strict'

var trello = require("node-trello");
var q = require('q');

// auth
var key = process.env.HUBOT_TRELLO_KEY;
var token = process.env.HUBOT_TRELLO_TOKEN;

var t = new trello(key, token);

module.exports ={

    /*******************************************************************/
    /*                              BOARDS                             */
    /*******************************************************************/

	getBoard: function(id, pars, callback){
        var deferred = q.defer();
        t.get("/1/board/"+id, pars, function(err, data){
			if (err) {
      		    deferred.reject(err);
	        };
            deferred.resolve(data);
	    });
        deferred.promise.nodeify(callback);
	    return deferred.promise;
	},

    /*******************************************************************/
    /*                              MEMBERS                            */
    /*******************************************************************/
	getMembers: function(id, pars, callback){
        var deferred = q.defer();
	    t.get("/1/members/"+id, function(err, data) {
	        if (err) {
      		    deferred.reject(err);
	        };
            deferred.resolve(data);
	    });
        deferred.promise.nodeify(callback);
	    return deferred.promise;
	},

    /*******************************************************************/
    /*                              LISTS                              */
    /*******************************************************************/
	getList: function(id, pars, callback){
		var deferred = q.defer();
		t.get("1/lists/"+id, pars, function(err, data){
			if (err){
				deferred.reject(err);
			};
			deferred.resolve(data);
		});
		deferred.promise.nodeify(callback);
		return deferred.promise;
	},

    /*******************************************************************/
    /*                         TESTING PURPOSES                        */
    /*******************************************************************/
	test: function(k){
		var k;
		t.get("1/board/BE7seI7e",'', function(err, data){
			if (err){
				k = err;
			};
			console.log(`cb: ${data}`);
			k = data;
			return k;
		})
		console.log(`k - test: ${k}`);
	}

}

<commit_msg>update trello-integration<commit_after>'use strict'

var trello = require("node-trello");
var q = require('q');

// auth
var key = process.env.HUBOT_TRELLO_KEY;
var token = process.env.HUBOT_TRELLO_TOKEN;

var t = new trello(key, token);

module.exports ={

    /*******************************************************************/
    /*                              BOARDS                             */
    /*******************************************************************/

	getBoard: function(id, pars, callback){
        var deferred = q.defer();
        t.get("/1/board/"+id, pars, function(err, data){
			if (err) {
      		    deferred.reject(err);
	        };
            deferred.resolve(data);
	    });
        deferred.promise.nodeify(callback);
	    return deferred.promise;
	},

    /*******************************************************************/
    /*                              MEMBERS                            */
    /*******************************************************************/
	getMembers: function(id, pars, callback){
        var deferred = q.defer();
	    t.get("/1/members/"+id, function(err, data) {
	        if (err) {
      		    deferred.reject(err);
	        };
            deferred.resolve(data);
	    });
        deferred.promise.nodeify(callback);
	    return deferred.promise;
	},

    /*******************************************************************/
    /*                              LISTS                              */
    /*******************************************************************/
	getList: function(id, pars, callback){
		var deferred = q.defer();
		t.get("1/lists/"+id, pars, function(err, data){
			if (err){
				deferred.reject(err);
			};
			deferred.resolve(data);
		});
		deferred.promise.nodeify(callback);
		return deferred.promise;
	},

    /*******************************************************************/
    /*                         TESTING PURPOSES                        */
    /*******************************************************************/
	test: function(k){
		var k;
		k = t.get("1/board/BE7seI7e",'', function(err, data){
			if (err){
				k = err;
			};
			console.log(`cb: ${data}`);
			k = data;
			return k;
		})
		return k;
		console.log(`k - test: ${k}`);
	}

}

<|endoftext|>