<commit_before>  /**
   * Author: Shibin George
   *         https://www.linkedin.com/in/sg1993
   **/

function dummyLoading(t){
  var status = document.getElementById('status');
  var w = document.createElement('div');
  w.innerHTML = "<img class='icon' src=" + chrome.extension.getURL('assets/loading.gif') + "";
  status.appendChild(w);
  for(i=0;i<t*1000;i++){
    for(j=0;j<t*1000;j++){

    }
  }
}

function returnShortName(s, d){
  var shortname="";
  if(s.length > d){
    shortname = s.substring(0, d) + '..';
  } else {
    shortname = s;
  }
  return shortname;
}

function toggle(){
  var c = document.getElementById('CheckAll');
  if(c.className == 'Profile'){
    c.className = 'SelectedProfile';
  } else {
    c.className = 'Profile';
  }
  var bool = c.className;
    //renderStatus(" " + bool + "");
    var checks = document.getElementsByName('Checkbox');

    for(i=0;i<checks.length;i++){
    //console.log('toggle called for ' + i + ' currently ' + checks[i].checked);
    //if(checks[i].type=='checkbox'){
      checks[i].className = bool;
    //}
  }
}

function finalizeChoice(addNewProfile){
  var tabs = document.getElementsByName('Checkbox');
  var s = "";
  var value = [];
  var numChoices = 0;
  console.log("Number of checkboxes = " + tabs.length);
  for(i=0; i<tabs.length; i++){
    if(tabs[i].className == 'SelectedProfile'){
      //this particular tab has to be added
      s += returnShortName(tabs[i].id, 20) + "\n";
      value.push(tabs[i].id);
      numChoices += 1;
    }
  }

  document.getElementById('status').innerHTML = '';
  var tnode;
  var status = document.getElementById('status');

  if(numChoices <= 0){
    status.innerHTML = "You must choose atleast one tab.";
  } else if(addNewProfile){
    //Save to a new Session
    var rand = Math.floor(Math.random()*101010);
    var inputHTML = '\nEnter the Session name: <input type="text" id="ProfileName" value="Profile' + rand + '">
';
    var buttonHTML = ''
    status.innerHTML = 'You have chosen the following tabs:\n\n' + s + inputHTML ;

    var button = document.createElement("div");
    button.setAttribute("id", "ProfileSubmitButton");
    button.innerHTML = '\n** NOTE: The session name above is randomly generated.\
    \nIt is highly recommended that you change the name\
    \nto something not used before. Otherwise, this may\
    \nlead to the profile being overwritten. Keep it short and simple.\
    \nBeam me up, Scotty!\
    \n\
    \n'
    var b = document.createElement("BUTTON");
    var t = document.createTextNode("Save The Session");
    b.appendChild(t);
    button.appendChild(b);
    button.style.fontSize = "smaller";
    button.style.color = "red";
    status.appendChild(button);

    b.onclick = function(){
      var key = document.getElementById("ProfileName").value;
      var obj = {};
      obj[key] = value;
      /*  write the profile to the local storage */
      chrome.storage.local.set(obj);
      renderStatus('Session saved to: ' + key);
    }
  } else {
    // Add to an existing Session
    // At this point, list the Profiles to choose from
    processProfiles(false, function(profiles) {
      console.log("back to finalize " + profiles);
      profiles.forEach(function(profile, index){
        chrome.storage.local.get(profile, function(db){
          console.log("before: " + db[profile].length);
          var obj = {};
          obj[profile] = db[profile].concat(value);
          chrome.storage.local.set(obj);
          console.log("after: " + obj[profile].length);
        });
      });
    });
  }
}

function renderStatus(statusText) {
  document.getElementById('status').textContent = statusText;
}

function listProfiles(){

  chrome.storage.local.get(null, function(items) {
    var allKeys = Object.keys(items);
    //debug();

    /*list all the existing options on loading*/
    var profile = new Array(allKeys.length);;
    var status = document.getElementById('status');
    var profileList = document.createElement("div");
    profileList.setAttribute("id", "ProfileList");
    status.appendChild(profileList);

    for(i=0;i<allKeys.length;i++){
      profile[i] = document.createElement("div");
      profile[i].setAttribute("id", allKeys[i]);
      profile[i].setAttribute("class", "Profile");
      profile[i].innerHTML = "\t" + allKeys[i];
      profileList.appendChild(profile[i]);

      //profile.setAttribute("onclick", "loadProfile(this.innerHTML)");
      profile[i].addEventListener("click", function(){
        loadProfile(this.id);
      });

    }
    addSeparator('status');
     /*
      * Profiles have been loaded.
      * Adding the "Save The Session" option
      */

    //var icon = document.createElement("div");
    //icon.setAttribute("class", "icon");

    var newProfile = document.createElement("div");
    newProfile.setAttribute("id", "NewProfile");
    newProfile.setAttribute("class", "ProfileOption");
    newProfile.innerHTML = "    Save The Session";
    newProfile.style.fontWeight = "bold";
    //newProfile.appendChild(icon);
    status.appendChild(newProfile);

    var addToExisting = document.createElement("div");
    addToExisting.setAttribute("id", "addToExisting");
    addToExisting.setAttribute("class", "ProfileOption");
    addToExisting.innerHTML = "\tAdd to existing Session";
    status.appendChild(addToExisting);

    var removeProfile = document.createElement("div");
    removeProfile.setAttribute("id", "RemoveProfile");
    removeProfile.setAttribute("class", "ProfileOption");
    removeProfile.innerHTML = "\tRemove saved Session";
    status.appendChild(removeProfile);

    newProfile.addEventListener("click", function(){
      queryTabs(true);
    });

    removeProfile.addEventListener("click", function(){
      //renderStatus('remove-profile coming soon');
      processProfiles(true);
    });

    addToExisting.addEventListener("click", function(){
    //renderStatus('remove-profile coming soon');
      addToProfile();
    });

    addSeparator('status');

    // Add Soure-code link
    var sourceCode = document.createElement("div");
    sourceCode.setAttribute("id", "sourceCode");
    sourceCode.setAttribute("class", "AboutOption");
    var version = chrome.runtime.getManifest().version;
    sourceCode.innerHTML = "\tKnow more about the extension"
                         + " (v" + version + ")";
    status.appendChild(sourceCode);

    // Add Linkedin profile as well
    var developer = document.createElement("div");
    developer.setAttribute("id", "sourceCode");
    developer.setAttribute("class", "AboutOption");
    developer.innerHTML = "\tWanna know more about me?";
    status.appendChild(developer);

  });
}

function addSeparator(parentId){
  var sep = document.createElement("div");
  var parent = document.getElementById(parentId);
  sep.setAttribute("id", "separator1");
  sep.setAttribute("class", "separator");
  parent.appendChild(sep);
}

function loadProfile(profile){

  chrome.storage.local.get(profile, function(item){
    tabURLs = [];
    console.log(item[profile]);
    //console.log(tabURLs);

    /*
     *  This is where the new window
     *  is created, and populated with
     *  the list of URLs saved in the
     *  profile.
     */
     chrome.windows.create({url:item[profile]}, function(window){
      console.log("hola amigos");
    });
   });
}

function clearLocalStorage(){
  chrome.storage.local.clear(function(){
    console.log(chrome.runtime.lastError);
  });
}

chrome.runtime.setUninstallURL("https://github.com/sg1993/Save-The-Session/blob/master/UNINSTALL.md", null);

document.addEventListener('DOMContentLoaded', function() {
  listProfiles();
});
<commit_msg>Check if no sessions have been saved yet<commit_after>  /**
   * Author: Shibin George
   *         https://www.linkedin.com/in/sg1993
   **/

function dummyLoading(t){
  var status = document.getElementById('status');
  var w = document.createElement('div');
  w.innerHTML = "<img class='icon' src=" + chrome.extension.getURL('assets/loading.gif') + "";
  status.appendChild(w);
  for(i=0;i<t*1000;i++){
    for(j=0;j<t*1000;j++){

    }
  }
}

function returnShortName(s, d){
  var shortname="";
  if(s.length > d){
    shortname = s.substring(0, d) + '..';
  } else {
    shortname = s;
  }
  return shortname;
}

function toggle(){
  var c = document.getElementById('CheckAll');
  if(c.className == 'Profile'){
    c.className = 'SelectedProfile';
  } else {
    c.className = 'Profile';
  }
  var bool = c.className;
    //renderStatus(" " + bool + "");
    var checks = document.getElementsByName('Checkbox');

    for(i=0;i<checks.length;i++){
    //console.log('toggle called for ' + i + ' currently ' + checks[i].checked);
    //if(checks[i].type=='checkbox'){
      checks[i].className = bool;
    //}
  }
}

function finalizeChoice(addNewProfile){
  var tabs = document.getElementsByName('Checkbox');
  var s = "";
  var value = [];
  var numChoices = 0;
  console.log("Number of checkboxes = " + tabs.length);
  for(i=0; i<tabs.length; i++){
    if(tabs[i].className == 'SelectedProfile'){
      //this particular tab has to be added
      s += returnShortName(tabs[i].id, 20) + "\n";
      value.push(tabs[i].id);
      numChoices += 1;
    }
  }

  document.getElementById('status').innerHTML = '';
  var tnode;
  var status = document.getElementById('status');

  if(numChoices <= 0){
    status.innerHTML = "You must choose atleast one tab.";
  } else if(addNewProfile){
    //Save to a new Session
    var rand = Math.floor(Math.random()*101010);
    var inputHTML = '\nEnter the Session name: <input type="text" id="ProfileName" value="Profile' + rand + '">
';
    var buttonHTML = ''
    status.innerHTML = 'You have chosen the following tabs:\n\n' + s + inputHTML ;

    var button = document.createElement("div");
    button.setAttribute("id", "ProfileSubmitButton");
    button.innerHTML = '\n** NOTE: The session name above is randomly generated.\
    \nIt is highly recommended that you change the name\
    \nto something not used before. Otherwise, this may\
    \nlead to the profile being overwritten. Keep it short and simple.\
    \nBeam me up, Scotty!\
    \n\
    \n'
    var b = document.createElement("BUTTON");
    var t = document.createTextNode("Save The Session");
    b.appendChild(t);
    button.appendChild(b);
    button.style.fontSize = "smaller";
    button.style.color = "red";
    status.appendChild(button);

    b.onclick = function(){
      var key = document.getElementById("ProfileName").value;
      var obj = {};
      obj[key] = value;
      /*  write the profile to the local storage */
      chrome.storage.local.set(obj);
      renderStatus('Session saved to: ' + key);
    }
  } else {
    // Add to an existing Session
    // At this point, list the Profiles to choose from
    processProfiles(false, function(profiles) {
      console.log("back to finalize " + profiles);
      profiles.forEach(function(profile, index){
        chrome.storage.local.get(profile, function(db){
          console.log("before: " + db[profile].length);
          var obj = {};
          obj[profile] = db[profile].concat(value);
          chrome.storage.local.set(obj);
          console.log("after: " + obj[profile].length);
        });
      });
    });
  }
}

