<commit_before>var loadFile=function(url,callback){
  JSZipUtils.getBinaryContent(url,callback);
};

var run_template= function(data) {
  loadFile("cv_template.docx",function(err,content){
    if (err) {
      //console.debug(err);
      throw err
    };
    doc=new Docxgen(content);
    doc.setData(data);
    doc.render(); //apply them (replace all occurences of {first_name} by Hipp, ...)
    out=doc.getZip().generate({type:"blob"}) //Output the document using Data-URI
    saveAs(out,"cv.docx")
  });
};

// template if person only has Academic Articles
var run_template_a= function(data) {
  loadFile("cv_template_only_a.docx",function(err,content){
    if (err) {
      //console.debug(err);
      throw err
    };
    doc=new Docxgen(content);
    doc.setData(data);
    doc.render(); //apply them (replace all occurences of {first_name} by Hipp, ...)
    out=doc.getZip().generate({type:"blob"}) //Output the document using Data-URI
    saveAs(out,"cv.docx")
  });
};

// this returns query string (everything after =)
function getParameterByName(name) {
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  results = regex.exec(location.search);
  return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};

var get_data = function(uri) {
  var base_url = "https://scholars.duke.edu/widgets/api/v0.9/people/complete/all.jsonp?";
  var uri = getParameterByName('uri');
  var person_uri = "uri=" + uri;
  var url = base_url + person_uri;
  $.ajax({
    url: url,
    cache: false,
    dataType: "jsonp",
    method: 'GET',
    }).done(function(data) {
      //gets ride of html tags
      var stripHtml = /(<([^>]+)>)/ig;
      var stripOpeningTag = /<a\b[^>]*>/i;
      var stripClosingTag = /<\/a>/i;

      // encompassing hash
      var results = {'cv': [], 'academicArticlesLabel': [], 'booksLabel': [], 'name': [], 'primaryPositionLabel': [], 'primaryPosition': [],
                     'secondaryPositionLabel': [], 'secondaryPosition': [], 'educationsLabel': [], 'educations': [], 'publicationsLabel': [],
                     'bookReviewsLabel': [], 'bookSectionsLabel': [], 'bookSeriesLabel': [], 'conferencePapersLabel': [], 'datasetsLabel': [], 'digitalPublicationsLabel': [],
                     'journalIssuesLabel': [], 'reportsLabel': [], 'scholarlyEditionsLabel': [], 'thesesLabel': [], 'otherArticlesLabel': [],
                     'academicArticles': [], 'books': [], 'bookReviews': [], 'bookSections': [], 'bookSeries': [],
                     'conferencePapers': [], 'datasets': [], 'digitalPublications': [], 'journalIssues': [], 'reports': [], 'scholarlyEdition': [],
                     'theses': [], 'otherArticles': [], 'softwareLabel': [], 'software': [], 'teachingLabel': [], 'teaching': [], 'grantsLabel': [],
                     'grants': [], 'researchInterestsLabel': [], 'awardsLabel': [], 'awards': [], 'presentationsLabel': [], 'presentations': [],
                     'servicesToProfessionLabel': [], 'servicesToProfession': [], 'servicesToDukeLabel': [], 'servicesToDuke': [], 'outreachLabel': [],
                     'outreach': [], 'researchInterests': []
      };

      //name
      var firstName = data['attributes']['firstName'];
      var middleName = data['attributes']['middleName'];
      var lastName = data['attributes']['lastName'];
      if (typeof middleName != 'undefined' && middleName != null && middleName.length > 0) {
        var fullName = firstName + " " + middleName + " " + lastName;
      }
      else {
        var fullName = firstName + " " + lastName;
        middle = false;
      };
      results['name'].push({'fullName': fullName});

      // primary & secondary positions
      var positions =  data['positions'];
      var positionTypes = {
        'primaryPosition': 'http://vivoweb.org/ontology/core#PrimaryPosition',
        'secondaryPosition': 'http://vivo.duke.edu/vivo/ontology/duke-extension#SecondaryPosition'
      };
      if (typeof positions != 'undefined' && positions != null && positions.length > 0) {
        $.each(positions, function(index, value) {
          var vivoType = value['vivoType'];
          var label = value['label'];
          if (vivoType != null) {
            switch (vivoType) {
              case positionTypes['primaryPosition']:
                results['primaryPosition'].push({'label': label});
                results['primaryPositionLabel'][0] = "Primary Appointment:";
              break;
              case positionTypes['secondaryPosition']:
                results['secondaryPosition'].push({'label':label});
                results['secondaryPositionLabel'][0] = "Secondary Appointment:";
              break;
            };
          };
        });
      }
      else {
        positions = false;
      };

      // present academic rank and title
      var title = data['title'];

      //educations
      var educations = data['educations'];
      if (typeof educations != 'undefined' && educations != null && educations.length > 0) {
        results['educationsLabel'] = "Education:";
        $.each(educations, function(index, value) {
          var institution = value.attributes['institution'];
          var endYear = [value.attributes['endDate'].substr(0,4)];
          var degree = value.attributes['degree'];
          var label = value['label'];
          if (typeof degree != 'undefined') {
            var degree = value.attributes['degree'];
            var allEducation = (degree + ", " + institution + " " + endYear);
          }
          else {
            allEducation = (label + ", " + institution + " " + endYear);
          }
          results['educations'].push({'allEducation': allEducation});
        });
      }
      else {
        educations = false;
      };
      results['educations'].reverse();

      //research interests
      var overview = data['attributes']['overview'];
      if (typeof overview != 'undefined' && overview != null && overview.length > 0) {
        results['researchInterestsLabel'] = "Research Interests:";
        var research_interests = overview.replace(stripHtml, "");
        research_interests = research_interests.replace(/( )*/g,"");
        results['researchInterests'].push({'research_interests': research_interests});
      }
      else {
        overview = false;
        research_interests = false;
      };

      results['cv'].push({'title': title});

      var pubTypes = {
                      'academicArticles': 'http://purl.org/ontology/bibo/AcademicArticle',
                      'books': 'http://purl.org/ontology/bibo/Book',
                      'bookReviews': 'http://vivoweb.org/ontology/core#Review',
                      'bookSections': 'http://purl.org/ontology/bibo/BookSection',
                      'bookSeries': 'http://vivo.duke.edu/vivo/ontology/duke-extension#BookSeries',
                      'conferencePapers': 'http://vivoweb.org/ontology/core#ConferencePaper',
                      'datasets': 'http://vivoweb.org/ontology/core#Dataset',
                      'digitalPublications': 'http://vivo.duke.edu/vivo/ontology/dukeextension#DigitalPublication',
                      'journalIssues': 'http://vivo.duke.edu/vivo/ontology/duke-extension#JournalIssue',
                      'reports': 'http://purl.org/ontology/bibo/Report',
                      'scholarlyEdition': 'http://purl.org/ontology/bibo/EditedBook',
                      'theses': 'http://purl.org/ontology/bibo/Thesis',
                      'otherArticles': 'http://vivo.duke.edu/vivo/ontology/duke-extension#OtherArticle',
                      'software': 'http://vivoweb.org/ontology/core#Software'
      };

      var pubs = data['publications'];
      if (typeof pubs != 'undefined' && pubs != null && pubs.length > 0) {
        results['publicationsLabel'][0] = "Publications:";
        $.each(pubs, function(index, value) {
          var citation = value.attributes['mlaCitation'].replace(stripOpeningTag,"").replace(stripClosingTag, "");
          citation = citation.replace(stripHtml, "");
          var pubmed = value.attributes['pmid'];
          var vivoType = value['vivoType'];
          var date = value.attributes['datetime'];
          if (vivoType != null) {
            if (vivoType === pubTypes['academicArticles']) {
              var academicArticles = "Academic Articles";
              results['academicArticlesLabel'] = academicArticles;
              results['academicArticles'].push({'pubmed': pubmed});

            };
            if (vivoType === pubTypes['books']) {
              var books = "Books";
              results['booksLabel'] = books;
              results['books'].push({'citation': citation});
            };
            if (vivoType === pubTypes['bookReviews']) {
              var bookReviews = "Book Reviews";
              results['bookReviewsLabel'] = bookReviews;
              results['bookReviews'].push({'citation':citation});
            };
            if (vivoType === pubTypes['bookSections']) {
              var bookSections = "Book Sections";
              results['bookSectionsLabel'] = bookSections;
              results['bookSections'].push({'citation': citation});
            };
            if (vivoType === pubTypes['bookSeries']) {
              var bookSeries = "Book Series";
              results['bookSeriesLabel'] = bookSeries;
              results['bookSeries'].push({'citation': citation});
            };
            if (vivoType === pubTypes['conferencePapers']) {
              var conferencePapers = "Conference Papers";
              results['conferencePapersLabel'] = conferencePapers;
              results['conferencePapers'].push({'citation': citation});
            };
            if (vivoType === pubTypes['datasets']) {
              var datasets = "Datasets";
              results['datasetsLabel'] = datasets;
              results['datasets'].push({'citation': citation});
            };
            if (vivoType === pubTypes['digitalPublications']) {
              var digitalPublications = "Digital Publications";
              results['digitalPublicationsLabel'] = digitalPublications;
              results['digitalPublications'].push({'citation': citation});
            };
            if (vivoType === pubTypes['journalIssues']) {
              var journalIssues = "Journal Issues";
              results['journalIssuesLabel'] = journalIssues;
              results['journalIssues'].push({'citation': citation});
            };
            if (vivoType === pubTypes['reports']) {
              var reports = "Reports";
              results['reportsLabel'] = reports;
              results['reports'].push({'citation': citation});
            };
            if (vivoType === pubTypes['scholarlyEdition']) {
              var scholarlyEdition = "Scholarly Editions";
              results['scholarlyEditionsLabel'] = scholarlyEdition;
              results['scholarlyEdition'].push({'citation': citation});
            };
            if (vivoType === pubTypes['theses']) {
              var theses = "Theses and Dissertations";
              results['thesesLabel'] = theses;
              results['theses'].push({'citation': citation});
            };
            if (vivoType === pubTypes['otherArticles']) {
              var otherArticles = "Other Articles";
              results['otherArticlesLabel'] = otherArticles;
              results['otherArticles'].push({'citation': citation});
            };
            if (vivoType === pubTypes['software']) {
              var software = "Software";
              results['softwareLabel'] = software;
              results['software'].push({'citation': citation});
            };
          };
        });
        results['academicArticles'].reverse(), results['books'].reverse(), results['bookReviews'].reverse(), results['bookSections'].reverse(),
        results['bookSeries'].reverse(), results['conferencePapers'].reverse(), results['datasets'].reverse(), results['digitalPublications'].reverse(),
        results['journalIssues'].reverse(), results['reports'].reverse(), results['scholarlyEdition'].reverse(), results['theses'].reverse(),
        results['otherArticles'].reverse(), results['software'].reverse();

      };

      //TEACHING
      var teaching = data['courses'];
      if (typeof teaching != 'undefined' && teaching != null && teaching.length > 0) {
        results['teachingLabel'][0] = "Teaching Responsibilities:";
        $.each(teaching, function(index, value) {
          var label = value['label'];
          results['teaching'].push({'label':label});
        });
      }
      else {
        teaching = false;
      };

      //GRANTS
      var grants = data['grants'];
      if (typeof grants != 'undefined' && grants != null && grants.length > 0) {
        results['grantsLabel'][0] = "Grants:";
        $.each(grants, function(index, value) {
          var label = value['label'] + ", awarded by "
          var awardedBy = value.attributes['awardedBy'] + ", ";
          var startDate = value.attributes['startDate'].substr(0,4) + " - ";
          var endDate = value.attributes['endDate'].substr(0,4) + " ";
          var role = value.attributes['roleName'];
          results['grants'].push({'label':label, 'awardedBy': awardedBy,
                                  'startDate': startDate, 'endDate': endDate, 'role': role});
        });
      }
      else {
        grants = false;
      };

      //AWARDS
      var awards = data['awards'];
      if (typeof awards != 'undefined' && awards != null && awards.length > 0) {
        results['awardsLabel'][0] = "Awards and Honors:";
        $.each(awards, function(index,value) {
          var label = value['label'];
          var date = value['attributes']['date'].substr(0,4);
          var label = (label + " " + date);
          results['awards'].push({'label':label});
        });
      }
      else {
        awards = false;
      };

      //PROFESSIONAL ACTIVITIES
      var professionalActivitiesTypes = {
                                         'presentations': 'http://vivo.duke.edu/vivo/ontology/duke-activity-extension#Presentation',
                                         'servicesToProfession': 'http://vivo.duke.edu/vivo/ontology/duke-activity-extension#ServiceToTheProfession',
                                         'servicesToDuke': 'http://vivo.duke.edu/vivo/ontology/duke-activity-extension#ServiceToTheUniversity',
                                         'outreach': 'http://vivo.duke.edu/vivo/ontology/duke-activity-extension#Outreach'
      };

      var professionalActivities = data['professionalActivities'];
      $.each(professionalActivities, function(index,value) {
        var label = value['label'];
        var vivoType = value['vivoType'];
        if (vivoType != null) {
          switch (vivoType) {
            case professionalActivitiesTypes['presentations']:
              results['presentationsLabel'][0] = "Presentations and Appearances:";
              results['presentations'].push({'label':label});
              break;
            case professionalActivitiesTypes['servicesToProfession']:
              results['servicesToProfessionLabel'][0] = "Services to the Profession:";
              results['servicesToProfession'].push({'label':label});
              break;
            case professionalActivitiesTypes['servicesToDuke']:
              results['servicesToDukeLabel'][0] = "Services to Duke:";
              results['servicesToDuke'].push({'label': label});
              break;
            default:
              results['outreachLabel'][0] = "Outreach and Engaged Scholarship:";
              results['outreach'].push({'label':label});
          };
        }
        else {
          professionalActivities = false;
        };
      });

      // different templates for different pub data
      if (results['academicArticles'].length >= 1 && results['books'].length === 0 && results['bookReviews'].length === 0 &&
          results['bookSections'].length === 0 && results['bookSeries'].length === 0 && results['conferencePapers'].length === 0 &&
          results['datasets'].length === 0 && results['digitalPublications'].length === 0 && results['journalIssues'].length === 0 &&
          results['reports'].length === 0 && results['scholarlyEdition'].length === 0 && results['theses'].length === 0 &&
          results['otherArticles'].length === 0 && results['software'].length === 0)
      {
        run_template_a(results);
      }
      else {
        run_template(results);
      };

      }).fail(function(xhr, textStatus, err) {
        //console.log(textStatus);
      });
    };

    $(document).ready(function(e){
      e.preventDefault;
      get_data();
    });

  <commit_msg>changes<commit_after>var loadFile=function(url,callback){
  JSZipUtils.getBinaryContent(url,callback);
};