function renderStatus(statusText) {
  document.getElementById('status').textContent = statusText;
}

function listProfiles(){

  chrome.storage.local.get(null, function(items) {
    var allKeys = Object.keys(items);
    //debug();

    /*list all the existing options on loading*/
    var profile = new Array(allKeys.length);;
    var status = document.getElementById('status');
    var profileList = document.createElement("div");
    profileList.setAttribute("id", "ProfileList");
    status.appendChild(profileList);

    if(allKeys.length == 0){
      status.innerHTML = "\nYou haven't saved any Sessions yet. Get started now!\n\n";
    }

    for(i=0;i<allKeys.length;i++){
      profile[i] = document.createElement("div");
      profile[i].setAttribute("id", allKeys[i]);
      profile[i].setAttribute("class", "Profile");
      profile[i].innerHTML = "\t" + allKeys[i];
      profileList.appendChild(profile[i]);

      //profile.setAttribute("onclick", "loadProfile(this.innerHTML)");
      profile[i].addEventListener("click", function(){
        loadProfile(this.id);
      });

    }
    addSeparator('status');
     /*
      * Profiles have been loaded.
      * Adding the "Save The Session" option
      */

    //var icon = document.createElement("div");
    //icon.setAttribute("class", "icon");

    var newProfile = document.createElement("div");
    newProfile.setAttribute("id", "NewProfile");
    newProfile.setAttribute("class", "ProfileOption");
    newProfile.innerHTML = "    Save The Session";
    newProfile.style.fontWeight = "bold";
    //newProfile.appendChild(icon);
    status.appendChild(newProfile);

    var addToExisting = document.createElement("div");
    addToExisting.setAttribute("id", "addToExisting");
    addToExisting.setAttribute("class", "ProfileOption");
    addToExisting.innerHTML = "\tAdd to existing Session";
    status.appendChild(addToExisting);

    var removeProfile = document.createElement("div");
    removeProfile.setAttribute("id", "RemoveProfile");
    removeProfile.setAttribute("class", "ProfileOption");
    removeProfile.innerHTML = "\tRemove saved Session";
    status.appendChild(removeProfile);

    newProfile.addEventListener("click", function(){
      queryTabs(true);
    });

    removeProfile.addEventListener("click", function(){
      //renderStatus('remove-profile coming soon');
      processProfiles(true);
    });

    addToExisting.addEventListener("click", function(){
    //renderStatus('remove-profile coming soon');
      addToProfile();
    });

    addSeparator('status');

    // Add Soure-code link
    var sourceCode = document.createElement("div");
    sourceCode.setAttribute("id", "sourceCode");
    sourceCode.setAttribute("class", "AboutOption");
    var version = chrome.runtime.getManifest().version;
    sourceCode.innerHTML = "\tKnow more about the extension"
                         + " (v" + version + ")";
    status.appendChild(sourceCode);

    // Add Linkedin profile as well
    var developer = document.createElement("div");
    developer.setAttribute("id", "sourceCode");
    developer.setAttribute("class", "AboutOption");
    developer.innerHTML = "\tWanna know more about me?";
    status.appendChild(developer);

  });
}

function addSeparator(parentId){
  var sep = document.createElement("div");
  var parent = document.getElementById(parentId);
  sep.setAttribute("id", "separator1");
  sep.setAttribute("class", "separator");
  parent.appendChild(sep);
}

function loadProfile(profile){

  chrome.storage.local.get(profile, function(item){
    tabURLs = [];
    console.log(item[profile]);
    //console.log(tabURLs);

    /*
     *  This is where the new window
     *  is created, and populated with
     *  the list of URLs saved in the
     *  profile.
     */
     chrome.windows.create({url:item[profile]}, function(window){
      console.log("hola amigos");
    });
   });
}

function clearLocalStorage(){
  chrome.storage.local.clear(function(){
    console.log(chrome.runtime.lastError);
  });
}

chrome.runtime.setUninstallURL("https://github.com/sg1993/Save-The-Session/blob/master/UNINSTALL.md", null);