var run_template= function(data) {
  loadFile("cv_template.docx",function(err,content){
    if (err) {
      //console.debug(err);
      throw err
    };
    doc=new Docxgen(content);
    doc.setData(data);
    doc.render(); //apply them (replace all occurences of {first_name} by Hipp, ...)
    out=doc.getZip().generate({type:"blob"}) //Output the document using Data-URI
    saveAs(out,"cv.docx")
  });
};

// template if person only has Academic Articles
var run_template_a= function(data) {
  loadFile("cv_template_only_a.docx",function(err,content){
    if (err) {
      //console.debug(err);
      throw err
    };
    doc=new Docxgen(content);
    doc.setData(data);
    doc.render(); //apply them (replace all occurences of {first_name} by Hipp, ...)
    out=doc.getZip().generate({type:"blob"}) //Output the document using Data-URI
    saveAs(out,"cv.docx")
  });
};

// this returns query string (everything after =)
function getParameterByName(name) {
  name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
  var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
  results = regex.exec(location.search);
  return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};

var get_data = function(uri) {
  var base_url = "https://scholars.duke.edu/widgets/api/v0.9/people/complete/all.jsonp?";
  var uri = getParameterByName('uri');
  var person_uri = "uri=" + uri;
  var url = base_url + person_uri;
  $.ajax({
    url: url,
    cache: false,
    dataType: "jsonp",
    method: 'GET',
    }).done(function(data) {
      //gets ride of html tags
      var stripHtml = /(<([^>]+)>)/ig;
      var stripOpeningTag = /<a\b[^>]*>/i;
      var stripClosingTag = /<\/a>/i;

      // encompassing hash
      var results = {'cv': [], 'academicArticlesLabel': [], 'booksLabel': [], 'name': [], 'primaryPositionLabel': [], 'primaryPosition': [],
                     'secondaryPositionLabel': [], 'secondaryPosition': [], 'educationsLabel': [], 'educations': [], 'publicationsLabel': [],
                     'bookReviewsLabel': [], 'bookSectionsLabel': [], 'bookSeriesLabel': [], 'conferencePapersLabel': [], 'datasetsLabel': [], 'digitalPublicationsLabel': [],
                     'journalIssuesLabel': [], 'reportsLabel': [], 'scholarlyEditionsLabel': [], 'thesesLabel': [], 'otherArticlesLabel': [],
                     'academicArticles': [], 'books': [], 'bookReviews': [], 'bookSections': [], 'bookSeries': [],
                     'conferencePapers': [], 'datasets': [], 'digitalPublications': [], 'journalIssues': [], 'reports': [], 'scholarlyEdition': [],
                     'theses': [], 'otherArticles': [], 'softwareLabel': [], 'software': [], 'teachingLabel': [], 'teaching': [], 'grantsLabel': [],
                     'grants': [], 'researchInterestsLabel': [], 'awardsLabel': [], 'awards': [], 'presentationsLabel': [], 'presentations': [],
                     'servicesToProfessionLabel': [], 'servicesToProfession': [], 'servicesToDukeLabel': [], 'servicesToDuke': [], 'outreachLabel': [],
                     'outreach': [], 'researchInterests': []
      };

      //name
      var firstName = data['attributes']['firstName'];
      var middleName = data['attributes']['middleName'];
      var lastName = data['attributes']['lastName'];
      if (typeof middleName != 'undefined' && middleName != null && middleName.length > 0) {
        var fullName = firstName + " " + middleName + " " + lastName;
      }
      else {
        var fullName = firstName + " " + lastName;
        middle = false;
      };
      results['name'].push({'fullName': fullName});

      // primary & secondary positions
      var positions =  data['positions'];
      var positionTypes = {
        'primaryPosition': 'http://vivoweb.org/ontology/core#PrimaryPosition',
        'secondaryPosition': 'http://vivo.duke.edu/vivo/ontology/duke-extension#SecondaryPosition'
      };
      if (typeof positions != 'undefined' && positions != null && positions.length > 0) {
        $.each(positions, function(index, value) {
          var vivoType = value['vivoType'];
          var label = value['label'];
          if (vivoType != null) {
            switch (vivoType) {
              case positionTypes['primaryPosition']:
                results['primaryPosition'].push({'label': label});
                results['primaryPositionLabel'][0] = "Primary Appointment:";
              break;
              case positionTypes['secondaryPosition']:
                results['secondaryPosition'].push({'label':label});
                results['secondaryPositionLabel'][0] = "Secondary Appointment:";
              break;
            };
          };
        });
      }
      else {
        positions = false;
      };

      // present academic rank and title
      var title = data['title'];

      //educations
      var educations = data['educations'];
      if (typeof educations != 'undefined' && educations != null && educations.length > 0) {
        results['educationsLabel'] = "Education:";
        $.each(educations, function(index, value) {
          var institution = value.attributes['institution'];
          var endYear = [value.attributes['endDate'].substr(0,4)];
          var degree = value.attributes['degree'];
          var label = value['label'];
          if (typeof degree != 'undefined') {
            var degree = value.attributes['degree'];
            var allEducation = (degree + ", " + institution + " " + endYear);
          }
          else {
            allEducation = (label + ", " + institution + " " + endYear);
          }
          results['educations'].push({'allEducation': allEducation});
        });
      }
      else {
        educations = false;
      };
      results['educations'].reverse();

      //research interests
      var overview = data['attributes']['overview'];
      if (typeof overview != 'undefined' && overview != null && overview.length > 0) {
        results['researchInterestsLabel'] = "Research Interests:";
        var research_interests = overview.replace(stripHtml, "");
        research_interests = research_interests.replace(/( )*/g,"");
        results['researchInterests'].push({'research_interests': research_interests});
      }
      else {
        overview = false;
        research_interests = false;
      };

      results['cv'].push({'title': title});

      var pubTypes = {
                      'academicArticles': 'http://purl.org/ontology/bibo/AcademicArticle',
                      'books': 'http://purl.org/ontology/bibo/Book',
                      'bookReviews': 'http://vivoweb.org/ontology/core#Review',
                      'bookSections': 'http://purl.org/ontology/bibo/BookSection',
                      'bookSeries': 'http://vivo.duke.edu/vivo/ontology/duke-extension#BookSeries',
                      'conferencePapers': 'http://vivoweb.org/ontology/core#ConferencePaper',
                      'datasets': 'http://vivoweb.org/ontology/core#Dataset',
                      'digitalPublications': 'http://vivo.duke.edu/vivo/ontology/dukeextension#DigitalPublication',
                      'journalIssues': 'http://vivo.duke.edu/vivo/ontology/duke-extension#JournalIssue',
                      'reports': 'http://purl.org/ontology/bibo/Report',
                      'scholarlyEdition': 'http://purl.org/ontology/bibo/EditedBook',
                      'theses': 'http://purl.org/ontology/bibo/Thesis',
                      'otherArticles': 'http://vivo.duke.edu/vivo/ontology/duke-extension#OtherArticle',
                      'software': 'http://vivoweb.org/ontology/core#Software'
      };

      var pubs = data['publications'];
      if (typeof pubs != 'undefined' && pubs != null && pubs.length > 0) {
        results['publicationsLabel'][0] = "Publications:";
        $.each(pubs, function(index, value) {
          var citation = value.attributes['mlaCitation'].replace(stripOpeningTag,"").replace(stripClosingTag, "");
          citation = citation.replace(stripHtml, "");
          var pubmed = value.attributes['pmid'];
          console.log(pubmed);
          var vivoType = value['vivoType'];
          var date = value.attributes['datetime'];
          if (vivoType != null) {
            if (vivoType === pubTypes['academicArticles']) {
              var academicArticles = "Academic Articles";
              results['academicArticlesLabel'] = academicArticles;
              results['academicArticles'].push({'pubmed': pubmed});

            };
            if (vivoType === pubTypes['books']) {
              var books = "Books";
              results['booksLabel'] = books;
              results['books'].push({'citation': citation});
            };
            if (vivoType === pubTypes['bookReviews']) {
              var bookReviews = "Book Reviews";
              results['bookReviewsLabel'] = bookReviews;
              results['bookReviews'].push({'citation':citation});
            };
            if (vivoType === pubTypes['bookSections']) {
              var bookSections = "Book Sections";
              results['bookSectionsLabel'] = bookSections;
              results['bookSections'].push({'citation': citation});
            };
            if (vivoType === pubTypes['bookSeries']) {
              var bookSeries = "Book Series";
              results['bookSeriesLabel'] = bookSeries;
              results['bookSeries'].push({'citation': citation});
            };
            if (vivoType === pubTypes['conferencePapers']) {
              var conferencePapers = "Conference Papers";
              results['conferencePapersLabel'] = conferencePapers;
              results['conferencePapers'].push({'citation': citation});
            };
            if (vivoType === pubTypes['datasets']) {
              var datasets = "Datasets";
              results['datasetsLabel'] = datasets;
              results['datasets'].push({'citation': citation});
            };
            if (vivoType === pubTypes['digitalPublications']) {
              var digitalPublications = "Digital Publications";
              results['digitalPublicationsLabel'] = digitalPublications;
              results['digitalPublications'].push({'citation': citation});
            };
            if (vivoType === pubTypes['journalIssues']) {
              var journalIssues = "Journal Issues";
              results['journalIssuesLabel'] = journalIssues;
              results['journalIssues'].push({'citation': citation});
            };
            if (vivoType === pubTypes['reports']) {
              var reports = "Reports";
              results['reportsLabel'] = reports;
              results['reports'].push({'citation': citation});
            };
            if (vivoType === pubTypes['scholarlyEdition']) {
              var scholarlyEdition = "Scholarly Editions";
              results['scholarlyEditionsLabel'] = scholarlyEdition;
              results['scholarlyEdition'].push({'citation': citation});
            };
            if (vivoType === pubTypes['theses']) {
              var theses = "Theses and Dissertations";
              results['thesesLabel'] = theses;
              results['theses'].push({'citation': citation});
            };
            if (vivoType === pubTypes['otherArticles']) {
              var otherArticles = "Other Articles";
              results['otherArticlesLabel'] = otherArticles;
              results['otherArticles'].push({'citation': citation});
            };
            if (vivoType === pubTypes['software']) {
              var software = "Software";
              results['softwareLabel'] = software;
              results['software'].push({'citation': citation});
            };
          };
        });
        results['academicArticles'].reverse(), results['books'].reverse(), results['bookReviews'].reverse(), results['bookSections'].reverse(),
        results['bookSeries'].reverse(), results['conferencePapers'].reverse(), results['datasets'].reverse(), results['digitalPublications'].reverse(),
        results['journalIssues'].reverse(), results['reports'].reverse(), results['scholarlyEdition'].reverse(), results['theses'].reverse(),
        results['otherArticles'].reverse(), results['software'].reverse();

      };

      //TEACHING
      var teaching = data['courses'];
      if (typeof teaching != 'undefined' && teaching != null && teaching.length > 0) {
        results['teachingLabel'][0] = "Teaching Responsibilities:";
        $.each(teaching, function(index, value) {
          var label = value['label'];
          results['teaching'].push({'label':label});
        });
      }
      else {
        teaching = false;
      };

      //GRANTS
      var grants = data['grants'];
      if (typeof grants != 'undefined' && grants != null && grants.length > 0) {
        results['grantsLabel'][0] = "Grants:";
        $.each(grants, function(index, value) {
          var label = value['label'] + ", awarded by "
          var awardedBy = value.attributes['awardedBy'] + ", ";
          var startDate = value.attributes['startDate'].substr(0,4) + " - ";
          var endDate = value.attributes['endDate'].substr(0,4) + " ";
          var role = value.attributes['roleName'];
          results['grants'].push({'label':label, 'awardedBy': awardedBy,
                                  'startDate': startDate, 'endDate': endDate, 'role': role});
        });
      }
      else {
        grants = false;
      };

      //AWARDS
      var awards = data['awards'];
      if (typeof awards != 'undefined' && awards != null && awards.length > 0) {
        results['awardsLabel'][0] = "Awards and Honors:";
        $.each(awards, function(index,value) {
          var label = value['label'];
          var date = value['attributes']['date'].substr(0,4);
          var label = (label + " " + date);
          results['awards'].push({'label':label});
        });
      }
      else {
        awards = false;
      };

      //PROFESSIONAL ACTIVITIES
      var professionalActivitiesTypes = {
                                         'presentations': 'http://vivo.duke.edu/vivo/ontology/duke-activity-extension#Presentation',
                                         'servicesToProfession': 'http://vivo.duke.edu/vivo/ontology/duke-activity-extension#ServiceToTheProfession',
                                         'servicesToDuke': 'http://vivo.duke.edu/vivo/ontology/duke-activity-extension#ServiceToTheUniversity',
                                         'outreach': 'http://vivo.duke.edu/vivo/ontology/duke-activity-extension#Outreach'
      };

      var professionalActivities = data['professionalActivities'];
      $.each(professionalActivities, function(index,value) {
        var label = value['label'];
        var vivoType = value['vivoType'];
        if (vivoType != null) {
          switch (vivoType) {
            case professionalActivitiesTypes['presentations']:
              results['presentationsLabel'][0] = "Presentations and Appearances:";
              results['presentations'].push({'label':label});
              break;
            case professionalActivitiesTypes['servicesToProfession']:
              results['servicesToProfessionLabel'][0] = "Services to the Profession:";
              results['servicesToProfession'].push({'label':label});
              break;
            case professionalActivitiesTypes['servicesToDuke']:
              results['servicesToDukeLabel'][0] = "Services to Duke:";
              results['servicesToDuke'].push({'label': label});
              break;
            default:
              results['outreachLabel'][0] = "Outreach and Engaged Scholarship:";
              results['outreach'].push({'label':label});
          };
        }
        else {
          professionalActivities = false;
        };
      });

      // different templates for different pub data
      if (results['academicArticles'].length >= 1 && results['books'].length === 0 && results['bookReviews'].length === 0 &&
          results['bookSections'].length === 0 && results['bookSeries'].length === 0 && results['conferencePapers'].length === 0 &&
          results['datasets'].length === 0 && results['digitalPublications'].length === 0 && results['journalIssues'].length === 0 &&
          results['reports'].length === 0 && results['scholarlyEdition'].length === 0 && results['theses'].length === 0 &&
          results['otherArticles'].length === 0 && results['software'].length === 0)
      {
        run_template_a(results);
      }
      else {
        run_template(results);
      };

      }).fail(function(xhr, textStatus, err) {
        //console.log(textStatus);
      });
    };

    $(document).ready(function(e){
      e.preventDefault;
      get_data();
    });

  <|endoftext|>