document.addEventListener('DOMContentLoaded', function() {
  listProfiles();
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import DS from 'ember-data';

const { Component, computed, inject, RSVP, isEmpty, isPresent } = Ember;
const { service } = inject;
const { PromiseArray } = DS;

export default Component.extend({
  store: service(),
  i18n: service(),
  currentUser: service(),
  flashMessages: service(),
  classNames: ['form-container', 'detail-view', 'new-myreport', 'mesh-manager'],
  title: null,
  currentSchool: null,
  currentSubject: 'course',
  currentPrepositionalObject: null,
  currentPrepositionalObjectId: null,
  subjectList: computed('i18n.locale', function(){
    let list = [
      {value: 'course', label: this.get('i18n').t('general.courses')},
      {value: 'session', label: this.get('i18n').t('general.sessions')},
      {value: 'program', label: this.get('i18n').t('general.programs')},
      {value: 'program year', label: this.get('i18n').t('general.programYears')},
      {value: 'instructor', label: this.get('i18n').t('general.instructors')},
      {value: 'instructor group', label: this.get('i18n').t('general.instructorGroups')},
      {value: 'learning material', label: this.get('i18n').t('general.learningMaterials')},
      {value: 'competency', label: this.get('i18n').t('general.competencies')},
      {value: 'topic', label: this.get('i18n').t('general.topics')},
      {value: 'mesh term', label: this.get('i18n').t('general.meshTerms')},
      {value: 'session type', label: this.get('i18n').t('general.sessionTypes')},
    ];

    return list;
  }),
  prepositionalObjectList: computed('i18n.locale', 'currentSubject', function(){
    let list = [
      {value: 'course', label: this.get('i18n').t('general.course'), subjects: ['session', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'topic', 'mesh term']},
      {value: 'session', label: this.get('i18n').t('general.session'), subjects: ['course', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'topic', 'mesh term', 'session type']},
      {value: 'program', label: this.get('i18n').t('general.program'), subjects: ['course', 'session', 'topic']},
      {value: 'instructor', label: this.get('i18n').t('general.instructor'), subjects: ['course', 'session', 'instructor group', 'learning material', 'topic', 'session type']},
      {value: 'instructor group', label: this.get('i18n').t('general.instructorGroup'), subjects: ['course', 'session', 'instructor', 'learning material', 'topic', 'session type']},
      {value: 'learning material', label: this.get('i18n').t('general.learningMaterial'), subjects: ['course', 'session', 'instructor', 'instructor group', 'topic', 'mesh term', 'sessiontype']},
      {value: 'competency', label: this.get('i18n').t('general.competency'), subjects: ['course', 'session', 'topic', 'session type']},
      {value: 'topic', label: this.get('i18n').t('general.topic'), subjects: ['course', 'session', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'mesh term']},
      {value: 'mesh term', label: this.get('i18n').t('general.meshTerm'), subjects: ['course', 'session', 'learning material', 'topic', 'session type']},
      {value: 'session type', label: this.get('i18n').t('general.sessionType'), subjects: ['session', 'instructor', 'instructor group', 'learning material', 'competency', 'topic', 'mesh term']},
    ];

    const subject = this.get('currentSubject');

    return list.filter(item =>item.subjects.contains(subject));
  }),
  prepositionalObjectIdList: computed('currentPrepositionalObject', 'currentSchool', function(){
    const type = this.get('currentPrepositionalObject');
    if(isEmpty(type) || type === 'instructor'){
      return [];
    }
    let defer = RSVP.defer();
    let model = type.dasherize();
    const store = this.get('store');
    let query = {
      limit: 1000,
      filters: {}
    };
    let schoolScopedModels = [
      'topic',
      'session',
      'program',
      'session-type',
      'instructor-group',
      'competency',
    ];
    if(schoolScopedModels.contains(model)){
      query.filters.school = this.get('currentSchool').get('id');
    }
    store.query(model, query).then(objects => {
      let label = type === 'mesh term'?'name':'title';
      let values = objects.map(object => {
        return {
          value: object.get('id'),
          label: object.get(label)
        };
      }).sortBy('label');

      defer.resolve(values);
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  currentSubjectLabel: computed('currentSubject', 'subjectList.[]', function(){
    const currentSubjectValue = this.get('currentSubject');
    let currentSubject = this.get('subjectList').find(subject => {
      return subject.value === currentSubjectValue;
    });

    return currentSubject.label;
  }),
  selectedUser: computed('currentPrepositionalObject', 'currentPrepositionalObjectId', function(){
    if(
      this.get('currentPrepositionalObject') === 'instructor' &&
      this.get('currentPrepositionalObjectId')
    ){
      return this.get('store').peekRecord('user', this.get('currentPrepositionalObjectId'));
    } else {
      return null;
    }
  }),
  selectedMeshTerm: computed('currentPrepositionalObject', 'currentPrepositionalObjectId', function(){
    if(
      this.get('currentPrepositionalObject') === 'mesh term' &&
      this.get('currentPrepositionalObjectId')
    ){
      return this.get('store').peekRecord('mesh-descriptor', this.get('currentPrepositionalObjectId'));
    } else {
      return null;
    }
  }),
  schoolList: computed('currentUser.schools.[]',function(){
    let defer = RSVP.defer();
    this.get('currentUser').get('model').then(user => {
      user.get('schools').then(schools => {
        defer.resolve(schools.sortBy('title'));
      });
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  actions: {
    changeSchool(schoolId){
      let school = this.get('schoolList').find(school =>  school.get('id') === schoolId);
      this.set('currentSchool', school);
    },
    changeSubject(subject){
      this.set('currentSubject', subject);
    },
    changePrepositionalObject(object){
      this.set('currentPrepositionalObject', object);
      this.set('currentPrepositionalObjectId', null);
    },
    changePrepositionalObjectId(id){
      this.set('currentPrepositionalObjectId', id);
    },
    chooseInstructor(user){
      this.set('currentPrepositionalObjectId', user.get('id'));
    },
    chooseMeshTerm(term){
      this.set('currentPrepositionalObjectId', term.get('id'));
    },
    closeEditor(){
      this.sendAction('close');
    },
    save(){
      const flashMessages = this.get('flashMessages');
      const store = this.get('store');
      const subject = this.get('currentSubject');
      let object = this.get('currentPrepositionalObject');
      if(isPresent(subject) && isEmpty(object)) {
        if(subject === 'instructor'){
          flashMessages.alert('dashboard.reportMissingObjectForInstructor');
          return;
        }
        if(subject === 'mesh term'){
          flashMessages.alert('dashboard.reportMissingObjectForMeshTerm');
          return;
        }
      }
      if(
        object &&
        !this.get('currentPrepositionalObjectId')
      ) {
        if(object === 'instructor'){
          flashMessages.alert('dashboard.reportMissingInstructor');
        }
        if(object === 'mesh term'){
          flashMessages.alert('dashboard.reportMissingMeshTerm');
        }
        return;
      }
      this.get('currentUser.model').then(user => {

        let title = this.get('title');
        let subject = this.get('currentSubject');
        let prepositionalObject = this.get('currentPrepositionalObject');
        let prepositionalObjectTableRowId = this.get('currentPrepositionalObjectId');
        let school = this.get('currentSchool');
        let report = store.createRecord('report', {
          title,
          user,
          subject,
          prepositionalObject,
          prepositionalObjectTableRowId,
          school
        });
        report.save().then(() => {
          this.sendAction('close');
        });
      });
    }
  }
});
<commit_msg>Stop trying to scope by school when no school is present<commit_after>import Ember from 'ember';
import DS from 'ember-data';

const { Component, computed, inject, RSVP, isEmpty, isPresent } = Ember;
const { service } = inject;
const { PromiseArray } = DS;

export default Component.extend({
  store: service(),
  i18n: service(),
  currentUser: service(),
  flashMessages: service(),
  classNames: ['form-container', 'detail-view', 'new-myreport', 'mesh-manager'],
  title: null,
  currentSchool: null,
  currentSubject: 'course',
  currentPrepositionalObject: null,
  currentPrepositionalObjectId: null,
  subjectList: computed('i18n.locale', function(){
    let list = [
      {value: 'course', label: this.get('i18n').t('general.courses')},
      {value: 'session', label: this.get('i18n').t('general.sessions')},
      {value: 'program', label: this.get('i18n').t('general.programs')},
      {value: 'program year', label: this.get('i18n').t('general.programYears')},
      {value: 'instructor', label: this.get('i18n').t('general.instructors')},
      {value: 'instructor group', label: this.get('i18n').t('general.instructorGroups')},
      {value: 'learning material', label: this.get('i18n').t('general.learningMaterials')},
      {value: 'competency', label: this.get('i18n').t('general.competencies')},
      {value: 'topic', label: this.get('i18n').t('general.topics')},
      {value: 'mesh term', label: this.get('i18n').t('general.meshTerms')},
      {value: 'session type', label: this.get('i18n').t('general.sessionTypes')},
    ];

    return list;
  }),
  prepositionalObjectList: computed('i18n.locale', 'currentSubject', function(){
    let list = [
      {value: 'course', label: this.get('i18n').t('general.course'), subjects: ['session', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'topic', 'mesh term']},
      {value: 'session', label: this.get('i18n').t('general.session'), subjects: ['course', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'topic', 'mesh term', 'session type']},
      {value: 'program', label: this.get('i18n').t('general.program'), subjects: ['course', 'session', 'topic']},
      {value: 'instructor', label: this.get('i18n').t('general.instructor'), subjects: ['course', 'session', 'instructor group', 'learning material', 'topic', 'session type']},
      {value: 'instructor group', label: this.get('i18n').t('general.instructorGroup'), subjects: ['course', 'session', 'instructor', 'learning material', 'topic', 'session type']},
      {value: 'learning material', label: this.get('i18n').t('general.learningMaterial'), subjects: ['course', 'session', 'instructor', 'instructor group', 'topic', 'mesh term', 'sessiontype']},
      {value: 'competency', label: this.get('i18n').t('general.competency'), subjects: ['course', 'session', 'topic', 'session type']},
      {value: 'topic', label: this.get('i18n').t('general.topic'), subjects: ['course', 'session', 'program', 'program year', 'instructor', 'instructor group', 'learning material', 'competency', 'mesh term']},
      {value: 'mesh term', label: this.get('i18n').t('general.meshTerm'), subjects: ['course', 'session', 'learning material', 'topic', 'session type']},
      {value: 'session type', label: this.get('i18n').t('general.sessionType'), subjects: ['session', 'instructor', 'instructor group', 'learning material', 'competency', 'topic', 'mesh term']},
    ];

    const subject = this.get('currentSubject');

    return list.filter(item =>item.subjects.contains(subject));
  }),
  prepositionalObjectIdList: computed('currentPrepositionalObject', 'currentSchool', function(){
    const type = this.get('currentPrepositionalObject');
    if(isEmpty(type) || type === 'instructor'){
      return [];
    }
    let defer = RSVP.defer();
    let model = type.dasherize();
    const store = this.get('store');
    const school = this.get('currentSchool');
    let query = {
      limit: 1000,
      filters: {}
    };
    if(isPresent(school)){
      let schoolScopedModels = [
        'topic',
        'session',
        'program',
        'session-type',
        'instructor-group',
        'competency',
      ];
      if(schoolScopedModels.contains(model)){
        query.filters.school = this.get('currentSchool').get('id');
      }
    }

    store.query(model, query).then(objects => {
      let label = type === 'mesh term'?'name':'title';
      let values = objects.map(object => {
        return {
          value: object.get('id'),
          label: object.get(label)
        };
      }).sortBy('label');

      defer.resolve(values);
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  currentSubjectLabel: computed('currentSubject', 'subjectList.[]', function(){
    const currentSubjectValue = this.get('currentSubject');
    let currentSubject = this.get('subjectList').find(subject => {
      return subject.value === currentSubjectValue;
    });

    return currentSubject.label;
  }),
  selectedUser: computed('currentPrepositionalObject', 'currentPrepositionalObjectId', function(){
    if(
      this.get('currentPrepositionalObject') === 'instructor' &&
      this.get('currentPrepositionalObjectId')
    ){
      return this.get('store').peekRecord('user', this.get('currentPrepositionalObjectId'));
    } else {
      return null;
    }
  }),
  selectedMeshTerm: computed('currentPrepositionalObject', 'currentPrepositionalObjectId', function(){
    if(
      this.get('currentPrepositionalObject') === 'mesh term' &&
      this.get('currentPrepositionalObjectId')
    ){
      return this.get('store').peekRecord('mesh-descriptor', this.get('currentPrepositionalObjectId'));
    } else {
      return null;
    }
  }),
  schoolList: computed('currentUser.schools.[]',function(){
    let defer = RSVP.defer();
    this.get('currentUser').get('model').then(user => {
      user.get('schools').then(schools => {
        defer.resolve(schools.sortBy('title'));
      });
    });
    return PromiseArray.create({
      promise: defer.promise
    });
  }),
  actions: {
    changeSchool(schoolId){
      let school = this.get('schoolList').find(school =>  school.get('id') === schoolId);
      this.set('currentSchool', school);
    },
    changeSubject(subject){
      this.set('currentSubject', subject);
    },
    changePrepositionalObject(object){
      this.set('currentPrepositionalObject', object);
      this.set('currentPrepositionalObjectId', null);
    },
    changePrepositionalObjectId(id){
      this.set('currentPrepositionalObjectId', id);
    },
    chooseInstructor(user){
      this.set('currentPrepositionalObjectId', user.get('id'));
    },
    chooseMeshTerm(term){
      this.set('currentPrepositionalObjectId', term.get('id'));
    },
    closeEditor(){
      this.sendAction('close');
    },
    save(){
      const flashMessages = this.get('flashMessages');
      const store = this.get('store');
      const subject = this.get('currentSubject');
      let object = this.get('currentPrepositionalObject');
      if(isPresent(subject) && isEmpty(object)) {
        if(subject === 'instructor'){
          flashMessages.alert('dashboard.reportMissingObjectForInstructor');
          return;
        }
        if(subject === 'mesh term'){
          flashMessages.alert('dashboard.reportMissingObjectForMeshTerm');
          return;
        }
      }
      if(
        object &&
        !this.get('currentPrepositionalObjectId')
      ) {
        if(object === 'instructor'){
          flashMessages.alert('dashboard.reportMissingInstructor');
        }
        if(object === 'mesh term'){
          flashMessages.alert('dashboard.reportMissingMeshTerm');
        }
        return;
      }
      this.get('currentUser.model').then(user => {

        let title = this.get('title');
        let subject = this.get('currentSubject');
        let prepositionalObject = this.get('currentPrepositionalObject');
        let prepositionalObjectTableRowId = this.get('currentPrepositionalObjectId');
        let school = this.get('currentSchool');
        let report = store.createRecord('report', {
          title,
          user,
          subject,
          prepositionalObject,
          prepositionalObjectTableRowId,
          school
        });
        report.save().then(() => {
          this.sendAction('close');
        });
      });
    }
  }
});
<|endoftext|>


<commit_before>window.onload = function () {
    // Get container elements
    var containers = [
        document.getElementById('currentCurator'),
        document.getElementById('nextCurator'),
        document.getElementById('followingCurator')
    ];
    var successive = document.getElementById('successiveCurators');
    var alertClose = document.getElementById('alert-close');

    // Get file path, add time-stamp to prevent caching
    var filePath = 'https://scratchtools.tk/fpc/api/v2/json/?u=' + new Date().getTime();

    // Init http request
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.ontimeout = function() {
        console.log('Timeout');
        error();
    };

    xmlHttp.onerror = function() {
        console.log('Error');
        error();
    };

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
            try {
                downloaded(JSON.parse(xmlHttp.responseText));
            } catch(e) {
                if (e instanceof SyntaxError) {
                    error();
                    console.log('Bad JSON syntax');
                } else {
                    throw e;
                }
            }
        }
    };

    xmlHttp.open('GET', filePath, true);
    xmlHttp.timeout = 5000;

    // Send http request
    xmlHttp.send(null);

    // Interpret downloaded data
    function downloaded(result) {
        // Check response was valid
        if (result['response']['code'] === 0) {

            // Load current, next and following curators
            for (var i = 0; i < 3; i++) {

                // Display week range

                var date = document.createElement('span');

                date.className = 'date';
                date.innerText =
                        formatDate(new Date(result['curators'][i]['start'])) +
                        ' - ' +
                        formatDate(new Date(result['curators'][i]['end']));

                containers[i].parentElement.insertBefore(
                        date,
                        containers[i].parentElement.childNodes[0]
                );

                // Load curator

                // Check curator is known

                if (result['curators'][i]['user']) {

                    // Check if FPC is confirmed

                    if (result['curators'][i]['confirmed']) {
                        //FPC was confirmed

                        containers[i].innerHTML =
                                '@' +
                                result['curators'][i]['user'] +
                                '';

                        containers[i].parentElement.href = result['curators'][i]['suggest_url'];
                        containers[i].className = '';
                    } else {
                        //FPC not confirmed

                        containers[i].innerHTML =
                                '@' +
                                result['curators'][i]['user'] +
                                ' (TBC)';
                        containers[i].className = 'gray';
                    }
                } else {
                    containers[i].title = 'The FPC during this period is currently unknown';
                    containers[i].innerText = 'Unknown';
                }
            }

            // Check if there are successive curators

            if (result['curators'].length > 2) {
                // There are successive curators

                // For each successive curator
                for (var i = 3; i < result['curators'].length; i++) {
                    // Add date
                    successive.innerHTML += 'Start - End';

                    // Check if curator has been suggested
                    if (result['curators'][i]['user']) {
                        // Curator has been suggested

                        // Check if curator is confirmed

                        if (result['curators'][i]['confirmed']) {
                            // Curator is confirmed

                            successive.innerHTML +=
                                    '@' +
                                    result['curators'][i]['user'] + '';
                        } else {
                            // Curator isn't confirmed, so display TBC label
                            // and add no link

                            successive.innerHTML +=
                                    '@' +
                                    result['curators'][i]['user'] +
                                    ' (TBC)';
                        }
                    } else {
                        // No known FPC for this period

                        // Display unknown message
                        successive.innerHTML +=
                                'Unknown';
                    }
                }

                // Show container for successive curators
                document.getElementById('successiveContainer').className = 'box hover-box';
            }

            // Show notice
            if (result['message']) {
                document.getElementById('alert-text').innerHTML = result['message'];
                document.getElementById('alert').className = 'box';
            }
        } else {
            error();
            console.log(
                    'Error: code ' +
                    result['response']['code'] +
                    ' - ' +
                    result['response']['description']
            );
        }
    }

    // Display error messages in every container
    function error() {
        // TODO: on error, hide containers and show separate div
        containers[0].innerText = 'Error';
        containers[1].innerText = 'Error';
        containers[2].innerText = 'Error';
    }

    // Loads the curator name into the specified container
    function load(user, element) {
        // Check if curator has been suggested

        if (user !== '') {
            // Curator has been suggested for this period

            var date = document.createElement('span');

            date.className = 'date';
            date.innerText = 'Start - End';

            element.parentElement.insertBefore(date, element.parentElement.childNodes[0]);

            if (user.endsWith('?')) {
                //FPC not confirmed

                element.innerHTML =
                        '@' +
                        user.substring(0, user.length - 1) +
                        ' (TBC)';
                element.className = 'gray';
            } else {
                //FPC was confirmed

                element.innerHTML = '@' + user + '';
                element.parentElement.href = 'https://scratch.mit.edu/users/' + user + '/';
                element.className = '';
            }
        }
    }

    // Makes a date human readable
    // Uses browser language to match users prefrences
    function formatDate(d) {
        return d.toLocaleString(navigator.language, {
            day: "numeric",
            month: "short"
        });
    }

    // Add close button click event
    alertClose.onclick = function() {
        document.getElementById('alert').className = 'hidden';
    };
};<commit_msg>Correct terminology<commit_after>window.onload = function () {
    // Get container elements
    var containers = [
        document.getElementById('currentCurator'),
        document.getElementById('nextCurator'),
        document.getElementById('followingCurator')
    ];
    var successive = document.getElementById('successiveCurators');
    var alertClose = document.getElementById('alert-close');

    // Get file path, add time-stamp to prevent caching
    var filePath = 'https://scratchtools.tk/fpc/api/v2/json/?u=' + new Date().getTime();

    // Init http request
    var xmlHttp = new XMLHttpRequest();

    xmlHttp.ontimeout = function() {
        console.log('Timeout');
        error();
    };

    xmlHttp.onerror = function() {
        console.log('Error');
        error();
    };

    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
            try {
                downloaded(JSON.parse(xmlHttp.responseText));
            } catch(e) {
                if (e instanceof SyntaxError) {
                    error();
                    console.log('Bad JSON syntax');
                } else {
                    throw e;
                }
            }
        }
    };

    xmlHttp.open('GET', filePath, true);
    xmlHttp.timeout = 5000;

    // Send http request
    xmlHttp.send(null);

    // Interpret downloaded data
    function downloaded(result) {
        // Check response was successful
        if (result['response']['code'] === 0) {

            // Load current, next and following curators
            for (var i = 0; i < 3; i++) {

                // Display week range

                var date = document.createElement('span');

                date.className = 'date';
                date.innerText =
                        formatDate(new Date(result['curators'][i]['start'])) +
                        ' - ' +
                        formatDate(new Date(result['curators'][i]['end']));

                containers[i].parentElement.insertBefore(
                        date,
                        containers[i].parentElement.childNodes[0]
                );

                // Load curator

                // Check curator is known

                if (result['curators'][i]['user']) {

                    // Check if FPC is confirmed

                    if (result['curators'][i]['confirmed']) {
                        //FPC was confirmed

                        containers[i].innerHTML =
                                '@' +
                                result['curators'][i]['user'] +
                                '';

                        containers[i].parentElement.href = result['curators'][i]['suggest_url'];
                        containers[i].className = '';
                    } else {
                        //FPC not confirmed

                        containers[i].innerHTML =
                                '@' +
                                result['curators'][i]['user'] +
                                ' (TBC)';
                        containers[i].className = 'gray';
                    }
                } else {
                    containers[i].title = 'The FPC during this period is currently unknown';
                    containers[i].innerText = 'Unknown';
                }
            }

            // Check if there are successive curators

            if (result['curators'].length > 2) {
                // There are successive curators

                // For each successive curator
                for (var i = 3; i < result['curators'].length; i++) {
                    // Add date
                    successive.innerHTML += 'Start - End';

                    // Check if curator has been suggested
                    if (result['curators'][i]['user']) {
                        // Curator has been suggested

                        // Check if curator is confirmed

                        if (result['curators'][i]['confirmed']) {
                            // Curator is confirmed

                            successive.innerHTML +=
                                    '@' +
                                    result['curators'][i]['user'] + '';
                        } else {
                            // Curator isn't confirmed, so display TBC label
                            // and add no link

                            successive.innerHTML +=
                                    '@' +
                                    result['curators'][i]['user'] +
                                    ' (TBC)';
                        }
                    } else {
                        // No known FPC for this period

                        // Display unknown message
                        successive.innerHTML +=
                                'Unknown';
                    }
                }

                // Show container for successive curators
                document.getElementById('successiveContainer').className = 'box hover-box';
            }

            // Show notice
            if (result['message']) {
                document.getElementById('alert-text').innerHTML = result['message'];
                document.getElementById('alert').className = 'box';
            }
        } else {
            error();
            console.log(
                    'Error: code ' +
                    result['response']['code'] +
                    ' - ' +
                    result['response']['description']
            );
        }
    }

    // Display error messages in every container
    function error() {
        // TODO: on error, hide containers and show separate div
        containers[0].innerText = 'Error';
        containers[1].innerText = 'Error';
        containers[2].innerText = 'Error';
    }

    // Loads the curator name into the specified container
    function load(user, element) {
        // Check if curator has been suggested

        if (user !== '') {
            // Curator has been suggested for this period

            var date = document.createElement('span');

            date.className = 'date';
            date.innerText = 'Start - End';

            element.parentElement.insertBefore(date, element.parentElement.childNodes[0]);

            if (user.endsWith('?')) {
                //FPC not confirmed

                element.innerHTML =
                        '@' +
                        user.substring(0, user.length - 1) +
                        ' (TBC)';
                element.className = 'gray';
            } else {
                //FPC was confirmed

                element.innerHTML = '@' + user + '';
                element.parentElement.href = 'https://scratch.mit.edu/users/' + user + '/';
                element.className = '';
            }
        }
    }

    // Makes a date human readable
    // Uses browser language to match users prefrences
    function formatDate(d) {
        return d.toLocaleString(navigator.language, {
            day: "numeric",
            month: "short"
        });
    }

    // Add close button click event
    alertClose.onclick = function() {
        document.getElementById('alert').className = 'hidden';
    };
};<|endoftext|>


<commit_before>mxn.register('googlev3', {

Mapstraction: {

	init: function(element, api){
	    var me = this;
            if ( google && google.maps ){
                var map = new google.maps.Map(element, {mapTypeId:google.maps.MapTypeId.ROADMAP});

                // deal with click

                // deal with zoom change
                google.maps.event.addListener(map, 'zoom_changed', function(){
                    me.changeZoom.fire();
		});
                // deal with map movement
		google.maps.event.addListener(map, 'dragend', function(){
                    me.moveendHandler(me);
                    me.endPan.fire();
		});
                this.maps[api] = map;
                this.loaded[api] = true;
                me.load.fire();
	    }
            else {
                alert(api + ' map script not imported');
            }
	},

	applyOptions: function(){
		var map = this.maps[this.api];
		// TODO: Add provider code
	},

	resizeTo: function(width, height){
            this.currentElement.style.width = width;
            this.currentElement.style.height = height;
            this.maps[this.api].checkResize();
  	},

	addControls: function( args ) {
	    var map = this.maps[this.api];
            // remove old controls

            // Google has a combined zoom and pan control.
            if (args.zoom || args.pan) {
                if (args.zoom == 'large'){
                    this.addLargeControls();
                } else {
                    this.addSmallControls();
                }
            }
	},

	addSmallControls: function() {
            var map = this.maps[this.api];
            var myOptions = {
                navigationControl:true,
		navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL}
            };
            map.setOptions(myOptions);
            this.addControlsArgs.pan = false;
            this.addControlsArgs.scale = false;
            this.addControlsArgs.zoom = 'small';
	},

	addLargeControls: function() {
	    var map = this.maps[this.api];
            var myOptions = {
                navigationControl:true,
		navigationControlOptions: {style:google.maps.NavigationControlStyle.DEFAULT}
            };
            map.setOptions(myOptions);
            this.addControlsArgs.pan = true;
            this.addControlsArgs.zoom = 'large';
	},

	addMapTypeControls: function() {
	    var map = this.maps[this.api];
            var myOptions = {
                mapTypeControl: true,
                mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DEFAULT}
            };
            map.setOptions(myOptions);
	    this.addControlsArgs.map_type = true;
	},

	dragging: function(on) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	setCenterAndZoom: function(point, zoom) {
		var map = this.maps[this.api];
		var pt = point.toProprietary(this.api);
		map.setCenter(pt);
                map.setZoom(zoom);
	},

	addMarker: function(marker, old) {
		var map = this.maps[this.api];
		var pin = marker.toProprietary(this.api);

		// TODO: Add provider code

		return pin;
	},

	removeMarker: function(marker) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	removeAllMarkers: function() {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	declutterMarkers: function(opts) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	addPolyline: function(polyline, old) {
		var map = this.maps[this.api];
		var pl = polyline.toProprietary(this.api);

		// TODO: Add provider code

		return pl;
	},

	removePolyline: function(polyline) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	getCenter: function() {
		var map = this.maps[this.api];
                var pt = map.getCenter();
                return new mxn.LatLonPoint(pt.lat(),pt.lng());
	},

	setCenter: function(point, options) {
		var map = this.maps[this.api];
		var pt = point.toProprietary(this.api);
		if(options && options.pan) {
                    map.panTo(pt);
		}
		else {
                    map.setCenter(pt);
		}
	},

	setZoom: function(zoom) {
		var map = this.maps[this.api];

		// TODO: Add provider code

	},

	getZoom: function() {
	    var map = this.maps[this.api];
            return map.getZoom();
	},

	getZoomLevelForBoundingBox: function( bbox ) {
		var map = this.maps[this.api];
                throw 'Not implemented';
	},

	setMapType: function(type) {
		var map = this.maps[this.api];
		switch(type) {
			case mxn.Mapstraction.ROAD:
                            map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
			    break;
			case mxn.Mapstraction.SATELLITE:
                            map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
			    break;
			case mxn.Mapstraction.HYBRID:
                            map.setMapTypeId(google.maps.MapTypeId.HYBRID);
			    break;
			default:
                            map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
		}
	},

	getMapType: function() {
            var map = this.maps[this.api];
            var type = map.getMapTypeId();
                switch(type) {
                        case google.maps.MapTypeId.ROADMAP:
                                return mxn.Mapstraction.ROAD;
                        case google.maps.MapTypeId.SATELLITE:
                                return mxn.Mapstraction.SATELLITE;
                        case google.maps.MapTypeId.HYBRID:
                                return mxn.Mapstraction.HYBRID;
                        //case google.maps.MapTypeId.TERRAIN:
                        //        return something;
                        default:
                                return null;
                }
	},

	getBounds: function () {
	    var map = this.maps[this.api];
	    var gLatLngBounds = map.getBounds();
            var sw = gLatLngBounds.getSouthWest();
            var ne = gLatLngBounds.getNorthEast();
            return new mxn.BoundingBox(sw.lat(), sw.lng(), ne.lat(), ne.lng());
	},

	setBounds: function(bounds){
		var map = this.maps[this.api];
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
                var gLatLngBounds = new google.maps.LatLngBounds({sw:sw, ne:ne});
		map.fitBounds(gLatLngBounds);
	},

	addImageOverlay: function(id, src, opacity, west, south, east, north, oContext) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	setImagePosition: function(id, oContext) {
		var map = this.maps[this.api];
		var topLeftPoint; var bottomRightPoint;

		// TODO: Add provider code

		//oContext.pixels.top = ...;
		//oContext.pixels.left = ...;
		//oContext.pixels.bottom = ...;
		//oContext.pixels.right = ...;
	},

	addOverlay: function(url, autoCenterAndZoom) {
		var map = this.maps[this.api];

		// TODO: Add provider code

	},

	addTileLayer: function(tile_url, opacity, copyright_text, min_zoom, max_zoom) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	toggleTileLayer: function(tile_url) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	getPixelRatio: function() {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	mousePosition: function(element) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	}
},

LatLonPoint: {

	toProprietary: function() {
            return new google.maps.LatLng(this.lat, this.lon);
	},

	fromProprietary: function(googlePoint) {
		this.lat = googlePoint.lat();
		this.lon = googlePoint.lng();
	}

},

Marker: {

	toProprietary: function() {
		// TODO: Add provider code
	},

	openBubble: function() {
		// TODO: Add provider code
	},

	hide: function() {
	    this.proprietary_marker.setOptions({visible:false});
	},

	show: function() {
	    this.proprietary_marker.setOptions({visible:true});
	},

	update: function() {
		// TODO: Add provider code
	}

},

Polyline: {

	toProprietary: function() {
            throw 'Not implemented';
	},

	show: function() {
            throw 'Not implemented';
	},

	hide: function() {
            throw 'Not implemented';
	}

}

});<commit_msg>removed deprecated method draggable, all controls off when first creating the map, bit of work on adding controls, though still doesnt seem to be working correctly<commit_after>mxn.register('googlev3', {

Mapstraction: {

	init: function(element, api){
	    var me = this;
            if ( google && google.maps ){
                // be default no controls and road map
                var myOptions = {
		    disableDefaultUI: true,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(element, myOptions);

                // deal with click

                // deal with zoom change
                google.maps.event.addListener(map, 'zoom_changed', function(){
                    me.changeZoom.fire();
		});
                // deal with map movement
		google.maps.event.addListener(map, 'dragend', function(){
                    me.moveendHandler(me);
                    me.endPan.fire();
		});
                this.maps[api] = map;
                this.loaded[api] = true;
                me.load.fire();
	    }
            else {
                alert(api + ' map script not imported');
            }
	},

	applyOptions: function(){
	    var map = this.maps[this.api];
	    var myOptions = [];
            if (this.options.enableDragging) {
		myOptions.draggable = true;
            }
            if (this.options.enableScrollWheelZoom){
		myOptions.scrollwheel = true;
            }
	    map.setOptions(myOptions);
	},

	resizeTo: function(width, height){
            this.currentElement.style.width = width;
            this.currentElement.style.height = height;
            this.maps[this.api].checkResize();
  	},

	addControls: function( args ) {
	    var map = this.maps[this.api];
            // remove old controls

            // Google has a combined zoom and pan control.
            if (args.zoom || args.pan) {
                if (args.zoom == 'large'){
                    this.addLargeControls();
                } else {
                    this.addSmallControls();
                }
            }
            if (args.scale){
                var myOptions = {
                    scaleControl:true,
		    scaleControlOptions: {style:google.maps.ScaleControlStyle.DEFAULT}
                };
                map.setOptions(myOptions);
                this.addControlsArgs.scale = true;
            }
	},

	addSmallControls: function() {
            var map = this.maps[this.api];
            var myOptions = {
                scrollwheel: false,
                navigationControl:true,
		navigationControlOptions: {style:google.maps.NavigationControlStyle.SMALL}
            };
            map.setOptions(myOptions);
            this.addControlsArgs.pan = false;
            this.addControlsArgs.scale = false;
            this.addControlsArgs.zoom = 'small';
	},

	addLargeControls: function() {
	    var map = this.maps[this.api];
            var myOptions = {
                navigationControl:true,
		navigationControlOptions: {style:google.maps.NavigationControlStyle.DEFAULT}
            };
            map.setOptions(myOptions);
            this.addControlsArgs.pan = true;
            this.addControlsArgs.zoom = 'large';
	},

	addMapTypeControls: function() {
	    var map = this.maps[this.api];
            var myOptions = {
                mapTypeControl: true,
                mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DEFAULT}
            };
            map.setOptions(myOptions);
	    this.addControlsArgs.map_type = true;
	},

	setCenterAndZoom: function(point, zoom) {
		var map = this.maps[this.api];
		var pt = point.toProprietary(this.api);
		map.setCenter(pt);
                map.setZoom(zoom);
	},

	addMarker: function(marker, old) {
		var map = this.maps[this.api];
		var pin = marker.toProprietary(this.api);

		// TODO: Add provider code

		return pin;
	},

	removeMarker: function(marker) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	removeAllMarkers: function() {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	declutterMarkers: function(opts) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	addPolyline: function(polyline, old) {
		var map = this.maps[this.api];
		var pl = polyline.toProprietary(this.api);

		// TODO: Add provider code

		return pl;
	},

	removePolyline: function(polyline) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	getCenter: function() {
		var map = this.maps[this.api];
                var pt = map.getCenter();
                return new mxn.LatLonPoint(pt.lat(),pt.lng());
	},

	setCenter: function(point, options) {
		var map = this.maps[this.api];
		var pt = point.toProprietary(this.api);
		if(options && options.pan) {
                    map.panTo(pt);
		}
		else {
                    map.setCenter(pt);
		}
	},

	setZoom: function(zoom) {
		var map = this.maps[this.api];

		// TODO: Add provider code

	},

	getZoom: function() {
	    var map = this.maps[this.api];
            return map.getZoom();
	},

	getZoomLevelForBoundingBox: function( bbox ) {
		var map = this.maps[this.api];
                throw 'Not implemented';
	},

	setMapType: function(type) {
		var map = this.maps[this.api];
		switch(type) {
			case mxn.Mapstraction.ROAD:
                            map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
			    break;
			case mxn.Mapstraction.SATELLITE:
                            map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
			    break;
			case mxn.Mapstraction.HYBRID:
                            map.setMapTypeId(google.maps.MapTypeId.HYBRID);
			    break;
			default:
                            map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
		}
	},

	getMapType: function() {
            var map = this.maps[this.api];
            var type = map.getMapTypeId();
                switch(type) {
                        case google.maps.MapTypeId.ROADMAP:
                                return mxn.Mapstraction.ROAD;
                        case google.maps.MapTypeId.SATELLITE:
                                return mxn.Mapstraction.SATELLITE;
                        case google.maps.MapTypeId.HYBRID:
                                return mxn.Mapstraction.HYBRID;
                        //case google.maps.MapTypeId.TERRAIN:
                        //        return something;
                        default:
                                return null;
                }
	},

	getBounds: function () {
	    var map = this.maps[this.api];
	    var gLatLngBounds = map.getBounds();
            var sw = gLatLngBounds.getSouthWest();
            var ne = gLatLngBounds.getNorthEast();
            return new mxn.BoundingBox(sw.lat(), sw.lng(), ne.lat(), ne.lng());
	},

	setBounds: function(bounds){
		var map = this.maps[this.api];
		var sw = bounds.getSouthWest();
		var ne = bounds.getNorthEast();
                var gLatLngBounds = new google.maps.LatLngBounds({sw:sw, ne:ne});
		map.fitBounds(gLatLngBounds);
	},

	addImageOverlay: function(id, src, opacity, west, south, east, north, oContext) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	setImagePosition: function(id, oContext) {
		var map = this.maps[this.api];
		var topLeftPoint; var bottomRightPoint;

		// TODO: Add provider code

		//oContext.pixels.top = ...;
		//oContext.pixels.left = ...;
		//oContext.pixels.bottom = ...;
		//oContext.pixels.right = ...;
	},

	addOverlay: function(url, autoCenterAndZoom) {
		var map = this.maps[this.api];

		// TODO: Add provider code

	},

	addTileLayer: function(tile_url, opacity, copyright_text, min_zoom, max_zoom) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	toggleTileLayer: function(tile_url) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	getPixelRatio: function() {
		var map = this.maps[this.api];

		// TODO: Add provider code
	},

	mousePosition: function(element) {
		var map = this.maps[this.api];

		// TODO: Add provider code
	}
},

LatLonPoint: {

	toProprietary: function() {
            return new google.maps.LatLng(this.lat, this.lon);
	},

	fromProprietary: function(googlePoint) {
		this.lat = googlePoint.lat();
		this.lon = googlePoint.lng();
	}

},

Marker: {

	toProprietary: function() {
		// TODO: Add provider code
	},

	openBubble: function() {
		// TODO: Add provider code
	},

	hide: function() {
	    this.proprietary_marker.setOptions({visible:false});
	},

	show: function() {
	    this.proprietary_marker.setOptions({visible:true});
	},

	update: function() {
		// TODO: Add provider code
	}

},

Polyline: {

	toProprietary: function() {
            throw 'Not implemented';
	},

	show: function() {
            throw 'Not implemented';
	},

	hide: function() {
            throw 'Not implemented';
	}

}

});<|endoftext|>


<commit_before>var alexa = require('alexa-app');
var request = require('request');
var express = require('express');

var express_app = express();

var app = new alexa.app('connect');
app.express({ expressApp: express_app });

app.intent('PlayIntent', {
    "utterances": [
        "play",
        "resume",
        "continue"
    ]
},
    function (req, res) {
        request.put("https://api.spotify.com/v1/me/player/play").auth(null, null, true, req.sessionDetails.accessToken);
        res.say('Playing');
    }
);

app.intent('PauseIntent', {
    "utterances": [
        "pause"
    ]
},
    function (req, res) {
        request.put("https://api.spotify.com/v1/me/player/pause").auth(null, null, true, req.sessionDetails.accessToken);
        res.say('Paused');
    }
);

app.intent('GetDevicesIntent', {
    "utterances": [
        "devices",
        "list"
    ]
},
    function (req, res) {
        var devices = [];
        request.get({
            url: "https://api.spotify.com/v1/me/player/devices",
            auth: {
                "bearer": req.sessionDetails.accessToken
            },
            json: true
        },
            function (error, response, body) {
                if (error != null) console.log('error:', error);
                devices = body.devices;
            });
        res.say("I found these devices");
        for (var i = 0; i < devices.length; i++) {
            res.say(devices[i].name);
        }
    }
);

var port = process.env.PORT || 8888;
console.log("Listening on port " + port);
express_app.listen(port);

module.exports = app;
<commit_msg>Fix express static for terms<commit_after>var alexa = require('alexa-app');
var request = require('request');
var express = require('express');

var express_app = express();

var app = new alexa.app('connect');
app.express({ expressApp: express_app });

app.intent('PlayIntent', {
    "utterances": [
        "play",
        "resume",
        "continue"
    ]
},
    function (req, res) {
        request.put("https://api.spotify.com/v1/me/player/play").auth(null, null, true, req.sessionDetails.accessToken);
        res.say('Playing');
    }
);

app.intent('PauseIntent', {
    "utterances": [
        "pause"
    ]
},
    function (req, res) {
        request.put("https://api.spotify.com/v1/me/player/pause").auth(null, null, true, req.sessionDetails.accessToken);
        res.say('Paused');
    }
);

app.intent('GetDevicesIntent', {
    "utterances": [
        "devices",
        "list"
    ]
},
    function (req, res) {
        var devices = [];
        request.get({
            url: "https://api.spotify.com/v1/me/player/devices",
            auth: {
                "bearer": req.sessionDetails.accessToken
            },
            json: true
        },
            function (error, response, body) {
                if (error != null) console.log('error:', error);
                devices = body.devices;
            });
        res.say("I found these devices");
        for (var i = 0; i < devices.length; i++) {
            res.say(devices[i].name);
        }
    }
);

express_app.use(express.static(__dirname));

var port = process.env.PORT || 8888;
console.log("Listening on port " + port);
express_app.listen(port);

module.exports = app;
<|endoftext|>


<commit_before>{% comment %}
 coding: utf-8

 maposmatic, the web front-end of the MapOSMatic city map generation system
 Copyright (C) 2012  David Decotigny
 Copyright (C) 2012  Frédéric Lehobey
 Copyright (C) 2012  Pierre Mauduit
 Copyright (C) 2012  David Mentré
 Copyright (C) 2012  Maxime Petazzoni
 Copyright (C) 2012  Thomas Petazzoni
 Copyright (C) 2012  Gaël Utard

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% load i18n %}
{% load extratags %}

/**
 * Map creation wizard.
 */

var BBOX_MAXIMUM_LENGTH_IN_KM = {{ BBOX_MAXIMUM_LENGTH_IN_METERS }} / 1000;

var map = null;
var country = null;
var languages = $('#id_map_language').html();

jQuery.fn.reverse = [].reverse;

$('#wizard').carousel({'interval': false});

/**
 * When the carousel initiates its slide, trigger the 'prepare' event on the
 * slide that is about to be activated.
 */
$('#wizard').bind('slide', function(e) {
  $(e.relatedTarget).trigger('prepare');
});

/**
 * The 'slid' event is triggered when the carousel finishes a slide in either
 * direction. This function is called by the 'slid' event handler to make sure
 * the prev/next links are in the * correct state based on the position in the
 * carousel.
 */
$('#wizard').bind('slid', setPrevNextLinks);

$('#wizard-step-location label').click(function(e) {
  $('#id_administrative_city').val('');
  $('#id_administrative_osmid').val('');
  country = null;
  $(this).tab('show');
  setPrevNextLinks();

  // If we're switching to the administrative boundary / city search tab, reset
  // the focus inside the input field.
  if ($(this).attr('for') == 'id_mode_0') {
    $('#id_administrative_city').focus();
  }

  // If it's the first time we switch to the bounding box tab, initialize the
  // minimap.
  if ($(this).attr('for') == 'id_mode_1' && !map) {
    map = wizardmap($('#step-location-map'));
  }
});

/**
 * Bind the keyup event on the map title field to control the disabled state of
 * the final submit button. The button can only be pressed if a map title is
 * present. The rest of the validation is assumed to have been taken care of at
 * each step boundary.
 */
$('#id_maptitle').bind('keyup', function(e) {
  if ($(this).val()) {
    $('#id_go_next_btn').removeAttr('disabled');
  } else {
    $('#id_go_next_btn').attr('disabled', 'disabled');
  }
});

function setPrevNextLinks() {
  var current = $('#wizard .carousel-inner div.item.active');
  var first   = $('#wizard .carousel-inner div.item:first-child');
  var last    = $('#wizard .carousel-inner div.item:last-child');

  $('#prevlink').hide();
  $('#nextlink').hide();
  if (current.attr('id') == first.attr('id')) {
    if ($('#id_administrative_osmid').val()) {
      $('#nextlink').show();
    }
  } else if (current.attr('id') == last.attr('id')) {
    $('#prevlink').show();
  } else {
    $('#prevlink').show();
    $('#nextlink').show();
  }
}

$('#wizard-step-paper-size').bind('prepare', function(e) {
  $('#paper-selection').hide();
  $('#paper-size-loading-error').hide();
  $('#paper-size-loading').show();
  $('#nextlink').hide();

  var args = null;
  if ($('#id_administrative_osmid').val()) {
    args = {
      osmid: $('#id_administrative_osmid').val(),
    };
  } else {
    args = {
      lat_upper_left: $('#id_lat_upper_left').val(),
      lon_upper_left: $('#id_lon_upper_left').val(),
      lat_bottom_right: $('#id_lat_bottom_right').val(),
      lon_bottom_right: $('#id_lon_bottom_right').val()
    };
  }

  args['layout'] = $('input[name=layout]:checked').val();
  args['stylesheet'] = $('input[name=stylesheet]:checked').val();
  args['overlay'] = $('input[name=overlay]:checked').val();

  $.ajax('/apis/papersize/', { type: 'post', data: args })
    .complete(function() { $('#paper-size-loading').hide(); })
    .error(function() { $('#paper-size-loading-error').show(); })
    .success(function(data) {

      function get_paper_def(paper) {
        for (i in data) {
          if (paper == data[i][0]) {
            return data[i];
          }
        }

        return null;
      }

      function handle_paper_size_click(w, h, p_ok, l_ok, l_preferred) {
        var l = $('#paper-selection input[value=landscape]');
        var p = $('#paper-selection input[value=portrait]');

        if (l_ok) {
          l.removeAttr('disabled');
          if (!p_ok) { l.attr('checked', 'checked'); }
        } else {
          l.attr('disabled', 'disabled');
        }

        if (p_ok) {
          p.removeAttr('disabled');
          if (!l_ok) { p.attr('checked', 'checked'); }
        } else {
          p.attr('disabled', 'disabled');
        }

        if (l_ok && p_ok) {
          if (l_preferred) {
            l.attr('checked', 'checked');
          } else {
            p.attr('checked', 'checked');
          }
        }

        $('#id_paper_width_mm').val(w);
        $('#id_paper_height_mm').val(h);
      }

      var default_paper = null;

      $.each($('#paper-size ul li'), function(i, item) {
        $(item).hide();

        var paper = $('label input[value]', item).val();
        var def = get_paper_def(paper);
        if (def) {
          $('label', item).bind('click', function() {
            handle_paper_size_click(def[1], def[2], def[3], def[4], def[6]);
          });

          if (def[5]) {
            default_paper = $(item);
          }

          $(item).show();

          // TODO: fix for i18n
          if (paper == 'Best fit') {
            w = def[1] / 10;
            h = def[2] / 10;
            $('label em.papersize', item).html('(' + w.toFixed(1) + ' × ' + h.toFixed(1) + ' cm²)');
          }
        }
      });

      $('label input', default_paper).click();
      $('#paper-selection').show();
      $('#nextlink').show();
    });
});

$('#wizard-step-lang-title').bind('prepare', function(e) {
  // Prepare the language list
  var list = $('#id_map_language');
  list.html(languages);

  /*
   * The goal is to build a list of languages in which we have first
   * the languages matching the current country code, then an empty
   * disabled entry used as a separator and finally all other
   * languages. To do so, we use prependTo(), which adds elements at
   * the beginning of the list. So we start by prepending the
   * separator, then the "no localization" special language, and
   * finally the languages matching the current country code.
   */
  $('<option disabled="disabled"></option>').prependTo(list);
  $('option[value=C]', list).prependTo(list);
  list.children('option').reverse().each(function() {
    if ($(this).val().match('.._' + country.toUpperCase() + '\..*') != null) {
      $(this).prependTo(list);
    }
  });
  $('option:first', list).attr('selected', 'selected');

  // Seed the summary fields
  if ($('#id_administrative_osmid').val()) {
    $('#summary-location').text($('#id_administrative_city').val());
  } else {
    $('#summary-location').html(
      '(' + $('#id_lat_upper_left').val() + ', ' +
            $('#id_lon_upper_left').val() + ')' +
      ' → ' +
      '(' + $('#id_lat_bottom_right').val() + ', ' +
            $('#id_lon_bottom_right').val() + ')');
  }

  $('#summary-layout').text($('input[name=layout]:checked').parent().text().trim());
  $('#summary-stylesheet').text($('input[name=stylesheet]:checked').parent().text().trim());
  $('#summary-overlay').text($('input[name=overlay]:checked').parent().text().trim());
  $('#summary-paper-size').text(
      ($('input[value=landscape]').is(':checked')
          ? '{% trans "Landscape" %}'
          : '{% trans "Portrait" %}'
      ) + ', ' + $('input[name=papersize]:checked').parent().text().trim());
});

function wizardmap(elt) {
  var map = create_map($('#step-location-map'));
  var lock = false;
  var bbox = null;
  var bbox_style = {
    fill: true,
    fillColor: "#FFFFFF",
    fillOpacity: 0.5,
    stroke: true,
    strokeOpacity: 0.8,
    strokeColor: "#FF0000",
    strokeWidth: 2
  };
  var countryquery = null;
  var locationFilter = new L.LocationFilter({buttonPosition: 'topright'});
  locationFilter.on("change", function (e) {
      bbox = e.bounds;
      map.fitBounds(e.bounds);
      update_fields();
  });
  locationFilter.on("enabled", function (e) {
      bbox = e.bounds;
      map.fitBounds(e.bounds);
      update_fields();
  });
  locationFilter.on("disabled", function (e) {
      bbox = null;
      update_fields();
  });
  locationFilter.addTo(map);

  // locate client position
  L.control.locate().addTo(map);

  // search button
  map.addControl( new L.Control.Search({
      url: '//nominatim.openstreetmap.org/search?format=json&q={s}',
      jsonpParam: 'json_callback',
      propertyName: 'display_name',
      propertyLoc: ['lat','lon'],
      circleLocation: true,
      markerLocation: false,
      autoType: false,
      autoCollapse: true,
      minLength: 2,
      zoom: 17
  }) );

  /**
   * Update the 4 text fields with the area coordinates.
   *
   * If a feature has been drawned (bbox != null), the bounding box of the
   * feature is used, otherwise the map extent is used.
   */
  var update_fields = function() {
    if (lock) {
      return;
    }

    var bounds = (bbox != null) ? bbox : map.getBounds();

    $('#id_lat_upper_left').val(bounds.getNorth().toFixed(4));

    $('#id_lon_upper_left').val(bounds.getWest().toFixed(4));
    $('#id_lat_bottom_right').val(bounds.getSouth().toFixed(4));
    $('#id_lon_bottom_right').val(bounds.getEast().toFixed(4));

    var center = bounds.getCenter();

    var upper_left   = bounds.getNorthWest();
    var upper_right  = bounds.getNorthEast();
    var bottom_left  = bounds.getSouthWest();
    var bottom_right = bounds.getSouthEast();

    var width  = upper_left.distanceTo(upper_right);
    var height = upper_right.distanceTo(bottom_right);

    if (width < {{ BBOX_MAXIMUM_LENGTH_IN_METERS }} &&
        height < {{ BBOX_MAXIMUM_LENGTH_IN_METERS }}) {
      $('#area-size-alert').hide();
      $('#nextlink').show();

      // Attempt to get the country by reverse geo lookup
      if (countryquery != null) { countryquery.abort(); }
      countryquery = $.getJSON(
        '/apis/reversegeo/' + center.lat + '/' + center.lng + '/',
        function(data) {
          $.each(data, function(i, item) {
            if (typeof item.country_code != 'undefined') {
              country = item.country_code;
            }
          });
        });
    } else {
      $('#area-size-alert').show();
      $('#nextlink').hide();
    }
  };

  /**
   * Set the map bounds and extent to the current values given by the 4 text
   * fields.
   */
  var set_map_bounds_from_fields = function() {
    return;
    lock = true;
    set_map_bounds(map, [
      [$('#id_lat_upper_left').val(), $('#id_lon_upper_left').val()],
      [$('#id_lat_bottom_right').val(), $('#id_lon_bottom_right').val()]
    ]);
    lock = false;
  };

  // Bind events.
  map.on('moveend', update_fields);
  map.on('zoomend', update_fields);

  $('#step-location-bbox input').bind('keydown', function(e) {
    if (bbox) {
      return;
    }

    if (e.keyCode == 38 || e.keyCode == 40) {
      var v = parseFloat($(e.target).val()) + (0.01 * (e.keyCode == 38 ? 1 : -1));
      $(e.target).val(v.toFixed(4));
    }

    set_map_bounds_from_fields();
    update_fields();
  });

  set_map_bounds_from_fields();
  update_fields();
  return map;
}
<commit_msg>make locatonFilter global<commit_after>{% comment %}
 coding: utf-8

 maposmatic, the web front-end of the MapOSMatic city map generation system
 Copyright (C) 2012  David Decotigny
 Copyright (C) 2012  Frédéric Lehobey
 Copyright (C) 2012  Pierre Mauduit
 Copyright (C) 2012  David Mentré
 Copyright (C) 2012  Maxime Petazzoni
 Copyright (C) 2012  Thomas Petazzoni
 Copyright (C) 2012  Gaël Utard

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as
 published by the Free Software Foundation, either version 3 of the
 License, or any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
{% endcomment %}
{% load i18n %}
{% load extratags %}

/**
 * Map creation wizard.
 */

var BBOX_MAXIMUM_LENGTH_IN_KM = {{ BBOX_MAXIMUM_LENGTH_IN_METERS }} / 1000;

var map = null;
var country = null;
var languages = $('#id_map_language').html();

jQuery.fn.reverse = [].reverse;

$('#wizard').carousel({'interval': false});

/**
 * When the carousel initiates its slide, trigger the 'prepare' event on the
 * slide that is about to be activated.
 */
$('#wizard').bind('slide', function(e) {
  $(e.relatedTarget).trigger('prepare');
});

/**
 * The 'slid' event is triggered when the carousel finishes a slide in either
 * direction. This function is called by the 'slid' event handler to make sure
 * the prev/next links are in the * correct state based on the position in the
 * carousel.
 */
$('#wizard').bind('slid', setPrevNextLinks);

$('#wizard-step-location label').click(function(e) {
  $('#id_administrative_city').val('');
  $('#id_administrative_osmid').val('');
  country = null;
  $(this).tab('show');
  setPrevNextLinks();

  // If we're switching to the administrative boundary / city search tab, reset
  // the focus inside the input field.
  if ($(this).attr('for') == 'id_mode_0') {
    $('#id_administrative_city').focus();
  }

  // If it's the first time we switch to the bounding box tab, initialize the
  // minimap.
  if ($(this).attr('for') == 'id_mode_1' && !map) {
    map = wizardmap($('#step-location-map'));
  }
});

/**
 * Bind the keyup event on the map title field to control the disabled state of
 * the final submit button. The button can only be pressed if a map title is
 * present. The rest of the validation is assumed to have been taken care of at
 * each step boundary.
 */
$('#id_maptitle').bind('keyup', function(e) {
  if ($(this).val()) {
    $('#id_go_next_btn').removeAttr('disabled');
  } else {
    $('#id_go_next_btn').attr('disabled', 'disabled');
  }
});

function setPrevNextLinks() {
  var current = $('#wizard .carousel-inner div.item.active');
  var first   = $('#wizard .carousel-inner div.item:first-child');
  var last    = $('#wizard .carousel-inner div.item:last-child');

  $('#prevlink').hide();
  $('#nextlink').hide();
  if (current.attr('id') == first.attr('id')) {
    if ($('#id_administrative_osmid').val()) {
      $('#nextlink').show();
    }
  } else if (current.attr('id') == last.attr('id')) {
    $('#prevlink').show();
  } else {
    $('#prevlink').show();
    $('#nextlink').show();
  }
}

$('#wizard-step-paper-size').bind('prepare', function(e) {
  $('#paper-selection').hide();
  $('#paper-size-loading-error').hide();
  $('#paper-size-loading').show();
  $('#nextlink').hide();

  var args = null;
  if ($('#id_administrative_osmid').val()) {
    args = {
      osmid: $('#id_administrative_osmid').val(),
    };
  } else {
    args = {
      lat_upper_left: $('#id_lat_upper_left').val(),
      lon_upper_left: $('#id_lon_upper_left').val(),
      lat_bottom_right: $('#id_lat_bottom_right').val(),
      lon_bottom_right: $('#id_lon_bottom_right').val()
    };
  }

  args['layout'] = $('input[name=layout]:checked').val();
  args['stylesheet'] = $('input[name=stylesheet]:checked').val();
  args['overlay'] = $('input[name=overlay]:checked').val();

  $.ajax('/apis/papersize/', { type: 'post', data: args })
    .complete(function() { $('#paper-size-loading').hide(); })
    .error(function() { $('#paper-size-loading-error').show(); })
    .success(function(data) {

      function get_paper_def(paper) {
        for (i in data) {
          if (paper == data[i][0]) {
            return data[i];
          }
        }

        return null;
      }

      function handle_paper_size_click(w, h, p_ok, l_ok, l_preferred) {
        var l = $('#paper-selection input[value=landscape]');
        var p = $('#paper-selection input[value=portrait]');

        if (l_ok) {
          l.removeAttr('disabled');
          if (!p_ok) { l.attr('checked', 'checked'); }
        } else {
          l.attr('disabled', 'disabled');
        }

        if (p_ok) {
          p.removeAttr('disabled');
          if (!l_ok) { p.attr('checked', 'checked'); }
        } else {
          p.attr('disabled', 'disabled');
        }

        if (l_ok && p_ok) {
          if (l_preferred) {
            l.attr('checked', 'checked');
          } else {
            p.attr('checked', 'checked');
          }
        }

        $('#id_paper_width_mm').val(w);
        $('#id_paper_height_mm').val(h);
      }

      var default_paper = null;

      $.each($('#paper-size ul li'), function(i, item) {
        $(item).hide();

        var paper = $('label input[value]', item).val();
        var def = get_paper_def(paper);
        if (def) {
          $('label', item).bind('click', function() {
            handle_paper_size_click(def[1], def[2], def[3], def[4], def[6]);
          });

          if (def[5]) {
            default_paper = $(item);
          }

          $(item).show();

          // TODO: fix for i18n
          if (paper == 'Best fit') {
            w = def[1] / 10;
            h = def[2] / 10;
            $('label em.papersize', item).html('(' + w.toFixed(1) + ' × ' + h.toFixed(1) + ' cm²)');
          }
        }
      });

      $('label input', default_paper).click();
      $('#paper-selection').show();
      $('#nextlink').show();
    });
});

$('#wizard-step-lang-title').bind('prepare', function(e) {
  // Prepare the language list
  var list = $('#id_map_language');
  list.html(languages);

  /*
   * The goal is to build a list of languages in which we have first
   * the languages matching the current country code, then an empty
   * disabled entry used as a separator and finally all other
   * languages. To do so, we use prependTo(), which adds elements at
   * the beginning of the list. So we start by prepending the
   * separator, then the "no localization" special language, and
   * finally the languages matching the current country code.
   */
  $('<option disabled="disabled"></option>').prependTo(list);
  $('option[value=C]', list).prependTo(list);
  list.children('option').reverse().each(function() {
    if ($(this).val().match('.._' + country.toUpperCase() + '\..*') != null) {
      $(this).prependTo(list);
    }
  });
  $('option:first', list).attr('selected', 'selected');

  // Seed the summary fields
  if ($('#id_administrative_osmid').val()) {
    $('#summary-location').text($('#id_administrative_city').val());
  } else {
    $('#summary-location').html(
      '(' + $('#id_lat_upper_left').val() + ', ' +
            $('#id_lon_upper_left').val() + ')' +
      ' → ' +
      '(' + $('#id_lat_bottom_right').val() + ', ' +
            $('#id_lon_bottom_right').val() + ')');
  }

  $('#summary-layout').text($('input[name=layout]:checked').parent().text().trim());
  $('#summary-stylesheet').text($('input[name=stylesheet]:checked').parent().text().trim());
  $('#summary-overlay').text($('input[name=overlay]:checked').parent().text().trim());
  $('#summary-paper-size').text(
      ($('input[value=landscape]').is(':checked')
          ? '{% trans "Landscape" %}'
          : '{% trans "Portrait" %}'
      ) + ', ' + $('input[name=papersize]:checked').parent().text().trim());
});

var locationFilter = null;

function wizardmap(elt) {
  var map = create_map($('#step-location-map'));
  var lock = false;
  var bbox = null;
  var bbox_style = {
    fill: true,
    fillColor: "#FFFFFF",
    fillOpacity: 0.5,
    stroke: true,
    strokeOpacity: 0.8,
    strokeColor: "#FF0000",
    strokeWidth: 2
  };
  var countryquery = null;
  locationFilter = new L.LocationFilter({buttonPosition: 'topright'});
  locationFilter.on("change", function (e) {
      bbox = e.bounds;
      map.fitBounds(e.bounds);
      update_fields();
  });
  locationFilter.on("enabled", function (e) {
      bbox = e.bounds;
      map.fitBounds(e.bounds);
      update_fields();
  });
  locationFilter.on("disabled", function (e) {
      bbox = null;
      update_fields();
  });
  locationFilter.addTo(map);

  // locate client position
  L.control.locate().addTo(map);

  // search button
  map.addControl( new L.Control.Search({
      url: '//nominatim.openstreetmap.org/search?format=json&q={s}',
      jsonpParam: 'json_callback',
      propertyName: 'display_name',
      propertyLoc: ['lat','lon'],
      circleLocation: true,
      markerLocation: false,
      autoType: false,
      autoCollapse: true,
      minLength: 2,
      zoom: 17
  }) );

  /**
   * Update the 4 text fields with the area coordinates.
   *
   * If a feature has been drawned (bbox != null), the bounding box of the
   * feature is used, otherwise the map extent is used.
   */
  var update_fields = function() {
    if (lock) {
      return;
    }

    var bounds = (bbox != null) ? bbox : map.getBounds();

    $('#id_lat_upper_left').val(bounds.getNorth().toFixed(4));

    $('#id_lon_upper_left').val(bounds.getWest().toFixed(4));
    $('#id_lat_bottom_right').val(bounds.getSouth().toFixed(4));
    $('#id_lon_bottom_right').val(bounds.getEast().toFixed(4));

    var center = bounds.getCenter();

    var upper_left   = bounds.getNorthWest();
    var upper_right  = bounds.getNorthEast();
    var bottom_left  = bounds.getSouthWest();
    var bottom_right = bounds.getSouthEast();

    var width  = upper_left.distanceTo(upper_right);
    var height = upper_right.distanceTo(bottom_right);

    if (width < {{ BBOX_MAXIMUM_LENGTH_IN_METERS }} &&
        height < {{ BBOX_MAXIMUM_LENGTH_IN_METERS }}) {
      $('#area-size-alert').hide();
      $('#nextlink').show();

      // Attempt to get the country by reverse geo lookup
      if (countryquery != null) { countryquery.abort(); }
      countryquery = $.getJSON(
        '/apis/reversegeo/' + center.lat + '/' + center.lng + '/',
        function(data) {
          $.each(data, function(i, item) {
            if (typeof item.country_code != 'undefined') {
              country = item.country_code;
            }
          });
        });
    } else {
      $('#area-size-alert').show();
      $('#nextlink').hide();
    }
  };

  /**
   * Set the map bounds and extent to the current values given by the 4 text
   * fields.
   */
  var set_map_bounds_from_fields = function() {
    return;
    lock = true;
    set_map_bounds(map, [
      [$('#id_lat_upper_left').val(), $('#id_lon_upper_left').val()],
      [$('#id_lat_bottom_right').val(), $('#id_lon_bottom_right').val()]
    ]);
    lock = false;
  };

  // Bind events.
  map.on('moveend', update_fields);
  map.on('zoomend', update_fields);

  $('#step-location-bbox input').bind('keydown', function(e) {
    if (bbox) {
      return;
    }

    if (e.keyCode == 38 || e.keyCode == 40) {
      var v = parseFloat($(e.target).val()) + (0.01 * (e.keyCode == 38 ? 1 : -1));
      $(e.target).val(v.toFixed(4));
    }

    set_map_bounds_from_fields();
    update_fields();
  });

  set_map_bounds_from_fields();
  update_fields();
  return map;
}
<|endoftext|>


<commit_before>/**
 * @title Open - cordova.plugins.bridge.open
 * @overview Open documents with compatible apps.
 * @copyright © 2015 cordova-bridge
 * @license GPLv2
 * @author Carlos Antonio
*/

var exec = require('cordova/exec');

/**
 * open
 *
 * @param {String} args File URI
 * @param {Function} success Success callback
 * @param {Function} error Failure callback
 */
exports.open = function(uri, success, error) {
  if (!uri || arguments.length === 0) { return false; }

  function onSuccess(path) {
    fire('success');
    if (typeof success === 'function') { success(path); }
    return path;
  }

  function onError(code) {
    fire('error');
    code = code || 0;
    if (typeof error === 'function') { error(code); }
    return code;
  }

  uri = encodeURI(uri);

  if (uri.match('http')) {
    downloadAndOpen(uri);
  } else {
    exec(onSuccess.bind(this, uri), onError, 'Open', 'open', [uri]);
  }
};

/**
 * downloadAndOpen
 *
 * @param {String} url File URI
 */
function downloadAndOpen(url) {
  var ft = new FileTransfer();
  var ios = cordova.file.cacheDirectory;
  var ext = cordova.file.externalCacheDirectory;
  var dir = (ext) ?  ext : ios;
  var name = url.substring(url.lastIndexOf('/') + 1);
  var path = dir + name;

  ft.download(url, path,
      function done(entry) {
        var file = entry.toURL();
        exec(onSuccess.bind(this, file), onError, 'Open', 'open', [file]);
      },
      onError,
      false
  );
}

/**
 * fire
 *
 * @param {String} event Event name
 */
function fire(event) {
  var channel = require('cordova/channel');
  var cordova = require('cordova');

  channel.onCordovaReady.subscribe(function() {
    cordova.fireDocumentEvent('open.' + event);
  });
}
<commit_msg>Fix callback execution context<commit_after>/**
 * @title Open - cordova.plugins.bridge.open
 * @overview Open documents with compatible apps.
 * @copyright © 2015 cordova-bridge
 * @license GPLv2
 * @author Carlos Antonio
*/

var exec = require('cordova/exec');

/**
 * open
 *
 * @param {String} args File URI
 * @param {Function} success Success callback
 * @param {Function} error Failure callback
 */
exports.open = function(uri, success, error) {
  if (!uri || arguments.length === 0) { return false; }

  uri = encodeURI(uri);

  if (uri.match('http')) {
    downloadAndOpen(uri, success, error);
  } else {
    exec(onSuccess.bind(this, uri, success),
         onError.bind(this, error), 'Open', 'open', [uri]);
  }
};

/**
 * downloadAndOpen
 *
 * @param {String} url File URI
 * @param {Function} success Success callback
 * @param {Function} error Failure callback
 */
function downloadAndOpen(url, success, error) {
  var ft = new FileTransfer();
  var ios = cordova.file.cacheDirectory;
  var ext = cordova.file.externalCacheDirectory;
  var dir = (ext) ?  ext : ios;
  var name = url.substring(url.lastIndexOf('/') + 1);
  var path = dir + name;

  ft.download(url, path,
      function done(entry) {
        var file = entry.toURL();
        exec(onSuccess.bind(this, file, success),
             onError.bind(this, error), 'Open', 'open', [file]);
      },
      onError,
      false
  );
}

/**
 * onSuccess
 *
 * @param {String} path File URI
 * @param {Function} callback Callback
 * @return {String} File URI
 */
function onSuccess(path, callback) {
  fire('success');
  if (typeof callback === 'function') { callback(path); }
  return path;
}

/**
 * onError
 *
 * @param {String} path File URI
 * @param {Function} callback Callback
 * @return {Number} Error code
 */
function onError(code, callback) {
  fire('error');
  code = code || 0;
  if (typeof callback === 'function') { callback(code); }
  return code;
}

/**
 * fire
 *
 * @param {String} event Event name
 */
function fire(event) {
  var channel = require('cordova/channel');
  var cordova = require('cordova');

  channel.onCordovaReady.subscribe(function() {
    cordova.fireDocumentEvent('open.' + event);
  });
}
<|endoftext|>


<commit_before>/**
 * @license
 * Copyright 2016 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Externs for our custom filters defined in test/test/boot.js.
 * @externs
 */

/**
 * @param {string} name
 * @param {jasmine.Callback} callback
 */
var externalIt = function(name, callback) {};

/**
 * @param {string} name
 * @param {jasmine.Callback} callback
 */
var drmIt = function(name, callback) {};

/**
 * @param {string} name
 * @param {jasmine.Callback} callback
 */
var quarantinedIt = function(name, callback) {};
<commit_msg>Drop unused extern<commit_after>/**
 * @license
 * Copyright 2016 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * @fileoverview Externs for our custom filters defined in test/test/boot.js.
 * @externs
 */

/**
 * @param {string} name
 * @param {jasmine.Callback} callback
 */
var drmIt = function(name, callback) {};

/**
 * @param {string} name
 * @param {jasmine.Callback} callback
 */
var quarantinedIt = function(name, callback) {};
<|endoftext|>


<commit_before><commit_msg>Whitespace fixes<commit_after><|endoftext|>