<commit_before>var deps = [
    'ui.router',
    'ngAnimate',
    'ngMaterial',
    'mdl',
    'ngIntercom',
    'ngStorage',
    'MinecraftlyAppControllers',
    'MinecraftlyAppServices'
];
angular.module("MinecraftlyAppControllers", []);
angular.module("MinecraftlyAppServices", []);
angular.module('MinecraftlyApp', deps)
        .run(function ($window) {
        })
        .config(function ($stateProvider, $locationProvider, $urlRouterProvider, IntercomProvider) {// $mdThemingProvider, $mdIconProvider,
            IntercomProvider.init('t02jhyr0');
//            $mdThemingProvider.theme('MinecraftlyTheme')
//                    .primaryPalette('blue')
//                    .accentPalette('purple')
//                    .warnPalette('deep-purple');
//            $mdThemingProvider.setDefaultTheme('MinecraftlyTheme');
//            $mdIconProvider
//                    .defaultIconSet('/img/mdi.svg');
            $locationProvider.html5Mode(true);
            $stateProvider
                    .state('app', {
                        url: "",
                        abstract: true,
                        templateUrl: "templates/app.html",
                        controller: 'AppCtrl'
                    })
            .state('app.home', {
                        cache: false,
                        url: "/",
                        views: {
                            'appContent': {
                                templateUrl: "templates/home.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.play', {
                        cache: false,
                        url: "/play",
                        views: {
                            'appContent': {
                                templateUrl: "templates/play.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.vote', {
                        cache: false,
                        url: "/vote",
                        views: {
                            'appContent': {
                                templateUrl: "templates/vote.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.team', {
                        cache: false,
                        url: "/team",
                        views: {
                            'appContent': {
                                templateUrl: "templates/team.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.about', {
                        cache: false,
                        url: "/about",
                        views: {
                            'appContent': {
                                templateUrl: "templates/about.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.education', {
                        cache: false,
                        url: "/education",
                        views: {
                            'appContent': {
                                templateUrl: "templates/education.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.jobs', {
                        cache: false,
                        url: "/jobs",
                        views: {
                            'appContent': {
                                templateUrl: "templates/jobs.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.terms', {
                        cache: false,
                        url: "/terms",
                        views: {
                            'appContent': {
                                templateUrl: "templates/terms.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.privacy', {
                        cache: false,
                        url: "/privacy",
                        views: {
                            'appContent': {
                                templateUrl: "templates/privacy.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
		    .state('app.features', {
                        cache: false,
                        url: "/features",
                        views: {
                            'appContent': {
                                templateUrl: "templates/features.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
            $urlRouterProvider.otherwise('/');
        });

<commit_msg>add 404.html to url<commit_after>var deps = [
    'ui.router',
    'ngAnimate',
    'ngMaterial',
    'mdl',
    'ngIntercom',
    'ngStorage',
    'MinecraftlyAppControllers',
    'MinecraftlyAppServices'
];
angular.module("MinecraftlyAppControllers", []);
angular.module("MinecraftlyAppServices", []);
angular.module('MinecraftlyApp', deps)
        .run(function ($window) {
        })
        .config(function ($stateProvider, $locationProvider, $urlRouterProvider, IntercomProvider) {// $mdThemingProvider, $mdIconProvider,
            IntercomProvider.init('t02jhyr0');
//            $mdThemingProvider.theme('MinecraftlyTheme')
//                    .primaryPalette('blue')
//                    .accentPalette('purple')
//                    .warnPalette('deep-purple');
//            $mdThemingProvider.setDefaultTheme('MinecraftlyTheme');
//            $mdIconProvider
//                    .defaultIconSet('/img/mdi.svg');
            $locationProvider.html5Mode(true);
            $stateProvider
                    .state('app', {
                        url: "",
                        abstract: true,
                        templateUrl: "templates/app.html",
                        controller: 'AppCtrl'
                    })
            .state('app.home', {
                        cache: false,
                        url: "/",
                        views: {
                            'appContent': {
                                templateUrl: "templates/home.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.play', {
                        cache: false,
                        url: "/play",
                        views: {
                            'appContent': {
                                templateUrl: "templates/play.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.vote', {
                        cache: false,
                        url: "/vote",
                        views: {
                            'appContent': {
                                templateUrl: "templates/vote.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.team', {
                        cache: false,
                        url: "/team",
                        views: {
                            'appContent': {
                                templateUrl: "templates/team.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.about', {
                        cache: false,
                        url: "/about",
                        views: {
                            'appContent': {
                                templateUrl: "templates/about.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.education', {
                        cache: false,
                        url: "/education",
                        views: {
                            'appContent': {
                                templateUrl: "templates/education.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.jobs', {
                        cache: false,
                        url: "/jobs",
                        views: {
                            'appContent': {
                                templateUrl: "templates/jobs.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.terms', {
                        cache: false,
                        url: "/terms",
                        views: {
                            'appContent': {
                                templateUrl: "templates/terms.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.privacy', {
                        cache: false,
                        url: "/privacy",
                        views: {
                            'appContent': {
                                templateUrl: "templates/privacy.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
			.state('app.404', {
                        cache: false,
                        url: "/404.html",
                        views: {
                            'appContent': {
                                templateUrl: "templates/404.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    })
		    .state('app.features', {
                        cache: false,
                        url: "/features",
                        views: {
                            'appContent': {
                                templateUrl: "templates/features.html",
                                controller: 'HomeCtrl'
                            }
                        }
                    });
            $urlRouterProvider.otherwise('/');
        });

<|endoftext|>


<commit_before>function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function passwordsMatch () {
  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");

    return true;
  }

  $('#passGroup').addClass("has-error");

  return false;
}

function pageEncrypt() {
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
  }
}

function pageDecrypt () {
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
  }
}

$( function () {

  $('#encrypt').click( pageEncrypt );
  $('#decrypt').click( pageDecrypt );

  console.log('Page loaded');
});

<commit_msg>Update app.js<commit_after>function encrypt(text, pass) {
  //console.log('pass:' + pass + ' encrypt IN:' + text);
  var key = Sha256.hash(pass);
  var encrypted = Aes.Ctr.encrypt(text, key, 256);
  //console.log('encrypt OUT:' + encrypted);
  return encrypted;
}

function decrypt (text, pass) {
  //console.log('pass:' + pass + ' decrypt IN:' + text);
  var key = Sha256.hash(pass);
  var decrypted = Aes.Ctr.decrypt(text, key, 256);
  //console.log('decrypt OUT:' + decrypted);
  return decrypted;
}

function passwordsMatch () {
  if( $('#password').val() == $('#password2').val() ) {

    $('#passGroup').removeClass("has-error");

    return true;
  }

  $('#passGroup').addClass("has-error");

  return false;
}

function pageEncrypt() {
  if ( passwordsMatch() ) {
    $('#message').val( encrypt( $('#message').val(), $('#password').val() ) );
    $('#message').select();
  }
}

function pageDecrypt () {
  if( passwordsMatch() ) {
    $('#message').val( decrypt( $('#message').val(), $('#password').val() ) );
    $('#message').select();
  }
}

$( function () {

  $('#encrypt').click( pageEncrypt );
  $('#decrypt').click( pageDecrypt );

  console.log('Page loaded');
});

<|endoftext|>


<commit_before>var myFirebaseRef = new Firebase("https://fiery-inferno-6630.firebaseio.com/");

	    var message = myFirebaseRef.child("selection")
	    var gyr_x = myFirebaseRef.child("gyr_x");
	    var gyr_y = myFirebaseRef.child("gyr_y");
	    var gyr_z = myFirebaseRef.child("gyr_z");
	    var acc_x = myFirebaseRef.child("acc_x");
	    var acc_y = myFirebaseRef.child("acc_y");
	    var acc_z = myFirebaseRef.child("acc_z");

		var $right = $(".glyphicon-chevron-right");
		var $left = $(".glyphicon-chevron-left");

		var $first = $('div:first', '#menu'),
	    	$last = $('div:last', '#menu');

	    dir = {}

	    dir.gyr_x_val = 0;
	    dir.gyr_y_val = 0;
	    dir.gyr_z_val = 0;
	    dir.acc_x_val = 0;
	    dir.acc_y_val = 0;
	    dir.acc_z_val = 0;

		message.on("value", function(snapshot) {
		  	if(snapshot.val() == "up") {
		  		var $prev, $selected = $(".selected");

			    $prev = $selected.prev('div').length ? $selected.prev('div') : $last;
			    $selected.removeClass("selected");
			    $prev.addClass('selected');
		  	} else if(snapshot.val() == "down") {
		  		var $next, $selected = $(".selected");

			    $next = $selected.next('div').length ? $selected.next('div') : $first;
			    $selected.removeClass("selected");
			    $next.addClass('selected');
		  	} else if(snapshot.val() == "Toggle") {
		  		console.log("toggle");
		  		$selected = $(".selected");
		  		$selected.click();
		  	}
		  	message.set(null);
		});

		gyr_x.on("value", function(snapshot) {
			dir.gyr_x_val = snapshot.val();
			$("#gyr_x").text(dir.gyr_x_val);
		});

		gyr_y.on("value", function(snapshot) {
			dir.gyr_y_val = snapshot.val();
			$("#gyr_y").text(dir.gyr_y_val);
		});

		gyr_z.on("value", function(snapshot) {
			dir.gyr_z_val = snapshot.val();
			$("#gyr_z").text(dir.gyr_z_val);
		});

		acc_x.on("value", function(snapshot) {
			dir.acc_x_val = snapshot.val();
			$("#acc_x").text(dir.acc_x_val);
		});

		acc_y.on("value", function(snapshot) {
			dir.acc_y_val = snapshot.val();
			$("#acc_y").text(dir.acc_y_val);
		});

		acc_z.on("value", function(snapshot) {
			dir.acc_z_val = snapshot.val();
			$("#acc_z").text(dir.acc_z_val);
		});

		$( ".settings" ).click(function() {
			console.log("settings");
			$("#settings").toggle();
		});

		$( ".jetpack_dir" ).click(function() {
			console.log("jetpack_dir");
			$("#jetpack").toggle();
		});

		var renderer	= new THREE.WebGLRenderer({
			antialias	: true
		});
		renderer.setSize( window.innerWidth, window.innerHeight );
		document.getElementById('hud').appendChild( renderer.domElement );
		renderer.shadowMapEnabled	= true

		var onRenderFcts= [];
		var scene	= new THREE.Scene();
		var camera	= new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.01, 100 );
		camera.position.z = 1;
		var light	= new THREE.AmbientLight( 0x222222 )
		scene.add( light )
		var light	= new THREE.DirectionalLight( 0xffffff, 1 )
		light.position.set(5,5,5)
		scene.add( light )
		light.castShadow	= true
		light.shadowCameraNear	= 0.01
		light.shadowCameraFar	= 15
		light.shadowCameraFov	= 45
		light.shadowCameraLeft	= -1
		light.shadowCameraRight	=  1
		light.shadowCameraTop	=  1
		light.shadowCameraBottom= -1
		// light.shadowCameraVisible	= true
		light.shadowBias	= 0.001
		light.shadowDarkness	= 0.2
		light.shadowMapWidth	= 1024
		light.shadowMapHeight	= 1024

		//////////////////////////////////////////////////////////////////////////////////
		//		added starfield							//
		//////////////////////////////////////////////////////////////////////////////////

		var starSphere	= THREEx.Planets.createStarfield()
		scene.add(starSphere)

		//////////////////////////////////////////////////////////////////////////////////
		//		add an object and make it move					//
		//////////////////////////////////////////////////////////////////////////////////
		// var datGUI	= new dat.GUI()
		var containerEarth	= new THREE.Object3D()
		containerEarth.rotateZ(-23.4 * Math.PI/180)
		containerEarth.position.z	= 0
		scene.add(containerEarth)
		var moonMesh	= THREEx.Planets.createMoon()
		moonMesh.position.set(0.5,0.5,0.5)
		moonMesh.scale.multiplyScalar(1/5)
		moonMesh.receiveShadow	= true
		moonMesh.castShadow	= true
		containerEarth.add(moonMesh)
		var earthMesh	= THREEx.Planets.createEarth()
		earthMesh.receiveShadow	= true
		earthMesh.castShadow	= true
		containerEarth.add(earthMesh)
		onRenderFcts.push(function(delta, now){
			earthMesh.rotation.y += 1/32 * delta;
		})
		var geometry	= new THREE.SphereGeometry(0.5, 32, 32)
		var material	= THREEx.createAtmosphereMaterial()
		material.uniforms.glowColor.value.set(0x00b3ff)
		material.uniforms.coeficient.value	= 0.8
		material.uniforms.power.value		= 2.0
		var mesh	= new THREE.Mesh(geometry, material );
		mesh.scale.multiplyScalar(1.01);
		containerEarth.add( mesh );

		// new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)
		var geometry	= new THREE.SphereGeometry(0.5, 32, 32)
		var material	= THREEx.createAtmosphereMaterial()
		material.side	= THREE.BackSide
		material.uniforms.glowColor.value.set(0x00b3ff)
		material.uniforms.coeficient.value	= 0.5
		material.uniforms.power.value		= 4.0
		var mesh	= new THREE.Mesh(geometry, material );
		mesh.scale.multiplyScalar(1.15);
		containerEarth.add( mesh );

		// new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)
		var earthCloud	= THREEx.Planets.createEarthCloud()
		earthCloud.receiveShadow	= true
		earthCloud.castShadow	= true
		containerEarth.add(earthCloud)
		onRenderFcts.push(function(delta, now){
			earthCloud.rotation.y += 1/8 * delta;
		})

		//////////////////////////////////////////////////////////////////////////////////
		//		Camera Controls							//
		//////////////////////////////////////////////////////////////////////////////////
		// var mouse	= {x : 0, y : 0}
		// document.addEventListener('mousemove', function(event){
		// 	mouse.x	= (dir.gyr_x_val / window.innerWidth ) - 0.5
		// 	mouse.y	= (dir.gyr_y_val / window.innerHeight) - 0.5
		// }, false)
		onRenderFcts.push(function(delta, now){
			camera.position.x += (dir.gyr_x_val/5 - camera.position.x) * (delta*3)
			camera.position.y += (dir.gyr_y_val/5 - camera.position.y) * (delta*3)
			// camera.position.x += (gyr_x*5 - camera.position.x) * (delta*3);
			// camera.position.y += (gyr_y*5 - camera.position.y) * (delta*3);
			camera.lookAt( scene.position )
		})
		//////////////////////////////////////////////////////////////////////////////////
		//		render the scene						//
		//////////////////////////////////////////////////////////////////////////////////
		onRenderFcts.push(function(){
			renderer.render( scene, camera );
		})

		//////////////////////////////////////////////////////////////////////////////////
		//		loop runner							//
		//////////////////////////////////////////////////////////////////////////////////
		var lastTimeMsec= null
		requestAnimationFrame(function animate(nowMsec){
			// keep looping
			requestAnimationFrame( animate );
			// measure time
			lastTimeMsec	= lastTimeMsec || nowMsec-1000/60
			var deltaMsec	= Math.min(200, nowMsec - lastTimeMsec)
			lastTimeMsec	= nowMsec
			// call each update function
			onRenderFcts.forEach(function(onRenderFct){
				onRenderFct(deltaMsec/1000, nowMsec/1000)
			})
		})<commit_msg>update<commit_after>var myFirebaseRef = new Firebase("https://fiery-inferno-6630.firebaseio.com/");

var message = myFirebaseRef.child("selection")
var gyr_x = myFirebaseRef.child("gyr_x");
var gyr_y = myFirebaseRef.child("gyr_y");
var gyr_z = myFirebaseRef.child("gyr_z");
var acc_x = myFirebaseRef.child("acc_x");
var acc_y = myFirebaseRef.child("acc_y");
var acc_z = myFirebaseRef.child("acc_z");

var go = myFirebaseRef.child("go");

var $right = $(".glyphicon-chevron-right");
var $left = $(".glyphicon-chevron-left");

var $first = $('div:first', '#menu'),
	$last = $('div:last', '#menu');

dir = {}

dir.gyr_x_val = 0;
dir.gyr_y_val = 0;
dir.gyr_z_val = 0;
dir.acc_x_val = 0;
dir.acc_y_val = 0;
dir.acc_z_val = 0;

message.on("value", function(snapshot) {
  	if(snapshot.val() == "up") {
  		var $prev, $selected = $(".selected");

	    $prev = $selected.prev('div').length ? $selected.prev('div') : $last;
	    $selected.removeClass("selected");
	    $prev.addClass('selected');
  	} else if(snapshot.val() == "down") {
  		var $next, $selected = $(".selected");

	    $next = $selected.next('div').length ? $selected.next('div') : $first;
	    $selected.removeClass("selected");
	    $next.addClass('selected');
  	} else if(snapshot.val() == "Toggle") {
  		console.log("toggle");
  		$selected = $(".selected");
  		$selected.click();
  	}
  	message.set(null);
});

gyr_x.on("value", function(snapshot) {
	var val = Math.round( snapshot.val() * 10) / 10
	if(val > 2) {
		dir.gyr_x_val = 1
	} else if (val < -2) {
		dir.gyr_x_val = -1
	} else if (val > -.05 && val < .05){
		dir.gyr_x_val = 0;
	}
	$("#gyr_x").text(dir.gyr_x_val);
});

gyr_y.on("value", function(snapshot) {
	var val = Math.round( snapshot.val() * 10) / 10
	if(val > 2) {
		dir.gyr_y_val = 1
	} else if (val < -2) {
		dir.gyr_y_val = -1
	} else if (val > -.05 && val < .05) {
		dir.gyr_y_val = 0;
	}
	$("#gyr_y").text(dir.gyr_y_val);
});

gyr_z.on("value", function(snapshot) {
	var val = Math.round( snapshot.val() * 10) / 10
	if(val > 2) {
		dir.gyr_z_val = 1
	} else if (val < -2) {
		dir.gyr_z_val = -1
	} else if (val > -.1 && val < .1){
		dir.gyr_z_val = 0;
	}
	$("#gyr_z").text(dir.gyr_z_val);
});

acc_x.on("value", function(snapshot) {
	dir.acc_x_val = Math.round( snapshot.val() * 10) / 10
	$("#acc_x").text(dir.acc_x_val);
});

acc_y.on("value", function(snapshot) {
	dir.acc_y_val = Math.round( snapshot.val() * 10) / 10
	$("#acc_y").text(dir.acc_y_val);
});

acc_z.on("value", function(snapshot) {
	dir.acc_z_val = Math.round( snapshot.val() * 10) / 10
	$("#acc_z").text(dir.acc_z_val);
});

$( ".settings" ).click(function() {
	console.log("settings");
	$("#settings").toggle();
});

$( ".jetpack_dir" ).click(function() {
	console.log("jetpack_dir");
	$("#jetpack").toggle();
});

var renderer	= new THREE.WebGLRenderer({
	antialias	: true
});
renderer.setSize( window.innerWidth, window.innerHeight );
document.getElementById('hud').appendChild( renderer.domElement );
renderer.shadowMapEnabled	= true

var onRenderFcts= [];
var scene	= new THREE.Scene();
var camera	= new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.01, 1000 );
camera.position.z = 1;
var light	= new THREE.AmbientLight( 0x222222 )
scene.add( light )
var light	= new THREE.DirectionalLight( 0xffffff, 1 )
light.position.set(5,5,5)
scene.add( light )
light.castShadow	= true
light.shadowCameraNear	= 0.01
light.shadowCameraFar	= 15
light.shadowCameraFov	= 45
light.shadowCameraLeft	= -1
light.shadowCameraRight	=  1
light.shadowCameraTop	=  1
light.shadowCameraBottom= -1
// light.shadowCameraVisible	= true
light.shadowBias	= 0.001
light.shadowDarkness	= 0.2
light.shadowMapWidth	= 1024
light.shadowMapHeight	= 1024

//////////////////////////////////////////////////////////////////////////////////
//		added starfield							//
//////////////////////////////////////////////////////////////////////////////////

var starSphere	= THREEx.Planets.createStarfield()
scene.add(starSphere)

//////////////////////////////////////////////////////////////////////////////////
//		add an object and make it move					//
//////////////////////////////////////////////////////////////////////////////////
// var datGUI	= new dat.GUI()
var containerEarth	= new THREE.Object3D()
//containerEarth.rotateZ(-23.4 * Math.PI/180)
containerEarth.position.z	= 0
scene.add(containerEarth)
var moonMesh	= THREEx.Planets.createMoon()
moonMesh.position.set(0.5,0.5,0.5)
moonMesh.scale.multiplyScalar(1/5)
moonMesh.receiveShadow	= true
//moonMesh.castShadow	= true
containerEarth.add(moonMesh)
var earthMesh	= THREEx.Planets.createEarth()
earthMesh.receiveShadow	= true
//earthMesh.castShadow	= true
containerEarth.add(earthMesh)
// onRenderFcts.push(function(delta, now){
// 	earthMesh.rotation.y += 1/32 * delta;
// })
var geometry	= new THREE.SphereGeometry(0.5, 32, 32)
var material	= THREEx.createAtmosphereMaterial()
material.uniforms.glowColor.value.set(0x00b3ff)
material.uniforms.coeficient.value	= 0.8
material.uniforms.power.value		= 2.0
var mesh	= new THREE.Mesh(geometry, material );
mesh.scale.multiplyScalar(1.01);
containerEarth.add( mesh );

// new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)
var geometry	= new THREE.SphereGeometry(0.5, 32, 32)
var material	= THREEx.createAtmosphereMaterial()
material.side	= THREE.BackSide
material.uniforms.glowColor.value.set(0x00b3ff)
material.uniforms.coeficient.value	= 0.5
material.uniforms.power.value		= 4.0
var mesh	= new THREE.Mesh(geometry, material );
mesh.scale.multiplyScalar(1.15);
containerEarth.add( mesh );

// new THREEx.addAtmosphereMaterial2DatGui(material, datGUI)
var earthCloud	= THREEx.Planets.createEarthCloud()
earthCloud.receiveShadow	= true
//earthCloud.castShadow	= true
containerEarth.add(earthCloud)
onRenderFcts.push(function(delta, now){
	earthCloud.rotation.y += 1/8 * delta;
})

//////////////////////////////////////////////////////////////////////////////////
//		Camera Controls							//
//////////////////////////////////////////////////////////////////////////////////
// var mouse	= {x : 0, y : 0}
// document.addEventListener('mousemove', function(event){
// 	mouse.x	= (dir.gyr_x_val / window.innerWidth ) - 0.5
// 	mouse.y	= (dir.gyr_y_val / window.innerHeight) - 0.5
// }, false)
onRenderFcts.push(function(delta, now){
	//camera.position.x -= (dir.acc_x_val/100 )//- camera.position.x) * (delta*3)
	//camera.position.y -= (dir.acc_z_val/100) //- camera.position.y) * (delta*3)
	if(dir.gyr_x_val >= 1) {
		camera.rotation.x +=.01;
	} else if (dir.gyr_x_val <= -1) {
		camera.rotation.x -= .01;
	}
	if(dir.gyr_z_val >= 1) {
		camera.rotation.y +=.01;
	} else if (dir.gyr_z_val <= -1) {
		camera.rotation.y -= .01;
	}
	if(dir.gyr_y_val >= 1) {
		camera.rotation.z -=.01;
	} else if (dir.gyr_y_val <= -1) {
		camera.rotation.z += .01;
	}
	//camera.position.z += (dir.gyr_x_val/100) //- camera.position.z) //* (delta*3)
	// camera.rotation.x += (dir.gyr_x_val/100 )//- camera.rotation.x) * (delta*3)
	// camera.rotation.y += (dir.gyr_y_val/100 )//- camera.rotation.y) * (delta*3)
	// camera.rotation.z += (dir.gyr_z_val/100 )//- camera.rotation.z) * (delta*3)

	// camera.position.x += (gyr_x*5 - camera.position.x) * (delta*3);
	// camera.position.y += (gyr_y*5 - camera.position.y) * (delta*3);
	//camera.lookAt( scene.position )
})
//////////////////////////////////////////////////////////////////////////////////
//		render the scene						//
//////////////////////////////////////////////////////////////////////////////////
onRenderFcts.push(function(){
	renderer.render( scene, camera );
})

//////////////////////////////////////////////////////////////////////////////////
//		loop runner							//
//////////////////////////////////////////////////////////////////////////////////
var lastTimeMsec= null
requestAnimationFrame(function animate(nowMsec){
	// keep looping
	requestAnimationFrame( animate );
	// measure time
	lastTimeMsec	= lastTimeMsec || nowMsec-1000/60
	var deltaMsec	= Math.min(200, nowMsec - lastTimeMsec)
	lastTimeMsec	= nowMsec
	// call each update function
	onRenderFcts.forEach(function(onRenderFct){
		onRenderFct(deltaMsec/1000, nowMsec/1000)
	})
})<|endoftext|>


<commit_before>var App = (function(){
	var servers = {"iceServers" :[{
	    url: 'stun:stun.l.google.com:19302'
	}]},

	signalData = {"desc":null,"ice":[]},
	peerConnection,
	localVideo = document.getElementById("localVideo"),
	localStream = null,
	remoteVideo = document.getElementById("remoteVideo"),
	txtBox      = $("#desc"),
	cpyRow      = $("#rowCpy"),
	cpyJumbRow  = $("#rowCpyJumb"),
  cpyJumBtn   = $("#btnCpyJumb")
	getUserMedia = navigator.getUserMedia.bind(navigator);

	var

	getPeerConnection = function(){
		peerConnection = new RTCPeerConnection(servers);
		peerConnection.onaddstream = gotRemoteStream;
		peerConnection.onicecandidate = gotIceCandidate;
		peerConnection.oniceconnectionstatechange = onConnectionStatusChange;
		peerConnection.onsignalingstatechange = (event) => {console.log("Signaling change"); console.log(event);}
	},

	getMediaStream = function(callback){
		getUserMedia(
			{	audio:true,
				video:true
			},function(stream){
				localStream = stream;
				callback(stream);
			},function(error){

		      console.log("getUserMedia error: ", error);

		    });
	},

	joinSession = function(){
		if(peerConnection == null){
			getPeerConnection();
		}

		var sigdata = JSON.parse(txtBox.val().trim());
		if(sigdata["desc"] == ""){
			alert("Please enter the offer");
			return;
		}
		getMediaStream(createAnswer);
	},

	createOffer = function(stream){
		localVideo.srcObject = stream;
  		peerConnection.addStream(stream);
  		peerConnection.createOffer(onConnection,handleError);
		txtBox.popover('show');
		cpyRow.show();
	},

	initiateOffer = function(){
		if(peerConnection == null){
			getPeerConnection();
		}
		getMediaStream(createOffer);
	},

	onConnection = function(desc){
		console.log("Description is "+desc.sdp);
		peerConnection.setLocalDescription(desc);
		signalData["desc"] = desc;
		//Change the event on click of Join Button to Complete Handshake on Initiator Side
		$("#joinBtn").off("click").on("click",completeHandshake);

	},

	createAnswer = function(stream){
		var sigdata = JSON.parse(txtBox.val().trim());
		localVideo.srcObject = stream;
		peerConnection.addStream(stream);
		peerConnection.setRemoteDescription(new RTCSessionDescription(sigdata["desc"]),function(){console.log("Success");},handleError);
		peerConnection.createAnswer(sendReply,handleError);
		addIceCandidates(sigdata["ice"]);
		txtBox.popover("show");
	},

	completeHandshake = function(){

		console.log("Inside complete handshake");
		var sigdata = document.getElementById("desc").value.trim();
		sigdata = JSON.parse(sigdata)
		if(!sigdata["desc"]){
			alert("Please enter the answer");
			return;
		}
		peerConnection.setRemoteDescription(new RTCSessionDescription(sigdata["desc"]),function(){console.log("Success");},handleError);
		addIceCandidates(sigdata["ice"]);

	},

	sendReply = function(desc){
		peerConnection.setLocalDescription(desc);
		signalData["desc"] = desc;
		console.log(JSON.stringify(signalData));
		cpyJumbRow.show();
		cpyJumBtn.popover('show');
	},

	gotIceCandidate = function(event){
		if(event.candidate){
			signalData["ice"].push(event.candidate);
			document.getElementById("desc").value=JSON.stringify(signalData);
		}
	},

	addIceCandidates = function(canArr){
		for(var i in canArr){
			peerConnection.addIceCandidate(new RTCIceCandidate(canArr[i]));
		}
	},

	handleError = function(err){
		console.log("Error occured "+err);
	},

	closeCall = function(){
		peerConnection.close();
		//peerConnection=null;

		txtBox.popover('hide');
		txtBox.val('');
		localVideo.pause();
		remoteVideo.pause();
		localStream = null;
		$(localVideo).hide();
		showModal();
	},

	showModal = function(){
		$("#textModal").modal('show');
	},

	hideModal = function(){
		$("#textModal").modal('hide');
	},

	onConnectionStatusChange = function (event) {
	    switch (peerConnection.iceConnectionState) {
	        case 'checking':
	            console.log('Connecting to peer...');
	            break;
	        case 'connected': // on caller side
	            console.log('Connection established.');
	            $('#textModal').modal('hide');
	            $("#localVideo").show();
	            $("#hangupdiv").show();
	            break;
	        case 'disconnected':
	            console.log('Disconnected.');
	            closeCall();
	            break;
	        case 'failed':
	        	console.log('Failed.');
	            break;
	        case 'closed':
	            console.log('Connection closed.');
	            peerConnection = null;
	            $("#joinBtn").off("click").on("click",joinSession);
	            break;
	    }
	},

	gotRemoteStream = function(event){
		console.log("Received remote stream");
		remoteVideo.srcObject = event.stream;
	},
	copyText = function() {
		var copyText = document.getElementById("desc");
		copyText.select();
		copyText.setSelectionRange(0, 99999);
		document.execCommand("copy");
	},
	copyText2 = function() {
		var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($("#desc").val()).select();
    document.execCommand("copy");
		$temp.remove();
	},
	attachEvents = function(){
		$("#callBtn").on("click",initiateOffer);
		$("#joinBtn").on("click",joinSession);
		$("#hangBtn").on("click",closeCall);
		$("#btnCpy").on("click", copyText);
		$("#btnCpyJumb").on("click", copyText2);
	},

	init = function(){
		getPeerConnection();
		attachEvents();
		showModal();
	}

	return {
		init:init
	};

})();

$(document).ready(function(){

	App.init();

});

<commit_msg>Fixed for firefox<commit_after>var App = (function(){
	var servers = {"iceServers" :[{
	    url: 'stun:stun.l.google.com:19302'
	}]},

	signalData = {"desc":null,"ice":[]},
	peerConnection,
	localVideo = document.getElementById("localVideo"),
	localStream = null,
	remoteVideo = document.getElementById("remoteVideo"),
	txtBox      = $("#desc"),
	cpyRow      = $("#rowCpy"),
	cpyJumbRow  = $("#rowCpyJumb"),
  cpyJumBtn   = $("#btnCpyJumb")
	getUserMedia = navigator.mediaDevices.getUserMedia.bind(navigator);

	var

	getPeerConnection = function(){
		peerConnection = new RTCPeerConnection(servers);
		peerConnection.onaddstream = gotRemoteStream;
		peerConnection.onicecandidate = gotIceCandidate;
		peerConnection.oniceconnectionstatechange = onConnectionStatusChange;
		peerConnection.onsignalingstatechange = (event) => {console.log("Signaling change"); console.log(event);}
	},

	getMediaStream = function(callback){
		getUserMedia(
			{	audio:true,
				video:true
			},function(stream){
				localStream = stream;
				callback(stream);
			},function(error){

		      console.log("getUserMedia error: ", error);

		    });
	},

	joinSession = function(){
		if(peerConnection == null){
			getPeerConnection();
		}

		var sigdata = JSON.parse(txtBox.val().trim());
		if(sigdata["desc"] == ""){
			alert("Please enter the offer");
			return;
		}
		getMediaStream(createAnswer);
	},

	createOffer = function(stream){
		localVideo.srcObject = stream;
  		peerConnection.addStream(stream);
  		peerConnection.createOffer(onConnection,handleError);
		txtBox.popover('show');
		cpyRow.show();
	},

	initiateOffer = function(){
		if(peerConnection == null){
			getPeerConnection();
		}
		getMediaStream(createOffer);
	},

	onConnection = function(desc){
		console.log("Description is "+desc.sdp);
		peerConnection.setLocalDescription(desc);
		signalData["desc"] = desc;
		//Change the event on click of Join Button to Complete Handshake on Initiator Side
		$("#joinBtn").off("click").on("click",completeHandshake);

	},

	createAnswer = function(stream){
		var sigdata = JSON.parse(txtBox.val().trim());
		localVideo.srcObject = stream;
		peerConnection.addStream(stream);
		peerConnection.setRemoteDescription(new RTCSessionDescription(sigdata["desc"]),function(){console.log("Success");},handleError);
		peerConnection.createAnswer(sendReply,handleError);
		addIceCandidates(sigdata["ice"]);
		txtBox.popover("show");
	},

	completeHandshake = function(){

		console.log("Inside complete handshake");
		var sigdata = document.getElementById("desc").value.trim();
		sigdata = JSON.parse(sigdata)
		if(!sigdata["desc"]){
			alert("Please enter the answer");
			return;
		}
		peerConnection.setRemoteDescription(new RTCSessionDescription(sigdata["desc"]),function(){console.log("Success");},handleError);
		addIceCandidates(sigdata["ice"]);

	},

	sendReply = function(desc){
		peerConnection.setLocalDescription(desc);
		signalData["desc"] = desc;
		console.log(JSON.stringify(signalData));
		cpyJumbRow.show();
		cpyJumBtn.popover('show');
	},

	gotIceCandidate = function(event){
		if(event.candidate){
			signalData["ice"].push(event.candidate);
			document.getElementById("desc").value=JSON.stringify(signalData);
		}
	},

	addIceCandidates = function(canArr){
		for(var i in canArr){
			peerConnection.addIceCandidate(new RTCIceCandidate(canArr[i]));
		}
	},

	handleError = function(err){
		console.log("Error occured "+err);
	},

	closeCall = function(){
		peerConnection.close();
		//peerConnection=null;

		txtBox.popover('hide');
		txtBox.val('');
		localVideo.pause();
		remoteVideo.pause();
		localStream = null;
		$(localVideo).hide();
		showModal();
	},

	showModal = function(){
		$("#textModal").modal('show');
	},

	hideModal = function(){
		$("#textModal").modal('hide');
	},

	onConnectionStatusChange = function (event) {
	    switch (peerConnection.iceConnectionState) {
	        case 'checking':
	            console.log('Connecting to peer...');
	            break;
	        case 'connected': // on caller side
	            console.log('Connection established.');
	            $('#textModal').modal('hide');
	            $("#localVideo").show();
	            $("#hangupdiv").show();
	            break;
	        case 'disconnected':
	            console.log('Disconnected.');
	            closeCall();
	            break;
	        case 'failed':
	        	console.log('Failed.');
	            break;
	        case 'closed':
	            console.log('Connection closed.');
	            peerConnection = null;
	            $("#joinBtn").off("click").on("click",joinSession);
	            break;
	    }
	},

	gotRemoteStream = function(event){
		console.log("Received remote stream");
		remoteVideo.srcObject = event.stream;
	},
	copyText = function() {
		var copyText = document.getElementById("desc");
		copyText.select();
		copyText.setSelectionRange(0, 99999);
		document.execCommand("copy");
	},
	copyText2 = function() {
		var $temp = $("<input>");
    $("body").append($temp);
    $temp.val($("#desc").val()).select();
    document.execCommand("copy");
		$temp.remove();
	},
	attachEvents = function(){
		$("#callBtn").on("click",initiateOffer);
		$("#joinBtn").on("click",joinSession);
		$("#hangBtn").on("click",closeCall);
		$("#btnCpy").on("click", copyText);
		$("#btnCpyJumb").on("click", copyText2);
	},

	init = function(){
		getPeerConnection();
		attachEvents();
		showModal();
	}

	return {
		init:init
	};

})();

$(document).ready(function(){

	App.init();

});

<|endoftext|>


<commit_before>var dataObj = [
    {
        busNumber: '1',
        description: 'Маршрут №1 пр-т Добровольского/ул. Паустовского',
        toRiviera: '8:30,9:25,9:55,10:25,10:55,11:25,11:55,12:25,12:55,13:25,13:55,14:25,14:55,15:25,15:55,16:25,16:55,17:25,17:55,18:25,18:55,19:25,19:55,20:25,20:55,21:25,21:55'.split(','),
        fromRiviera: '9:25,9:55,10:25,10:55,11:25,11:55,12:25,12:55,13:25,13:55,14:25,14:55,15:25,15:55,16:25,16:55,17:25,17:55,18:25,18:55,19:25,19:55,20:25,20:55,21:25,21:55,22:25'.split(',')
    },
    {
        busNumber: '2',
        description: 'Маршрут №2 ул. Ж. Кюри/Бочарова',
        toRiviera: '9:30,10:00,10:30,11:00,11:30,12:00,12:30,13:00,13:30,14:00,14:30,15:00,15:30,16:00,16:30,17:00,17:30,18:00,18:30,19:00,19:30,20:00,20:30,12:00,21:30,22:00'.split(','),
        fromRiviera: '10:00,10:30,11:00,11:30,12:00,12:30,13:00,13:30,14:00,14:30,15:00,15:30,16:00,16:30,17:00,17:30,18:00,18:30,19:00,19:30,20:00,20:30,21:00,21:30,22:00,22:30'.split(',')
    },
    {
        busNumber: '4',
        description: 'Маршрут №4 Ж. Кюри/Заболотного (Курская)',
        toRiviera: '8:20,9:20,10:20,11:20,12:20,13:20,14:20,15:20,16:20,17:20,18:20,19:20,20:20,21:20,22:20'.split(','),
        fromRiviera: '9:00,10:00,11:00,12:00,13:00,14:00,15:00,16:00,17:00,18:00,19:00,20:00,21:00,22:00,23:00'.split(',')
    },
    {
        busNumber: '5',
        description: 'Маршрут №5 ул. Кишиневская (пр-т. Добровольского)',
        toRiviera: '8:15,9:15,10:15,11:15,12:15,13:15,14:15,15:15,16:15,17:15,18:15,19:15,20:15,21:15,22:15'.split(','),
        fromRiviera: '8:45,9:45,10:45,11:45,12:45,13:45,14:45,15:45,16:45,17:45,18:45,19:45,20:45,21:45,23:00'.split(',')
    },
    {
        busNumber: '6',
        description: 'Маршрут №6 ТЦ "Семья"',
        toRiviera: '8:20,8:50,9:20,9:50,10:20,10:50,11:20,11:50,12:20,12:50,13:20,13:50,14:20,14:50,15:20,15:50,16:20,16:50,17:20,17:50,18:20,18:50,19:20,19:50,20:20,20:50,21:20,21:50,22:20'.split(','),
        fromRiviera: '8:50,9:20,9:50,10:20,10:50,11:20,11:50,12:20,12:50,13:20,13:50,14:20,14:50,15:20,15:50,16:20,16:50,17:20,17:50,18:20,18:50,19:20,19:50,20:20,20:50,21:20,21:50,22:20,22:50'.split(',')
    },
    {
        busNumber: '7',
        description: 'Маршрут №7 ул. Паустовского (Днепр.дор.)',
        toRiviera: '8:10,9:10,10:10,11:10,12:10,13:10,14:10,15:10,16:10,17:10,18:10,19:10,20:10,21:10,22:10'.split(','),
        fromRiviera: '8:40,9:40,10:40,11:40,12:40,13:40,14:40,15:40,16:40,17:40,18:40,19:40,20:40,21:40,22:40'.split(',')
    }
];

function renderSchedule() {
    var settings = getSettings();
    var now = new Date();
    var year = now.getFullYear(),
        month = now.getMonth(),
        day = now.getDate();
    var toRiviera = [];
    var fromRiviera = [];
    dataObj.forEach(function (item) {
        if(settings.showBuses.indexOf(item.busNumber) >= 0){
            item.toRiviera.forEach(function(time){
                var timeArr = time.split(':');
                toRiviera.push({busNumber: item.busNumber, time: new Date(year, month, day, timeArr[0], timeArr[1])});
            });

            item.fromRiviera.forEach(function(time){
                var timeArr = time.split(':');
                fromRiviera.push({busNumber: item.busNumber, time: new Date(year, month, day, timeArr[0], timeArr[1])});
            });
        }
    });

    toRiviera.sort(function(a, b){
        return a.time - b.time;
    });
    toRiviera = toRiviera.filter(function(item){
        if(item.time >= now) return true;
        else return false;
    });

    fromRiviera.sort(function(a, b){
        return a.time - b.time;
    });
    fromRiviera = fromRiviera.filter(function(item){
        if(item.time >= now) return true;
        else return false;
    });

    var tableContent = '';
    for(var i = 0; i < Math.max(toRiviera.length, fromRiviera.length); ++i){
        tableContent += '
';
        if(toRiviera[i]){
            tableContent += '
'+toRiviera[i].busNumber+' - '+toRiviera[i].time.getHours()+':'+addPrevZero(toRiviera[i].time.getMinutes())+'
';
        }else{
            tableContent += '

';
        }
        if(fromRiviera[i]){
            tableContent += '
'+fromRiviera[i].busNumber+' - '+fromRiviera[i].time.getHours()+':'+addPrevZero(fromRiviera[i].time.getMinutes())+'
';
        }else{
            tableContent += '

';
        }
        tableContent += '
';
    }
    document.querySelector('#schedule .body').innerHTML = tableContent;
}

function addPrevZero(val) {
    return (val.toString().length === 1) ? '0' + val : val;
}

function renderRecordsCount() {
    var oneRecordHeight = 25;
    document.querySelector('#schedule .body').style.height = oneRecordHeight * getSettings().recordsCount + 'px';
}

function renderDescription() {
    var settings = getSettings();
    var descriptionsList = '';
    dataObj.forEach(function (item) {
        if(settings.showBuses.indexOf(item.busNumber) >= 0){
            descriptionsList += '
'+item.description+'
';
        }
    });
    document.getElementById('description').innerHTML = descriptionsList;
}

function getDefaultSettings(){
    return {
        recordsCount: 8,
        showBuses: ['1', '2', '4', '5', '6', '7']
    };
};

function getSettings(){
    if(localStorage){
        if(localStorage.getItem('rivieraBusSchedule')){
            return JSON.parse(localStorage.getItem('rivieraBusSchedule'));
        }else{
            localStorage.setItem('rivieraBusSchedule', JSON.stringify(getDefaultSettings()));
            return getDefaultSettings();
        }
    }else{
        return getDefaultSettings();
    }
}

function saveAndApplySettings(){
    var settings = getSettings();

    // задаем количество отображаемых записей
    var recordsCount = parseInt(document.querySelector('#settings--records-count input').value);
    if(recordsCount < 2 || recordsCount > 15 || isNaN(recordsCount)) recordsCount = getDefaultSettings().recordsCount;

    settings.recordsCount = recordsCount;

    // задаем отображаемые маршруты
    var routesDOMItemsList = document.querySelectorAll('#settings--routes-list input[type="checkbox"]');
    var showBuses = [];
    Array.prototype.forEach.call(routesDOMItemsList, function(item){
        if(item.checked){
            showBuses.push(item.value);
        }
    });
    settings.showBuses = showBuses;

    // сохраняем данные
    localStorage.setItem('rivieraBusSchedule', JSON.stringify(settings));

    // отрисовываем изменения
    renderRecordsCount();
    renderSchedule();
    renderDescription()
}

function showSettingsPage(){
    // получаем настройки
    var settings = getSettings();

    // задаем количество отображаемых записей
    document.querySelector('#settings--records-count input').value = settings.recordsCount;

    // задаем отображаемые маршруты
    var routesList = '';
    dataObj.forEach(function (item) {
        var checked = settings.showBuses.indexOf(item.busNumber) >= 0 ? 'checked' : '';
        routesList += '<input '+checked+' type="checkbox" value="'+item.busNumber+'">'+item.description+'';
    });
    document.getElementById('settings--routes-list').innerHTML = routesList;

    //показываем страницу настроек
    document.getElementById('settings').classList.toggle('active');
}

function hideSettingsPage() {
    saveAndApplySettings();
    window.scrollTo(0, 0);
    document.getElementById('settings').classList.toggle('active');
}

function init(){
    renderSchedule();
    setInterval(renderSchedule, 120000);
    renderRecordsCount();
    renderDescription()
    if(localStorage){
        document.getElementById('open-settings').addEventListener('click', showSettingsPage);
        document.getElementById('close-settings').addEventListener('click', hideSettingsPage);
    }else{
        // при отсутствии localStorage убираем кнопку с настройками. все равно хранить их будет негде.
        document.getElementById('open-settings').style.display = 'none';
    }
}

document.addEventListener("DOMContentLoaded", init);
<commit_msg>code optimized, new routes added<commit_after>(function () {
    var dataObj = [
        {
            busNumber: '1',
            description: 'Маршрут №1 пр-т Добровольского/ул. Паустовского',
            toRiviera: '8:30,8:55,9:25,9:55,10:25,10:55,11:25,11:55,12:25,12:55,13:25,13:55,14:25,14:55,15:25,15:55,16:25,16:55,17:25,17:55,18:25,18:55,19:25,19:55,20:25,20:55,21:25,21:55'.split(','),
            fromRiviera: '9:25,9:55,10:25,10:55,11:25,11:55,12:25,12:55,13:25,13:55,14:25,14:55,15:25,15:55,16:25,16:55,17:25,17:55,18:25,18:55,19:25,19:55,20:25,20:55,21:25,22:10,22:30'.split(',')
        },
        {
            busNumber: '2',
            description: 'Маршрут №2 ул. Ж. Кюри/Бочарова',
            toRiviera: '9:30,10:00,10:30,11:00,11:30,12:00,12:30,13:00,13:30,14:00,14:30,15:00,15:30,16:00,16:30,17:00,17:30,18:00,18:30,19:00,19:30,20:00,20:30,21:00,21:30,22:00'.split(','),
            fromRiviera: '10:00,10:30,11:00,11:30,12:00,12:30,13:00,13:30,14:00,14:30,15:00,15:30,16:00,16:30,17:00,17:30,18:00,18:30,19:00,19:30,20:00,20:30,21:00,21:30,22:00,22:30'.split(',')
        },
        {
            busNumber: '3',
            days: [1,2,3,4,5],
            description: 'Маршрут №3 мост Пересыпь (с Понедельника по Пятницу)',
            toRiviera: '9:00,11:00,13:00,15:00,17:00,19:00,21:00'.split(','),
            fromRiviera: '10:00,12:00,14:00,16:00,18:00,20:00,22:10'.split(',')
        },
        {
            busNumber: '4',
            description: 'Маршрут №4 Ж. Кюри/Заболотного (Курская)',
            toRiviera: '8:20,9:20,10:20,11:20,12:20,13:20,14:20,15:20,16:20,17:20,18:20,19:20,20:20,21:20,22:20'.split(','),
            fromRiviera: '9:00,10:00,11:00,12:00,13:00,14:00,15:00,16:00,17:00,18:00,19:00,20:00,21:00,22:00,23:00'.split(',')
        },
        {
            busNumber: '5',
            description: 'Маршрут №5 ул. Кишиневская (пр-т. Добровольского)',
            toRiviera: '8:15,9:15,10:15,11:15,12:15,13:15,14:15,15:15,16:15,17:15,18:15,19:15,20:15,21:15,22:15'.split(','),
            fromRiviera: '8:45,9:45,10:45,11:45,12:45,13:45,14:45,15:45,16:45,17:45,18:45,19:45,20:45,21:45,23:00'.split(',')
        },
        {
            busNumber: '6',
            description: 'Маршрут №6 ТЦ "Семья"',
            toRiviera: '8:20,8:50,9:20,9:50,10:20,10:50,11:20,11:50,12:20,12:50,13:20,13:50,14:20,14:50,15:20,15:50,16:20,16:50,17:20,17:50,18:20,18:50,19:20,19:50,20:20,20:50,21:20,21:50,22:20'.split(','),
            fromRiviera: '8:50,9:20,9:50,10:20,10:50,11:20,11:50,12:20,12:50,13:20,13:50,14:20,14:50,15:20,15:50,16:20,16:50,17:20,17:50,18:20,18:50,19:20,19:50,20:20,20:50,21:20,21:50,22:20,22:50'.split(',')
        },
        {
            busNumber: '7',
            description: 'Маршрут №7 ул. Паустовского (Днепр.дор.)',
            toRiviera: '8:10,9:10,10:10,11:10,12:10,13:10,14:10,15:10,16:10,17:10,18:10,19:10,20:10,21:10,22:10'.split(','),
            fromRiviera: '8:40,9:40,10:40,11:40,12:40,13:40,14:40,15:40,16:40,17:40,18:40,19:40,20:40,21:40,22:40'.split(',')
        },
        {
            busNumber: '8',
            days: [6,0],
            description: 'Маршрут №8 Пантелеймоновская 58 (Суббота, Воскресенье)',
            toRiviera: '9:00,10:00,11:00,12:00,13:00,14:00,15:00,16:00,17:00,18:00,19:00,20:00'.split(','),
            fromRiviera: '10:00,11:00,12:00,13:00,14:00,15:00,16:00,17:00,18:00,19:00,20:00,21:00'.split(',')
        }
    ];
    var schedule, settings;
    function setSchedule() {
        var now = new Date();
        var year = now.getFullYear(),
            month = now.getMonth(),
            day = now.getDate(),
            weekDay = now.getDay();
        var toRiviera = [];
        var fromRiviera = [];
        dataObj.forEach(function (item) {
            if(item.days && item.days.indexOf(weekDay) === -1) return;
            item.toRiviera.forEach(function(time){
                var timeArr = time.split(':');
                toRiviera.push({busNumber: item.busNumber, time: new Date(year, month, day, timeArr[0], timeArr[1])});
            });
            item.fromRiviera.forEach(function(time){
                var timeArr = time.split(':');
                fromRiviera.push({busNumber: item.busNumber, time: new Date(year, month, day, timeArr[0], timeArr[1])});
            });
        });
        toRiviera.sort(function(a, b){
            return a.time - b.time;
        });
        fromRiviera.sort(function(a, b){
            return a.time - b.time;
        });
        schedule = {
            to: toRiviera,
            from: fromRiviera
        };
    }

    function renderSchedule() {
        var now = new Date();
        var toRiviera = schedule.to.filter(function(item){
            return item.time >= now && settings.showBuses.indexOf(item.busNumber) >= 0;
        });
        var fromRiviera = schedule.from.filter(function(item){
            return item.time >= now && settings.showBuses.indexOf(item.busNumber) >= 0;
        });

        var scheduleContent = '';
        for(var i = 0; i < Math.max(toRiviera.length, fromRiviera.length); ++i){
            scheduleContent += '
';
            if(toRiviera[i]){
                scheduleContent += '
'+toRiviera[i].busNumber+' - '+toRiviera[i].time.getHours()+':'+addPrevZero(toRiviera[i].time.getMinutes())+'
';
            }else{
                scheduleContent += '

';
            }
            if(fromRiviera[i]){
                scheduleContent += '
'+fromRiviera[i].busNumber+' - '+fromRiviera[i].time.getHours()+':'+addPrevZero(fromRiviera[i].time.getMinutes())+'
';
            }else{
                scheduleContent += '

';
            }
            scheduleContent += '
';
        }
        document.querySelector('#schedule .body').innerHTML = scheduleContent;
    }

    function addPrevZero(val) {
        return (val.toString().length === 1) ? '0' + val : val;
    }

    function setScheduleElementHeight() {
        var oneRecordHeight = 25;
        document.querySelector('#schedule .body').style.height = oneRecordHeight * settings.recordsCount + 'px';
    }

    function renderDescription() {
        document.getElementById('description').innerHTML = dataObj.reduce(function (html, item) {
            return (settings.showBuses.indexOf(item.busNumber) >= 0) ? html += '
'+item.description+'
' : html;
        }, '');
    }

    function getDefaultSettings(){
        return {
            recordsCount: 8,
            showBuses: ['1', '2', '3', '4', '5', '6', '7', '8']
        };
    }

    function loadSettings(){
        if(localStorage){
            if(localStorage.getItem('rivieraBusSchedule')){
                settings = JSON.parse(localStorage.getItem('rivieraBusSchedule'));
            }else{
                settings = getDefaultSettings();
                localStorage.setItem('rivieraBusSchedule', JSON.stringify(settings));
            }
        }else{
            settings = getDefaultSettings();
        }
    }

    function saveAndApplySettings(){
        // задаем количество отображаемых записей
        var recordsCount = parseInt(document.querySelector('#settings--records-count input').value);
        if(recordsCount >= 2 && recordsCount <= 15) settings.recordsCount = recordsCount;

        // задаем отображаемые маршруты
        var routesDOMItemsList = document.querySelectorAll('#settings--routes-list input[type="checkbox"]:checked');
        settings.showBuses = Array.prototype.map.call(routesDOMItemsList, function(item){
            return item.value;
        });

        // сохраняем данные
        localStorage.setItem('rivieraBusSchedule', JSON.stringify(settings));

        // отрисовываем изменения
        setScheduleElementHeight();
        renderSchedule();
        renderDescription()
    }

    function showSettingsPage(){
        document.querySelector('#settings--records-count input').value = settings.recordsCount;
        document.getElementById('settings--routes-list').innerHTML = dataObj.reduce(function (html, item) {
            return html + '<input '+ (settings.showBuses.indexOf(item.busNumber) >= 0 ? 'checked' : '') +' type="checkbox" value="'+item.busNumber+'">'+item.description+'';
        }, '');
        document.getElementById('settings').classList.toggle('active');
    }

    function hideSettingsPage() {
        saveAndApplySettings();
        window.scrollTo(0, 0);
        document.getElementById('settings').classList.toggle('active');
    }

    function init(){
        loadSettings();
        setSchedule();
        setScheduleElementHeight();
        renderSchedule();
        renderDescription();
        if(localStorage){
            document.getElementById('open-settings').addEventListener('click', showSettingsPage);
            document.getElementById('close-settings').addEventListener('click', hideSettingsPage);
        }else{
            // при отсутствии localStorage убираем кнопку с настройками. все равно хранить их будет негде.
            document.getElementById('open-settings').style.display = 'none';
        }
        setInterval(renderSchedule, 120000);
    }
    document.addEventListener("DOMContentLoaded", init);
})();<|endoftext|>


<commit_before>//Initialize variables
var zipCodeToSearch;
var searchTermToSearch;

$('#submit').on('click', function() {

  //obtain zip code
  zipCodeToSearch = $('#zipCode').val().trim();
  //Verify the zip code is a 5 digit numeric value before proceeding
  if (isNaN(zipCodeToSearch) == false && zipCodeToSearch > 0) {

    //obtain search term
    searchTermToSearch = $('#searchTerm').val().trim();

    //call seatgeek API with necessary info
    displaySportInfo(searchTermToSearch,zipCodeToSearch);

    //call betting odds API with necessary info
    getSportsObject(searchTermToSearch);

    //update page with results from JSON odds API
    $('#bettingOdds').html("Search JSONOdds for " + searchTermToSearch);

    $.get('api/jsonOdds.php?action=' + searchTermToSearch, function(data) {
      $('#bettingOdds').html(data);
    });
  }
//
});

function checkZipCode(zipCodeToSearch){
  if (zipCodeToSearch.length == 5) {
    if (parseInt(zipCodeToSearch) != NaN) {
      console.log("is a 5 digit number");
      return false;
    }
  } else {
    console.log("enter a valid zip code");
  }

}<commit_msg>merging<commit_after>//Initialize variables
var zipCodeToSearch;
var searchTermToSearch;

$('#submit').on('click', function() {

  //obtain zip code
  zipCodeToSearch = $('#zipCode').val().trim();
  //Verify the zip code is a 5 digit numeric value before proceeding
  if (isNaN(zipCodeToSearch) == false && zipCodeToSearch > 0) {

    //obtain search term
    searchTermToSearch = $('#searchTerm').val().trim();

    //call seatgeek API with necessary info
    displaySportInfo(searchTermToSearch,zipCodeToSearch);

    //call betting odds API with necessary info
    getSportsObject(searchTermToSearch);

    //update page with results from JSON odds API
    $('#bettingOdds').html("Search JSONOdds for " + searchTermToSearch);

    $.get('api/jsonOdds.php?action=' + searchTermToSearch, function(data) {
      $('#bettingOdds').html(data);
    });
  }

  // changeBackground(searchTermToSearch);
//
});

function checkZipCode(zipCodeToSearch){
  if (zipCodeToSearch.length == 5) {
    if (parseInt(zipCodeToSearch) != NaN) {
      console.log("is a 5 digit number");
      return false;
    }
  } else {
    console.log("enter a valid zip code");
  }

}

// function changeBackground(sport) {
//   .intro {
//   background: url(../img/soccer.jpg) no-repeat bottom center scroll;
// }<|endoftext|>