<commit_before>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Modernizr */

function l(data) {
  'use strict';
  console.log(data);
}

var
	winHeight = $(window).height();

jQuery(document).ready(function () {
  'use strict';
  l('Hola Globie');

  // SPLASH
  if ($('#splash').length) {
  	$('.splash-margin').css('margin-top', winHeight);
  	$('#main-container').removeClass('u-hidden');
  }

  // PACKERY
  if ( $('.js-packery-container').length ) {
    $('.js-packery-container').imagesLoaded( function() {
      $('.js-packery-container').packery({
        itemSelector: '.js-packery-item',
        columnWidth: 1,
        gutter: 0,
        transitionDuration: '0s',
      }).css({
        'opacity': 1
      });
    });
  }

  //RESIZE
  $(window).on('resize', function() {
  	winHeight = $(window).height();

		if ($('#splash').length) {
	  	$('.splash-margin').css('margin-top', winHeight);
	  }
  })

});<commit_msg>add slider sizing and click events<commit_after>/* jshint browser: true, devel: true, indent: 2, curly: true, eqeqeq: true, futurehostile: true, latedef: true, undef: true, unused: true */
/* global $, jQuery, document, Modernizr */

function l(data) {
  'use strict';
  console.log(data);
}

var
	winHeight = $(window).height(),
  headerHeight = $('#header').outerHeight(),
  slideMargin = parseInt( $('#header').css('padding-top'), 10 ),
  slideIndex;

jQuery(document).ready(function () {
  'use strict';
  l('Hola Globie');

  // SPLASH
  if ($('#splash').length) {
  	$('.splash-margin').css('margin-top', winHeight);
  	$('#main-container').removeClass('u-hidden');
  }

  // PACKERY
  if ( $('.js-packery-container').length ) {
    $('.js-packery-container').imagesLoaded( function() {
      $('.js-packery-container').packery({
        itemSelector: '.js-packery-item',
        columnWidth: 1,
        gutter: 0,
        transitionDuration: '0s',
      }).css({
        'opacity': 1
      });
    });
  }

  //SLIDER
  var sliderHeight = winHeight - headerHeight - slideMargin;
  l(sliderHeight);
  $('.slider-img').css('height', sliderHeight );

  $('.js-single-packery-item').on({
    click: function() {
      if ($('.slider-content').hasClass('slider-hidden')) {
        var slideIndex = $(this).attr('data-index');
        $('.cycle-slideshow').cycle('goto', slideIndex);
        $('.packery-content').animate({'opacity' : 0}, 300, function() {
          $('.packery-content').css('display','none');
          $('.slider-content').animate({'opacity' : 1}, 300).removeClass('slider-hidden');
          $('#view-toggle').removeClass('u-hidden');
        });
      }
    }
  });

  $('#view-toggle').on({
    click: function() {
      $('.slider-content').animate({'opacity' : 0}, 300, function() {
        $('.packery-content').css('display','block').animate({'opacity' : 1}, 300);
        $('.slider-content').addClass('slider-hidden');
        $('#view-toggle').addClass('u-hidden');
      });
    }
  });

  //RESIZE
  $(window).on('resize', function() {
  	winHeight = $(window).height();

		if ($('#splash').length) {
	  	$('.splash-margin').css('margin-top', winHeight);
	  }
  })

});<|endoftext|>


<commit_before>var elements = document.getElementsByTagName('script')

Array.prototype.forEach.call(elements, function(element) {
  if (element.type.indexOf('math/tex') != -1) {
     // Extract math markdown
     var textToRender = element.innerText || element.textContent;

     // Create span for KaTeX
     var katexElement = document.createElement('span');

     // Support inline and display math
     if (element.type.indexOf('mode=display') != -1){
       katexElement.className += "math-display";
       textToRender = '\\displaystyle {' + textToRender + '}';
     } else {
       katexElement.className += "math-inline";
     }

     katex.render(textToRender, katexElement);
     element.parentNode.insertBefore(katexElement, element);
  }
});

var blocmetrics = {};
blocmetrics.report = function(eventName) {
   var event = {event: { name: eventName }};
   var request = new XMLHttpRequest();
   request.open("POST", "http://blocmetrics-boltz.herokuapp.com/api/events", true);
   request.setRequestHeader('Content-Type', 'application/json');
   request.send(JSON.stringify(event));
};

$(document).ready(function() {
  blocmetrics.report("page load");
});<commit_msg>Correct blocmetrics route to include v1<commit_after>var elements = document.getElementsByTagName('script')

Array.prototype.forEach.call(elements, function(element) {
  if (element.type.indexOf('math/tex') != -1) {
     // Extract math markdown
     var textToRender = element.innerText || element.textContent;

     // Create span for KaTeX
     var katexElement = document.createElement('span');

     // Support inline and display math
     if (element.type.indexOf('mode=display') != -1){
       katexElement.className += "math-display";
       textToRender = '\\displaystyle {' + textToRender + '}';
     } else {
       katexElement.className += "math-inline";
     }

     katex.render(textToRender, katexElement);
     element.parentNode.insertBefore(katexElement, element);
  }
});

var blocmetrics = {};
blocmetrics.report = function(eventName) {
   var event = {event: { name: eventName }};
   var request = new XMLHttpRequest();
   request.open("POST", "http://blocmetrics-boltz.herokuapp.com/api/v1/events", true);
   request.setRequestHeader('Content-Type', 'application/json');
   request.send(JSON.stringify(event));
};

$(document).ready(function() {
  blocmetrics.report("page load");
});<|endoftext|>


<commit_before>var News = {
  newsMinLimit: 1,
  newsMaxLimit: 15,
  unreadMaxCount: 3, // 0-indexed like the list it its counting, actually +1
  msgNewsLimit: 'Nyhetsantall må være et tall mellom '+this.newsMinLimit+' og '+this.newsMaxLimit,
  msgConnectionError: 'Frakoblet fra feeden til ',
  msgUnsupportedFeed: 'Feeden støttes ikke',
  msgCallbackRequired: 'Callback er påkrevd, legg resultatene inn i DOMen',

  debug: 1,

  // Get is called by background.html periodically, with News.unreadCount as
  // callback. Fetchfeed is also called by popup.html when requested, but
  // without the callback as we already know the amount of unread posts.
  get: function(affiliationObject, limit, callback) {
    if (affiliationObject === undefined) {
      if (this.debug) console.log('ERROR:', this.msgUnsupportedFeed);
      callback(this.msgUnsupportedFeed);
      return;
    }
    if (!isNumber(limit) || (limit < 1 && 20 < limit)) {
      if (this.debug) console.log('ERROR:', this.msgNewsLimit);
      callback(this.msgNewsLimit);
      return;
    }
    if (callback == undefined) {
      console.log('ERROR:', this.msgCallbackRequired);
      callback(this.msgCallbackRequired);
      return;
    }

    var rssUrl = affiliationObject.feed;

    var self = this;
    Ajaxer.getXml({
      url: rssUrl,
      success: function(xml) {
        self.parseFeed(xml, affiliationObject, limit, callback);
      },
      error: function(jqXHR, text, err) {
        if (self.debug) console.log('ERROR:', self.msgConnectionError, affiliationObject.name);
        callback(self.msgConnectionError, affiliationObject.name);
      },
    });
  },

  // Need to know about the news feeds used in Online Notifier:
  // These RSS fields are always used:
  // - title
  // - link
  // - desc - often wrapped in <![CDATA[content here]]>
  // These RSS fields are sometimes used:
  // - guid - usually the same as link
  // - pubDate
  // - category
  // - dc:creator - author name or username
  // - enclosure - may contain an image as an XML attribute: url="news_post_image.jpg"
  // - source
  // In Atom feeds, these are the usual fields:
  // - id - a useless ID
  // - published - the publishing date, must be parsed
  // - updated - the updated date, must be parsed
  // - title
  // - content - is the full entry as HTML
  // - link[rel="self"] - is this entry in XML format, useless
  // - link[rel="alternate"] - is the entry as text/html, good!
  // - author -> name
  parseFeed: function(xml, affiliationObject, limit, callback) {
    var posts = [];
    var self = this;
    var count = 0;
    // Add each item from RSS feed
    if ($(xml).find('item').length != 0) {
      $(xml).find('item').each( function() {
        if (count++ < limit) {
          var item = self.parseRssItem(this, affiliationObject);
          item = self.postProcess(item);
          posts.push(item);
        }
      });
    }
    // Add each item from Atom feed
    else if ($(xml).find('entry').length != 0) {
      $(xml).find('entry').each( function() {
        if (count++ < limit) {
          var entry = self.parseAtomEntry(this, affiliationObject);
          entry = self.postProcess(entry);
          posts.push(entry);
        }
      });
    }
    else {
      if (this.debug) console.log('ERROR: Unknown feed type, neither RSS nor Atom');
    }
    callback(posts);
  },

  parseRssItem: function(item, affiliationObject) {
    var post = {};

    // - "If I've seen RSS feeds with multiple title fields in one item? Why, yes, yes I have."

    // The popular fields
    post.title = $(item).find("title").filter(':first').text();
    post.link = $(item).find("link").filter(':first').text();
    post.description = $(item).find("description").filter(':first').text();
    // Less used fields
    post.creator = $(item).find("dc:creator").filter(':first').text();
    post.date = $(item).find("pubDate").filter(':first').text().substr(5, 11);
    // Locally stored
    post.image = affiliationObject.placeholder;
    // Tag the posts with the key and name of the feed they came from
    post.feedKey = affiliationObject.key;
    post.feedName = affiliationObject.name;

    // Check for image in rarely used tags <enclosure> and <bilde>
    try {
      // Universitetsavisa does this little trick to get images in their feed
      var enclosure = $(item).find('enclosure').filter(':first');
      if (enclosure.length != 0) {
        post.image = enclosure['0'].attributes.url.textContent;
      }
      // Gemini uses this rather blunt hack to put images in their feed
      var bilde = $(item).find('bilde');
      if (bilde.length != 0) {
        post.image = bilde['0'].textContent;
      }
    }
    catch (err) {
      // Do nothing, we we're just checking, move along quitely
    }

    // In case browser does not grok tags with colons, stupid browser
    if (post.creator == '') {
      var tag = ("dc\\:creator").replace( /.*(\:)(.*)/, "$2" );
      $(item).find(tag).each(function(){
        post.creator = $(this).text().trim();
      });
    }

    return post;
  },

  parseAtomEntry: function(entry, affiliationObject) {
    var post = {};

    // The popular fields
    post.title = $(entry).find("title").filter(':first').text();
    post.link = $(entry).find("link[rel='alternate'][type='text/html']").filter(':first').attr('href');
    post.description = $(entry).find("content").filter(':first').text();
    post.creator = $(entry).find("author name").filter(':first').text();
    post.date = $(entry).find("published").filter(':first').text().substr(5, 11);

    // Locally stored
    post.image = affiliationObject.placeholder;
    // Tag the posts with the key and name of the feed they came from
    post.feedKey = affiliationObject.key;
    post.feedName = affiliationObject.name;

    // Extract image from content HTML
    var image = $(entry).find('content').filter(':first').text();
    if (image != undefined) {
      image = image.match(/src="(http:\/\/[a-zA-Z0-9.\/\-_]+)"/);
      if (image != null) {
        post.image = image[1];
      }
    }

    // Empty title field?
    if (post.title.trim() == '')
      post.title = 'Uten tittel';

    // Parse date field
    post.date = new Date(post.date);
    if (post.date != "Invalid Date")
      post.date = post.date.toDateString();
    else
      post.date = null;

    return post;
  },

  postProcess: function(post) {
    // Check for alternative links in description
    post.altLink = this.checkForAltLink(post.description);

    // Remove HTML from description
    post.description = post.description.replace(/<[^>]*>/g, ''); // Tags
    // post.description = post.description.replace(/&(#\d+|\w+);/g, ''); // Entities

    // Didn't find a creator, set the feedname as creator
    if (post.creator.length == 0) {
      post.creator = post.feedName;
    }
    // Capitalize creator name either way
    post.creator = post.creator.capitalize();
    // Abbreviate long creator names
    post.creator = this.abbreviateName(post.creator);

    // In case pubDate didn't exist, set to null
    if (post.date == '') {
      post.date = null;
    }

    // Trimming
    post.title = post.title.trim();
    post.description = post.description.trim();

    // Shorten 'bedriftspresentasjon' to 'bedpres'
    post.title = post.title.replace(/edrift(s)?presentasjon/gi, 'edpres');
    post.description = post.description.replace(/edrift(s)?presentasjon/gi, 'edpres');

    // title + description must not exceed 5 lines
    var line = 50; // conservative estimation
    var desclength = line * 3;
    // double line titles will shorten the description by 1 line
    if (line <= post.title.length)
      desclength -= line;
    // shorten description according to desclength
    if (desclength < post.description.length)
      post.description = post.description.substr(0, desclength) + '...';

    return post;
  },

  // News specific
  refreshAffiliationNewsList: function(items) {
    var freshList = [];
    items.forEach(function(item, index) {
      freshList.push(item.link);
    });
    localStorage.affiliationNewsList = JSON.stringify(freshList);
  },

  // Media specific
  refreshMediaNewsList: function(items) {
    var freshList = [];
    items.forEach(function(item, index) {
      freshList.push(item.link);
    });
    localStorage.mediaNewsList = JSON.stringify(freshList);
  },

  // News specific
  countAffiliationNewsAndNotify: function(items) {
    var unreadCount = 0;
    var maxNewsAmount = this.unreadMaxCount;
    if (items.length-1 < maxNewsAmount)
      maxNewsAmount = items.length-1;

    var newsList = JSON.parse(localStorage.newsList);

    // Count feed items
    var self = this;
    items.forEach(function(item, index) {

      var link = item.link;

      // Counting...
      if (newsList.indexOf(link) === -1) {
        unreadCount++;

        // Send a desktop notification about the first new item
        if (unreadCount == 1) {
          if (localStorage.lastNotified != link) {
            self.showNotification(item);
          }
        }
      }
      // All counted :)
      else {
        if (unreadCount == 0) {
          if (self.debug) console.log('no new posts');
          Browser.setBadgeText('');
        }
        else if (maxNewsAmount <= unreadCount) {
          if (self.debug) console.log(maxNewsAmount + '+ unread posts');
          Browser.setBadgeText(maxNewsAmount + '+');
        }
        else {
          if (self.debug) console.log('1-' + (maxNewsAmount - 1) + ' unread posts');
          Browser.setBadgeText(String(unreadCount));
        }
        localStorage.unreadCount = unreadCount;
        return;
      }

      // Stop counting if unread number is greater than maxNewsAmount
      if ((maxNewsAmount - 1) < index) { // Remember index is counting 0
        if (self.debug) console.log((maxNewsAmount + 1) + ' unread posts (stopped counting)');
        Browser.setBadgeText(String(maxNewsAmount + 1));
        localStorage.unreadCount = maxNewsAmount + 1;
        return;
      }
    });
  },

  showNotification: function(item) {
    if (localStorage.showNotifications == 'true') {
      // Remember this
      localStorage.lastNotified = item.link;
      // Get content
      localStorage.notificationTitle = item.title;
      localStorage.notificationLink = item.link;
      localStorage.notificationDescription = item.description;
      localStorage.notificationCreator = item.creator;
      localStorage.notificationImage = item.image;
      localStorage.notificationFeedKey = item.feedKey;
      localStorage.notificationFeedName = item.feedName;
      // Show desktop notification
      Browser.createNotification('notification.html');
    }
  },

  checkForAltLink: function(description) {
    // Looking for alternative link, find the first and best full link
    var altLink = description.match(/href="(http[^"]*)"/);
    if (altLink != null) {
      if (typeof altLink[1] == 'string') {
        return altLink[1];
      }
    }
    return null;
  },

  abbreviateName: function(oldName) {
    if (oldName != undefined) {
      // Abbreviate middle names if name is long
      if (18 < oldName.length) {
        var pieces = oldName.split(' ');
        if (2 < pieces.length) {
          // Add first name
          var newName = pieces[0];
          // Add one letter per middle name
          for (var i = 1; i < pieces.length - 1; i++)
            newName += ' ' + pieces[i].charAt(0).toUpperCase() + '.';
          // Add last name
          newName += ' ' + pieces[pieces.length-1];
          return newName;
        }
      }
    }
    else {
      if (this.debug) console.log('ERROR: cannot abbreviate an undefined name');
    }
    return oldName;
  },

}
<commit_msg>news: moving responsibility for ls.lastNotified to another function<commit_after>var News = {
  newsMinLimit: 1,
  newsMaxLimit: 15,
  unreadMaxCount: 3, // 0-indexed like the list it its counting, actually +1
  msgNewsLimit: 'Nyhetsantall må være et tall mellom '+this.newsMinLimit+' og '+this.newsMaxLimit,
  msgConnectionError: 'Frakoblet fra feeden til ',
  msgUnsupportedFeed: 'Feeden støttes ikke',
  msgCallbackRequired: 'Callback er påkrevd, legg resultatene inn i DOMen',

  debug: 1,

  // Get is called by background.html periodically, with News.unreadCount as
  // callback. Fetchfeed is also called by popup.html when requested, but
  // without the callback as we already know the amount of unread posts.
  get: function(affiliationObject, limit, callback) {
    if (affiliationObject === undefined) {
      if (this.debug) console.log('ERROR:', this.msgUnsupportedFeed);
      callback(this.msgUnsupportedFeed);
      return;
    }
    if (!isNumber(limit) || (limit < 1 && 20 < limit)) {
      if (this.debug) console.log('ERROR:', this.msgNewsLimit);
      callback(this.msgNewsLimit);
      return;
    }
    if (callback == undefined) {
      console.log('ERROR:', this.msgCallbackRequired);
      callback(this.msgCallbackRequired);
      return;
    }

    var rssUrl = affiliationObject.feed;

    var self = this;
    Ajaxer.getXml({
      url: rssUrl,
      success: function(xml) {
        self.parseFeed(xml, affiliationObject, limit, callback);
      },
      error: function(jqXHR, text, err) {
        if (self.debug) console.log('ERROR:', self.msgConnectionError, affiliationObject.name);
        callback(self.msgConnectionError, affiliationObject.name);
      },
    });
  },

  // Need to know about the news feeds used in Online Notifier:
  // These RSS fields are always used:
  // - title
  // - link
  // - desc - often wrapped in <![CDATA[content here]]>
  // These RSS fields are sometimes used:
  // - guid - usually the same as link
  // - pubDate
  // - category
  // - dc:creator - author name or username
  // - enclosure - may contain an image as an XML attribute: url="news_post_image.jpg"
  // - source
  // In Atom feeds, these are the usual fields:
  // - id - a useless ID
  // - published - the publishing date, must be parsed
  // - updated - the updated date, must be parsed
  // - title
  // - content - is the full entry as HTML
  // - link[rel="self"] - is this entry in XML format, useless
  // - link[rel="alternate"] - is the entry as text/html, good!
  // - author -> name
  parseFeed: function(xml, affiliationObject, limit, callback) {
    var posts = [];
    var self = this;
    var count = 0;
    // Add each item from RSS feed
    if ($(xml).find('item').length != 0) {
      $(xml).find('item').each( function() {
        if (count++ < limit) {
          var item = self.parseRssItem(this, affiliationObject);
          item = self.postProcess(item);
          posts.push(item);
        }
      });
    }
    // Add each item from Atom feed
    else if ($(xml).find('entry').length != 0) {
      $(xml).find('entry').each( function() {
        if (count++ < limit) {
          var entry = self.parseAtomEntry(this, affiliationObject);
          entry = self.postProcess(entry);
          posts.push(entry);
        }
      });
    }
    else {
      if (this.debug) console.log('ERROR: Unknown feed type, neither RSS nor Atom');
    }
    callback(posts);
  },

  parseRssItem: function(item, affiliationObject) {
    var post = {};

    // - "If I've seen RSS feeds with multiple title fields in one item? Why, yes, yes I have."

    // The popular fields
    post.title = $(item).find("title").filter(':first').text();
    post.link = $(item).find("link").filter(':first').text();
    post.description = $(item).find("description").filter(':first').text();
    // Less used fields
    post.creator = $(item).find("dc:creator").filter(':first').text();
    post.date = $(item).find("pubDate").filter(':first').text().substr(5, 11);
    // Locally stored
    post.image = affiliationObject.placeholder;
    // Tag the posts with the key and name of the feed they came from
    post.feedKey = affiliationObject.key;
    post.feedName = affiliationObject.name;

    // Check for image in rarely used tags <enclosure> and <bilde>
    try {
      // Universitetsavisa does this little trick to get images in their feed
      var enclosure = $(item).find('enclosure').filter(':first');
      if (enclosure.length != 0) {
        post.image = enclosure['0'].attributes.url.textContent;
      }
      // Gemini uses this rather blunt hack to put images in their feed
      var bilde = $(item).find('bilde');
      if (bilde.length != 0) {
        post.image = bilde['0'].textContent;
      }
    }
    catch (err) {
      // Do nothing, we we're just checking, move along quitely
    }

    // In case browser does not grok tags with colons, stupid browser
    if (post.creator == '') {
      var tag = ("dc\\:creator").replace( /.*(\:)(.*)/, "$2" );
      $(item).find(tag).each(function(){
        post.creator = $(this).text().trim();
      });
    }

    return post;
  },

  parseAtomEntry: function(entry, affiliationObject) {
    var post = {};

    // The popular fields
    post.title = $(entry).find("title").filter(':first').text();
    post.link = $(entry).find("link[rel='alternate'][type='text/html']").filter(':first').attr('href');
    post.description = $(entry).find("content").filter(':first').text();
    post.creator = $(entry).find("author name").filter(':first').text();
    post.date = $(entry).find("published").filter(':first').text().substr(5, 11);

    // Locally stored
    post.image = affiliationObject.placeholder;
    // Tag the posts with the key and name of the feed they came from
    post.feedKey = affiliationObject.key;
    post.feedName = affiliationObject.name;

    // Extract image from content HTML
    var image = $(entry).find('content').filter(':first').text();
    if (image != undefined) {
      image = image.match(/src="(http:\/\/[a-zA-Z0-9.\/\-_]+)"/);
      if (image != null) {
        post.image = image[1];
      }
    }

    // Empty title field?
    if (post.title.trim() == '')
      post.title = 'Uten tittel';

    // Parse date field
    post.date = new Date(post.date);
    if (post.date != "Invalid Date")
      post.date = post.date.toDateString();
    else
      post.date = null;

    return post;
  },

  postProcess: function(post) {
    // Check for alternative links in description
    post.altLink = this.checkForAltLink(post.description);

    // Remove HTML from description
    post.description = post.description.replace(/<[^>]*>/g, ''); // Tags
    // post.description = post.description.replace(/&(#\d+|\w+);/g, ''); // Entities

    // Didn't find a creator, set the feedname as creator
    if (post.creator.length == 0) {
      post.creator = post.feedName;
    }
    // Capitalize creator name either way
    post.creator = post.creator.capitalize();
    // Abbreviate long creator names
    post.creator = this.abbreviateName(post.creator);

    // In case pubDate didn't exist, set to null
    if (post.date == '') {
      post.date = null;
    }

    // Trimming
    post.title = post.title.trim();
    post.description = post.description.trim();

    // Shorten 'bedriftspresentasjon' to 'bedpres'
    post.title = post.title.replace(/edrift(s)?presentasjon/gi, 'edpres');
    post.description = post.description.replace(/edrift(s)?presentasjon/gi, 'edpres');

    // title + description must not exceed 5 lines
    var line = 50; // conservative estimation
    var desclength = line * 3;
    // double line titles will shorten the description by 1 line
    if (line <= post.title.length)
      desclength -= line;
    // shorten description according to desclength
    if (desclength < post.description.length)
      post.description = post.description.substr(0, desclength) + '...';

    return post;
  },

  // News specific
  refreshAffiliationNewsList: function(items) {
    var freshList = [];
    items.forEach(function(item, index) {
      freshList.push(item.link);
    });
    localStorage.affiliationNewsList = JSON.stringify(freshList);
  },

  // Media specific
  refreshMediaNewsList: function(items) {
    var freshList = [];
    items.forEach(function(item, index) {
      freshList.push(item.link);
    });
    localStorage.mediaNewsList = JSON.stringify(freshList);
  },

  // News specific
  countAffiliationNewsAndNotify: function(items) {
    var unreadCount = 0;
    var maxNewsAmount = this.unreadMaxCount;
    if (items.length-1 < maxNewsAmount)
      maxNewsAmount = items.length-1;

    var newsList = JSON.parse(localStorage.newsList);

    // Count feed items
    var self = this;
    items.forEach(function(item, index) {

      var link = item.link;

      // Counting...
      if (newsList.indexOf(link) === -1) {
        unreadCount++;

        // Send a desktop notification about the first new item
        if (unreadCount == 1) {
          if (localStorage.lastNotifiedAffiliationNews != link) {
            // Remember this
            localStorage.lastNotifiedAffiliationNews = item.link;
            // Show it
            self.showNotification(item);
          }
        }
      }
      // All counted :)
      else {
        if (unreadCount == 0) {
          if (self.debug) console.log('no new posts');
          Browser.setBadgeText('');
        }
        else if (maxNewsAmount <= unreadCount) {
          if (self.debug) console.log(maxNewsAmount + '+ unread posts');
          Browser.setBadgeText(maxNewsAmount + '+');
        }
        else {
          if (self.debug) console.log('1-' + (maxNewsAmount - 1) + ' unread posts');
          Browser.setBadgeText(String(unreadCount));
        }
        localStorage.unreadCount = unreadCount;
        return;
      }

      // Stop counting if unread number is greater than maxNewsAmount
      if ((maxNewsAmount - 1) < index) { // Remember index is counting 0
        if (self.debug) console.log((maxNewsAmount + 1) + ' unread posts (stopped counting)');
        Browser.setBadgeText(String(maxNewsAmount + 1));
        localStorage.unreadCount = maxNewsAmount + 1;
        return;
      }
    });
  },

  showNotification: function(item) {
    if (localStorage.showNotifications == 'true') {
      // Get content
      localStorage.notificationTitle = item.title;
      localStorage.notificationLink = item.link;
      localStorage.notificationDescription = item.description;
      localStorage.notificationCreator = item.creator;
      localStorage.notificationImage = item.image;
      localStorage.notificationFeedKey = item.feedKey;
      localStorage.notificationFeedName = item.feedName;
      // Show desktop notification
      Browser.createNotification('notification.html');
    }
  },

  checkForAltLink: function(description) {
    // Looking for alternative link, find the first and best full link
    var altLink = description.match(/href="(http[^"]*)"/);
    if (altLink != null) {
      if (typeof altLink[1] == 'string') {
        return altLink[1];
      }
    }
    return null;
  },

  abbreviateName: function(oldName) {
    if (oldName != undefined) {
      // Abbreviate middle names if name is long
      if (18 < oldName.length) {
        var pieces = oldName.split(' ');
        if (2 < pieces.length) {
          // Add first name
          var newName = pieces[0];
          // Add one letter per middle name
          for (var i = 1; i < pieces.length - 1; i++)
            newName += ' ' + pieces[i].charAt(0).toUpperCase() + '.';
          // Add last name
          newName += ' ' + pieces[pieces.length-1];
          return newName;
        }
      }
    }
    else {
      if (this.debug) console.log('ERROR: cannot abbreviate an undefined name');
    }
    return oldName;
  },

}
<|endoftext|>


<commit_before>News={
	DropDownMenu: {
		fade:function(menu){
			$(menu).toggle();
			return false;
		},
		dropdown:function(button){
			var list = $(button).parent().find('ul#dropdownmenu');
			if (list.css('display') == 'none')
				list.slideDown('fast').show();
			else
				list.slideUp('fast');

			return false;
		},
		selectItem:function(item, folderid){
			var parent = $(item).parent().parent();
			parent.find('#dropdownBtn').text($(item).text());
			parent.find(':input[name="folderid"]').val(folderid);
			parent.find('ul#dropdownmenu').slideUp('fast');
		}
	},
	UI: {
		overview:function(dialogtype, dialogfile){
		    	if($(dialogtype).dialog('isOpen') == true){
				$(dialogtype).dialog('moveToTop');
			}else{
				$('#dialog_holder').load(OC.filePath('news', 'ajax', dialogfile), function(jsondata){
					if(jsondata.status != 'error'){
						$(dialogtype).dialog({
							dialogClass:'dialog',
							minWidth: 600,
							close: function(event, ui) {
								$(this).dialog('destroy').remove();
							}
						}).css('overflow','visible');
					} else {
						alert(jsondata.data.message);
					}
				});
			}
			return false;
		},
		cloudFileSelected:function(path){
			$.getJSON(OC.filePath('contacts', 'ajax', 'oc_photo.php'),{'path':path,'id':Contacts.UI.Card.id},function(jsondata){
				if(jsondata.status == 'success'){
					//alert(jsondata.data.page);
					Contacts.UI.Card.editPhoto(jsondata.data.id, jsondata.data.tmp)
					$('#edit_photo_dialog_img').html(jsondata.data.page);
				}
				else{
					OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error'));
				}
			});
		}
	},
	Folder: {
		submit:function(button){
			var displayname = $("#folder_add_name").val().trim();

			if(displayname.length == 0) {
				OC.dialogs.alert(t('news', 'Name of the folder cannot be empty.'), t('news', 'Error'));
				return false;
			}

			$(button).attr("disabled", true);
			$(button).prop('value', t('news', 'Adding...'));

			var folderid = $('#inputfolderid:input[name="folderid"]').val();

			var url;
			url = OC.filePath('news', 'ajax', 'createfolder.php');

			$.post(url, { name: displayname, parentid: folderid },
				function(jsondata){
					if(jsondata.status == 'success'){
						//$(button).closest('tr').prev().html(jsondata.page).show().next().remove();
						OC.dialogs.alert(jsondata.data.message, t('news', 'Success!'));
					} else {
						OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
					}
					$("#folder_add_name").val('');
					$(button).attr("disabled", false);
					$(button).prop('value', t('news','Add folder'));
			});
		},
		'delete':function(folderid) {
			$('#feeds_delete').tipsy('hide');
			OC.dialogs.confirm(t('news', 'Are you sure you want to delete this folder and all its feeds?'), t('news', 'Warning'), function(answer) {
				if(answer == true) {
					$.post(OC.filePath('news', 'ajax', 'deletefolder.php'),{'folderid':folderid},function(jsondata){
						if(jsondata.status == 'success'){
							//change this with actually removing the folder in the view instead of the alert msg
							alert('removed!');
						}
						else{
							OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
						}
					});
				}
			});
			return false;
		}
	},
	Feed: {
		id:'',
		submit:function(button){
			var feedurl = $("#feed_add_url").val().trim();

			if(feedurl.length == 0) {
				OC.dialogs.alert(t('news', 'URL cannot be empty.'), t('news', 'Error'));
				return false;
			}

			$(button).attr("disabled", true);
			$(button).prop('value', t('news', 'Adding...'));

			var folderid = $('#inputfolderid:input[name="folderid"]').val();

			$.post(OC.filePath('news', 'ajax', 'createfeed.php'), { feedurl: feedurl, folderid: folderid },
				function(jsondata){
					if(jsondata.status == 'success'){
						OC.dialogs.alert(jsondata.data.message, t('news', 'Success!'));
					} else {
						OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
					}
				$("#feed_add_url").val('');
				$(button).attr("disabled", false);
				$(button).prop('value', t('news', 'Add feed'));
			});

		},
		'delete':function(feedid) {
			$('#feeds_delete').tipsy('hide');
			OC.dialogs.confirm(t('news', 'Are you sure you want to delete this feed?'), t('news', 'Warning'), function(answer) {
				if(answer == true) {
					$.post(OC.filePath('news', 'ajax', 'deletefeed.php'),{'feedid':feedid},function(jsondata){
						if(jsondata.status == 'success'){
							$('#leftcontent [data-id="'+jsondata.data.feedid+'"]').remove();
							//change the right view too (maybe a message to subscribe, like in Google Reader?)
						}
						else{
							OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
						}
					});
				}
			});
			return false;
		},
		markItem:function(itemid) {
			$.post(OC.filePath('news', 'ajax', 'markitem.php'),{'itemid':itemid},function(jsondata){
				if(jsondata.status == 'success'){
					var $currentitem = $('#rightcontent [data-id="'+jsondata.data.itemid+'"]');
					$currentitem.removeClass('title_unread');
					$currentitem.addClass('title_read');
					//set a timeout for this
				}
				else{
					OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
				}
			});
		},
		updateAll:function() {
			$.post(OC.filePath('news', 'ajax', 'feedlist.php'),function(jsondata){
				if(jsondata.status == 'success'){
					var feeds = jsondata.data;
					for (var i = 0; i < feeds.length; i++) {
						News.Feed.updateFeed(feeds[i]['id'], feeds[i]['url'], feeds[i]['folderid']);
					}
				}
				else {
					//TODO:handle error case
				}
			});
		},
		updateFeed:function(feedid, feedurl, folderid) {
			$.post(OC.filePath('news', 'ajax', 'updatefeed.php'),{'feedid':feedid, 'feedurl':feedurl, 'folderid':folderid},function(jsondata){
				if(jsondata.status == 'success'){

				}
				else{
					//TODO:handle error case
				}
			});
		}
	}
}

function setupFeedList() {
    	$('.collapsable_container').click(function(){
		$(this).parent().children().toggle();
		$(this).toggle();
	});

	var list = $('.collapsable,.feeds_list').hover(
		function() {
			$(this).find('#feeds_delete,#feeds_edit').css('display', 'inline');
			$(this).find('#unreaditemcounter').css('display', 'none');
		},
		function() {
			$(this).find('#feeds_delete,#feeds_edit').css('display', 'none');
			$(this).find('#unreaditemcounter').css('display', 'inline');
		}
	);
	list.find('#feeds_delete').hide();
	list.find('#feeds_edit').hide();
	list.find('#unreaditemcounter').show();
}

$(document).ready(function(){

	$('#addfeed').click(function() {
		News.UI.overview('#addfeed_dialog','feeddialog.php');
	});
	$('#addfolder').click(function() {
		News.UI.overview('#addfolder_dialog','folderdialog.php');
	});

	$('.accordion .title_unread').click(function() {
		$(this).next().toggle();
		return false;
	}).next().hide();

	$('.accordion .title_read').click(function() {
		$(this).next().toggle();
		return false;
	}).next().hide();

	$('#addfeedfolder').click(function(event) {
	      event.stopPropagation();
	});

	$('#settingsbtn').click(function() {
		News.UI.overview('#import_dialog', 'importdialog.php');
	});

	$('#cloudbtn').click(function() {
		OC.dialogs.filepicker(t('news', 'Select file'), News.UI.cloudFileSelected, false, '', true);
	});

	setupFeedList();

	var updateInterval = 500000; //how often the feeds should update (in msec)
	setInterval('News.Feed.updateAll()', updateInterval);

});

$(document).click(function(event) {
	$('#feedfoldermenu').hide();
});

<commit_msg>fix cloudbtn javascript handling<commit_after>News={
	DropDownMenu: {
		fade:function(menu){
			$(menu).toggle();
			return false;
		},
		dropdown:function(button){
			var list = $(button).parent().find('ul#dropdownmenu');
			if (list.css('display') == 'none')
				list.slideDown('fast').show();
			else
				list.slideUp('fast');

			return false;
		},
		selectItem:function(item, folderid){
			var parent = $(item).parent().parent();
			parent.find('#dropdownBtn').text($(item).text());
			parent.find(':input[name="folderid"]').val(folderid);
			parent.find('ul#dropdownmenu').slideUp('fast');
		}
	},
	UI: {
		overview:function(dialogtype, dialogfile){
		    	if($(dialogtype).dialog('isOpen') == true){
				$(dialogtype).dialog('moveToTop');
			}else{
				$('#dialog_holder').load(OC.filePath('news', 'ajax', dialogfile), function(jsondata){
					if(jsondata.status != 'error'){
						if(dialogtype == '#import_dialog') {
							$('#cloudbtn').click(function() {
								OC.dialogs.filepicker(t('news', 'Select file'), News.UI.cloudFileSelected, false, '', true);
							});
						}
						$(dialogtype).dialog({
							dialogClass:'dialog',
							minWidth: 600,
							close: function(event, ui) {
								$(this).dialog('destroy').remove();
							}
						}).css('overflow','visible');
					} else {
						alert(jsondata.data.message);
					}
				});
			}
			return false;
		},
		cloudFileSelected:function(path){
			$.getJSON(OC.filePath('contacts', 'ajax', 'oc_photo.php'),{'path':path,'id':Contacts.UI.Card.id},function(jsondata){
				if(jsondata.status == 'success'){
					//alert(jsondata.data.page);
					Contacts.UI.Card.editPhoto(jsondata.data.id, jsondata.data.tmp)
					$('#edit_photo_dialog_img').html(jsondata.data.page);
				}
				else{
					OC.dialogs.alert(jsondata.data.message, t('contacts', 'Error'));
				}
			});
		}
	},
	Folder: {
		submit:function(button){
			var displayname = $("#folder_add_name").val().trim();

			if(displayname.length == 0) {
				OC.dialogs.alert(t('news', 'Name of the folder cannot be empty.'), t('news', 'Error'));
				return false;
			}

			$(button).attr("disabled", true);
			$(button).prop('value', t('news', 'Adding...'));

			var folderid = $('#inputfolderid:input[name="folderid"]').val();

			var url;
			url = OC.filePath('news', 'ajax', 'createfolder.php');

			$.post(url, { name: displayname, parentid: folderid },
				function(jsondata){
					if(jsondata.status == 'success'){
						//$(button).closest('tr').prev().html(jsondata.page).show().next().remove();
						OC.dialogs.alert(jsondata.data.message, t('news', 'Success!'));
					} else {
						OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
					}
					$("#folder_add_name").val('');
					$(button).attr("disabled", false);
					$(button).prop('value', t('news','Add folder'));
			});
		},
		'delete':function(folderid) {
			$('#feeds_delete').tipsy('hide');
			OC.dialogs.confirm(t('news', 'Are you sure you want to delete this folder and all its feeds?'), t('news', 'Warning'), function(answer) {
				if(answer == true) {
					$.post(OC.filePath('news', 'ajax', 'deletefolder.php'),{'folderid':folderid},function(jsondata){
						if(jsondata.status == 'success'){
							//change this with actually removing the folder in the view instead of the alert msg
							alert('removed!');
						}
						else{
							OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
						}
					});
				}
			});
			return false;
		}
	},
	Feed: {
		id:'',
		submit:function(button){
			var feedurl = $("#feed_add_url").val().trim();

			if(feedurl.length == 0) {
				OC.dialogs.alert(t('news', 'URL cannot be empty.'), t('news', 'Error'));
				return false;
			}

			$(button).attr("disabled", true);
			$(button).prop('value', t('news', 'Adding...'));

			var folderid = $('#inputfolderid:input[name="folderid"]').val();

			$.post(OC.filePath('news', 'ajax', 'createfeed.php'), { feedurl: feedurl, folderid: folderid },
				function(jsondata){
					if(jsondata.status == 'success'){
						OC.dialogs.alert(jsondata.data.message, t('news', 'Success!'));
					} else {
						OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
					}
				$("#feed_add_url").val('');
				$(button).attr("disabled", false);
				$(button).prop('value', t('news', 'Add feed'));
			});

		},
		'delete':function(feedid) {
			$('#feeds_delete').tipsy('hide');
			OC.dialogs.confirm(t('news', 'Are you sure you want to delete this feed?'), t('news', 'Warning'), function(answer) {
				if(answer == true) {
					$.post(OC.filePath('news', 'ajax', 'deletefeed.php'),{'feedid':feedid},function(jsondata){
						if(jsondata.status == 'success'){
							$('#leftcontent [data-id="'+jsondata.data.feedid+'"]').remove();
							//change the right view too (maybe a message to subscribe, like in Google Reader?)
						}
						else{
							OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
						}
					});
				}
			});
			return false;
		},
		markItem:function(itemid) {
			$.post(OC.filePath('news', 'ajax', 'markitem.php'),{'itemid':itemid},function(jsondata){
				if(jsondata.status == 'success'){
					var $currentitem = $('#rightcontent [data-id="'+jsondata.data.itemid+'"]');
					$currentitem.removeClass('title_unread');
					$currentitem.addClass('title_read');
					//set a timeout for this
				}
				else{
					OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
				}
			});
		},
		updateAll:function() {
			$.post(OC.filePath('news', 'ajax', 'feedlist.php'),function(jsondata){
				if(jsondata.status == 'success'){
					var feeds = jsondata.data;
					for (var i = 0; i < feeds.length; i++) {
						News.Feed.updateFeed(feeds[i]['id'], feeds[i]['url'], feeds[i]['folderid']);
					}
				}
				else {
					//TODO:handle error case
				}
			});
		},
		updateFeed:function(feedid, feedurl, folderid) {
			$.post(OC.filePath('news', 'ajax', 'updatefeed.php'),{'feedid':feedid, 'feedurl':feedurl, 'folderid':folderid},function(jsondata){
				if(jsondata.status == 'success'){

				}
				else{
					//TODO:handle error case
				}
			});
		}
	}
}

function setupFeedList() {
    	$('.collapsable_container').click(function(){
		$(this).parent().children().toggle();
		$(this).toggle();
	});

	var list = $('.collapsable,.feeds_list').hover(
		function() {
			$(this).find('#feeds_delete,#feeds_edit').css('display', 'inline');
			$(this).find('#unreaditemcounter').css('display', 'none');
		},
		function() {
			$(this).find('#feeds_delete,#feeds_edit').css('display', 'none');
			$(this).find('#unreaditemcounter').css('display', 'inline');
		}
	);
	list.find('#feeds_delete').hide();
	list.find('#feeds_edit').hide();
	list.find('#unreaditemcounter').show();
}

$(document).ready(function(){

	$('#addfeed').click(function() {
		News.UI.overview('#addfeed_dialog','feeddialog.php');
	});
	$('#addfolder').click(function() {
		News.UI.overview('#addfolder_dialog','folderdialog.php');
	});

	$('.accordion .title_unread').click(function() {
		$(this).next().toggle();
		return false;
	}).next().hide();

	$('.accordion .title_read').click(function() {
		$(this).next().toggle();
		return false;
	}).next().hide();

	$('#addfeedfolder').click(function(event) {
	      event.stopPropagation();
	});

	$('#settingsbtn').click(function() {
		News.UI.overview('#import_dialog', 'importdialog.php');
	});

	setupFeedList();

	var updateInterval = 500000; //how often the feeds should update (in msec)
	setInterval('News.Feed.updateAll()', updateInterval);

});

$(document).click(function(event) {
	$('#feedfoldermenu').hide();
});

<|endoftext|>


<commit_before>/**
 * Created with JetBrains WebStorm.
 * User: k-nkgwj
 * Date: 13/01/11
 * Time: 9:20
 * To change this template use File | Settings | File Templates.
 */

var mainRef = new Firebase("https://rtc.firebaseio.com/hub_test_v1/");
//var projectName = prompt("Enter your project name.","");
var projectName = "test";
var projectRef = mainRef.child(projectName);
var nextIdRef = projectRef.child("nextId");
var nodesRef = projectRef.child("nodes");

var myId,parentId;

function listen(myId) {
    parentId = Math.floor(myId / 2);
    log("Your ID:" + myId + "\nParent ID:" + parentId);
    nextIdRef.set(myId + 1);
    nodesRef.child(myId).child("queue").on('child_added', function (snapshot) {
        var data = snapshot.val();
        log(JSON.stringify(data));
        snapshot.ref().remove();
        switch (data.type) {
            case "offer":
                incomingOffer(data.offer, data.port, data.sender);
                break;
            case "answer":
                incomingAnswer(data.answer, data.port, data.sender);
                break;
        }
    });

}

$(function () {
    if (isRoot) {
        myId = 1;
        nodesRef.remove(function(){
            nextIdRef.set(myId, function() {
                listen(myId);
            });
        });
    } else {
        nextIdRef.once('value', function (snapshot) {
            myId = snapshot.val();
            listen(myId);
            nodesRef.child(parentId).child("queue").push({
                type:"request",
                sender:myId
            });
            initiateCall();
        });
    }
});
<commit_msg>introduce projects layer for firebase tree.<commit_after>/**
 * Created with JetBrains WebStorm.
 * User: k-nkgwj
 * Date: 13/01/11
 * Time: 9:20
 * To change this template use File | Settings | File Templates.
 */

var mainRef = new Firebase("https://rtc.firebaseio.com/hub_test_v1/");
var projectsRef = mainRef.child("projects");
//var projectName = prompt("Enter your project name.","");
var projectName = "test";
var projectRef =  projectsRef.child(projectName);
var nextIdRef = projectRef.child("nextId");
var nodesRef = projectRef.child("nodes");

var myId,parentId;

function listen(myId) {
    parentId = Math.floor(myId / 2);
    log("Your ID:" + myId + "\nParent ID:" + parentId);
    nextIdRef.set(myId + 1);
    nodesRef.child(myId).child("queue").on('child_added', function (snapshot) {
        var data = snapshot.val();
        log(JSON.stringify(data));
        snapshot.ref().remove();
        switch (data.type) {
            case "offer":
                incomingOffer(data.offer, data.port, data.sender);
                break;
            case "answer":
                incomingAnswer(data.answer, data.port, data.sender);
                break;
        }
    });

}

$(function () {
    if (isRoot) {
        myId = 1;
        nodesRef.remove(function(){
            nextIdRef.set(myId, function() {
                listen(myId);
            });
        });
    } else {
        nextIdRef.once('value', function (snapshot) {
            myId = snapshot.val();
            listen(myId);
            nodesRef.child(parentId).child("queue").push({
                type:"request",
                sender:myId
            });
            initiateCall();
        });
    }
});
<|endoftext|>


<commit_before>/**
 * Created by marekfort on 1/8/17.
 */

(function($) {

    $.Slider = function(el) {
        this.selected_now = 2;
        this.thumb_list = $(this).find('.thumbnails');
        this.slider_list = $(this).find('.slider');
    };

}(jQuery));

$('.thumbnails li').click(function(e) {
    index = $(e.target.parentNode).index();

    /*change_image();*/

    selected_now = index;
});

$('.right-arrow').click(function() {
    slider_box = $(this.parent);
    if (!(slider_box instanceof $.Slider)) {
        console.log("FAIL");
        this.parent = new $.Slider(this.parent);
        slider_box = new $.Slider(slider_box);
    }

    console.log(slider_box.selected_now);

    change_image(slider_box);

    slider_box.selected_now += 1;

});

function change_image(slider_box) {

    /*deselected_button = get_button(slider_box.selected_now);*/
    deselected_thumb = slider_box.thumb_list.find('li').eq(slider_box.selected_now);
    deselected_button = deselected_thumb.children('button');
    deselected_button.removeClass('selected-thumb');
    /*button = get_button(slider_box, index);*/
    console.log(slider_box.thumb_list);
    thumb = slider_box.thumb_list.find('li').eq(slider_box.selected_now);
    button = thumb.children('button');
    button.addClass('selected-thumb');

    deselected_img = slider_box.slider_list.eq(slider_box.selected_now);
    deselected_img.css('opacity', ('0'));

    img = slider_box.slider_list.eq(slider_box.selected_now);
    img.css('opacity', ('1'));
}

/*
function get_button(slider_box, index) {
    thumb = slider_box.thumb_list.eq(index);
    button = thumb.children('button');
    return button;
}*/
<commit_msg>selected_now count fixed<commit_after>/**
 * Created by marekfort on 1/8/17.
 */

(function($) {

    $.Slider = function(el) {
        this.selected_now = 0;
        this.thumb_list = $(this).find('.thumbnails');
        this.slider_list = $(this).find('.slider');
    };

}(jQuery));

$('.thumbnails li').click(function(e) {
    index = $(e.target.parentNode).index();

    /*change_image();*/

    selected_now = index;
});

$('.right-arrow').click(function() {
    if (!(this.parent instanceof $.Slider)) {
        this.parent = new $.Slider(this.parent);
        console.log(this.parent.selected_now);
    }

    change_image(this.parent);

    this.parent.selected_now += 1;
});

function change_image(slider_box) {
    console.log(slider_box.selected_now);
    /*deselected_button = get_button(slider_box.selected_now);*/
    deselected_thumb = slider_box.thumb_list.find('li').eq(slider_box.selected_now);
    deselected_button = deselected_thumb.children('button');
    deselected_button.removeClass('selected-thumb');
    /*button = get_button(slider_box, index);*/
    console.log(slider_box.thumb_list);
    thumb = slider_box.thumb_list.find('li').eq(slider_box.selected_now + 1);
    button = thumb.children('button');
    button.addClass('selected-thumb');

    deselected_img = slider_box.slider_list.eq(slider_box.selected_now);
    deselected_img.css('opacity', ('0'));

    img = slider_box.slider_list.eq(slider_box.selected_now + 1);
    img.css('opacity', ('1'));
}

/*
function get_button(slider_box, index) {
    thumb = slider_box.thumb_list.eq(index);
    button = thumb.children('button');
    return button;
}*/
<|endoftext|>


<commit_before>"use strict";
(function() {
  var baseURL = "https://dl.dropboxusercontent.com/s/";
  var chapterInfo = [
    {
      "number": "1",
      "title": "One Punch",
      "pages": [
        "cadz9o1zrnftgjd/OPM_1_01.jpg",
        "tm10u82i6fisd8c/OPM_1_02-03.jpg",
        "dnccp9idmwlbj82/OPM_1_04.jpg",
        "1ppjf2cdj708zku/OPM_1_05.jpg",
        "q46jiur8xkmtrxv/OPM_1_06.jpg",
        "yf2ch4b9m9pxtyp/OPM_1_07.jpg",
        "b8n0t27zf0ruzt7/OPM_1_08.jpg",
        "efcfbrw4jzglpyz/OPM_1_09.jpg",
        "gtowm1j5qrtbgm5/OPM_1_10.jpg",
        "r4ajxgkmfzr0xa3/OPM_1_11.jpg",
        "a6znj0s5zsp5we4/OPM_1_12.jpg",
        "trzmatbr9s1rpdm/OPM_1_13.jpg",
        "xm05vuha9g3mdo6/OPM_1_14-15.jpg",
        "ng0x19z2r740hf5/OPM_1_16.jpg",
        "41yx5va4bwyk9i4/OPM_1_17.jpg",
        "d1pc2ruexmo8box/OPM_1_18-19.jpg",
        "98rx0erbl7boqnh/OPM_1_20-21.jpg",
        "9gsjxzy85na9h0q/OPM_1_22.jpg"
      ]
    }
  ]

  var lastChapter = chapterInfo.length;

  var currentChapter = 1;
  var currentPage = 1;
  var chapterSize = 1;

  var imageElement = null;

  function switchChapter(chapterIndex) {
    currentChapter = chapterIndex;
    chapterSize = chapterInfo[currentChapter].pages.length;
    loadPage(1);
  }

  function loadPage(pageIndex) {
    currentPage = pageIndex;
    imageElement.src = baseURL + chapterInfo[currentChapter].pages[currentPage];
  }

  function pageBack() {
    if (currentPage < 2) {
      if (currentChapter > 1) {
        switchChapter(currentChapter - 1);
      }
    }
    else {
      loadPage(currentPage - 1);
    }
  }

  function pageForward() {
    if (currentPage >= chapterSize) {
      if (currentChapter < lastChapter) {
        switchChapter(currentChapter + 1);
      }
    }
    else {
      loadPage(currentPage + 1);
    }
  }

  function keyCheck(e) {
    if (e.keyCode === 37) { // Left Arrow
      pageBack();
    }
    else if (e.keyCode === 39) { // Right Arrow
      pageForward();
    }
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    imageElement = document.getElementById("image");
    document.getElementById("left").addEventListener("click", pageBack);
    document.getElementById("right").addEventListener("click", pageForward);
    document.addEventListener("keydown", keyCheck);
    loadPage(1);
  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<commit_msg>Update read.js<commit_after>"use strict";
(function() {
  var baseURL = "https://dl.dropboxusercontent.com/s/";
  var chapterInfo = [{},
    {
      "number": "1",
      "title": "One Punch",
      "pages": [
        "cadz9o1zrnftgjd/OPM_1_01.jpg",
        "tm10u82i6fisd8c/OPM_1_02-03.jpg",
        "dnccp9idmwlbj82/OPM_1_04.jpg",
        "1ppjf2cdj708zku/OPM_1_05.jpg",
        "q46jiur8xkmtrxv/OPM_1_06.jpg",
        "yf2ch4b9m9pxtyp/OPM_1_07.jpg",
        "b8n0t27zf0ruzt7/OPM_1_08.jpg",
        "efcfbrw4jzglpyz/OPM_1_09.jpg",
        "gtowm1j5qrtbgm5/OPM_1_10.jpg",
        "r4ajxgkmfzr0xa3/OPM_1_11.jpg",
        "a6znj0s5zsp5we4/OPM_1_12.jpg",
        "trzmatbr9s1rpdm/OPM_1_13.jpg",
        "xm05vuha9g3mdo6/OPM_1_14-15.jpg",
        "ng0x19z2r740hf5/OPM_1_16.jpg",
        "41yx5va4bwyk9i4/OPM_1_17.jpg",
        "d1pc2ruexmo8box/OPM_1_18-19.jpg",
        "98rx0erbl7boqnh/OPM_1_20-21.jpg",
        "9gsjxzy85na9h0q/OPM_1_22.jpg"
      ]
    }
  ]

  var lastChapter = chapterInfo.length - 1;

  var currentChapter = -1;
  var currentPage = -1;
  var chapterSize = -1;

  var imageElement = null;

  function switchChapter(chapterIndex) {
    currentChapter = chapterIndex;
    chapterSize = chapterInfo[currentChapter].pages.length;
    loadPage(1);
  }

  function loadPage(pageIndex) {
    currentPage = pageIndex;
    imageElement.src = baseURL + chapterInfo[currentChapter].pages[currentPage];
  }

  function pageBack() {
    if (currentPage < 2) {
      if (currentChapter > 1) {
        switchChapter(currentChapter - 1);
      }
    }
    else {
      loadPage(currentPage - 1);
    }
  }

  function pageForward() {
    if (currentPage >= chapterSize) {
      if (currentChapter < lastChapter) {
        switchChapter(currentChapter + 1);
      }
    }
    else {
      loadPage(currentPage + 1);
    }
  }

  function keyCheck(e) {
    if (e.keyCode === 37) { // Left Arrow
      pageBack();
    }
    else if (e.keyCode === 39) { // Right Arrow
      pageForward();
    }
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    imageElement = document.getElementById("image");
    document.getElementById("left").addEventListener("click", pageBack);
    document.getElementById("right").addEventListener("click", pageForward);
    document.addEventListener("keydown", keyCheck);
    switchChapter(1);
  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<|endoftext|>


<commit_before>"use strict";
(function() {
  var baseURL = "https://dl.dropboxusercontent.com/s/";
  var chapterInfo = [{},
    {
      "number": "1",
      "title": "One Punch",
      "pages": ["",
        "cadz9o1zrnftgjd/OPM_1_01.jpg",
        "tm10u82i6fisd8c/OPM_1_02-03.jpg",
        "dnccp9idmwlbj82/OPM_1_04.jpg",
        "1ppjf2cdj708zku/OPM_1_05.jpg",
        "q46jiur8xkmtrxv/OPM_1_06.jpg",
        "yf2ch4b9m9pxtyp/OPM_1_07.jpg",
        "b8n0t27zf0ruzt7/OPM_1_08.jpg",
        "efcfbrw4jzglpyz/OPM_1_09.jpg",
        "gtowm1j5qrtbgm5/OPM_1_10.jpg",
        "r4ajxgkmfzr0xa3/OPM_1_11.jpg",
        "a6znj0s5zsp5we4/OPM_1_12.jpg",
        "trzmatbr9s1rpdm/OPM_1_13.jpg",
        "xm05vuha9g3mdo6/OPM_1_14-15.jpg",
        "ng0x19z2r740hf5/OPM_1_16.jpg",
        "41yx5va4bwyk9i4/OPM_1_17.jpg",
        "d1pc2ruexmo8box/OPM_1_18-19.jpg",
        "98rx0erbl7boqnh/OPM_1_20-21.jpg",
        "9gsjxzy85na9h0q/OPM_1_22.jpg"
      ]
    }
  ]

  var lastChapter = chapterInfo.length - 1;

  var currentChapter = -1;
  var currentPage = -1;
  var chapterSize = -1;

  var imageElement = null;
  var loadingElement = null;
  var leftElement = null;
  var rightElement = null;

  function switchChapter(chapterIndex) {
    currentChapter = chapterIndex;
    chapterSize = chapterInfo[currentChapter].pages.length - 1;
    loadPage(1);
  }

  function loadPage(pageIndex) {
    startLoading();
    currentPage = pageIndex;
    var newURL = baseURL + chapterInfo[currentChapter].pages[currentPage];
    if (currentPage < 2 && currentChapter < 2) {
      leftElement.className = "side";
    }
    else {
      leftElement.className = "side hand";
    }
    if (currentPage >= chapterSize && currentChapter >= lastChapter) {
      rightElement.className = "side";
    }
    else {
      rightElement.className = "side hand";
    }
    loadingElement.innerHTML = "Loading... 0.00%";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", newURL);
    xhr.onprogress = function(data) {
      var percentDisplay = (data.loaded / data.total * 100).toFixed(2);
      loadingElement.innerHTML = "Loading..." + percentDisplay;
    };
    xhr.onload = function() {
      loadingElement.innerHTML = "Loading... 100.00%";
      imageElement.src = newURL;
      stopLoading();
    };
    xhr.setRequestHeader("Pragma", "");
    xhr.setRequestHeader("Cache-Control", "");
    xhr.send();
  }

  function startLoading() {
    loadingElement.className = "";
  }

  function stopLoading() {
    imageElement.className = "";
    loadingElement.className = "hidden";
  }

  function pageBack() {
    if (currentPage < 2) {
      if (currentChapter > 1) {
        switchChapter(currentChapter - 1);
      }
    }
    else {
      loadPage(currentPage - 1);
    }
  }

  function pageForward() {
    if (currentPage >= chapterSize) {
      if (currentChapter < lastChapter) {
        switchChapter(currentChapter + 1);
      }
    }
    else {
      loadPage(currentPage + 1);
    }
  }

  function keyCheck(e) {
    if (e.keyCode === 37) { // Left Arrow
      pageBack();
    }
    else if (e.keyCode === 39) { // Right Arrow
      pageForward();
    }
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    imageElement = document.getElementById("image");
    loadingElement = document.getElementById("loading");
    leftElement = document.getElementById("left")
    rightElement = document.getElementById("right");
    leftElement.addEventListener("click", pageBack);
    rightElement.addEventListener("click", pageForward);
    //imageElement.addEventListener("load", stopLoading);
    document.addEventListener("keydown", keyCheck);
    switchChapter(1);
  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<commit_msg>Update read.js<commit_after>"use strict";
(function() {
  var baseURL = "https://dl.dropboxusercontent.com/s/";
  var chapterInfo = [{},
    {
      "number": "1",
      "title": "One Punch",
      "pages": ["",
        "cadz9o1zrnftgjd/OPM_1_01.jpg",
        "tm10u82i6fisd8c/OPM_1_02-03.jpg",
        "dnccp9idmwlbj82/OPM_1_04.jpg",
        "1ppjf2cdj708zku/OPM_1_05.jpg",
        "q46jiur8xkmtrxv/OPM_1_06.jpg",
        "yf2ch4b9m9pxtyp/OPM_1_07.jpg",
        "b8n0t27zf0ruzt7/OPM_1_08.jpg",
        "efcfbrw4jzglpyz/OPM_1_09.jpg",
        "gtowm1j5qrtbgm5/OPM_1_10.jpg",
        "r4ajxgkmfzr0xa3/OPM_1_11.jpg",
        "a6znj0s5zsp5we4/OPM_1_12.jpg",
        "trzmatbr9s1rpdm/OPM_1_13.jpg",
        "xm05vuha9g3mdo6/OPM_1_14-15.jpg",
        "ng0x19z2r740hf5/OPM_1_16.jpg",
        "41yx5va4bwyk9i4/OPM_1_17.jpg",
        "d1pc2ruexmo8box/OPM_1_18-19.jpg",
        "98rx0erbl7boqnh/OPM_1_20-21.jpg",
        "9gsjxzy85na9h0q/OPM_1_22.jpg"
      ]
    }
  ]

  var lastChapter = chapterInfo.length - 1;

  var currentChapter = -1;
  var currentPage = -1;
  var chapterSize = -1;

  var imageElement = null;
  var loadingElement = null;
  var leftElement = null;
  var rightElement = null;

  function switchChapter(chapterIndex) {
    currentChapter = chapterIndex;
    chapterSize = chapterInfo[currentChapter].pages.length - 1;
    loadPage(1);
  }

  function loadPage(pageIndex) {
    startLoading();
    currentPage = pageIndex;
    var newURL = baseURL + chapterInfo[currentChapter].pages[currentPage];
    if (currentPage < 2 && currentChapter < 2) {
      leftElement.className = "side";
    }
    else {
      leftElement.className = "side hand";
    }
    if (currentPage >= chapterSize && currentChapter >= lastChapter) {
      rightElement.className = "side";
    }
    else {
      rightElement.className = "side hand";
    }
    loadingElement.innerHTML = "Loading... 0.00%";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", newURL);
    xhr.responseType = "arraybuffer";
    xhr.onprogress = function(data) {
      var percentDisplay = (data.loaded / data.total * 100).toFixed(2);
      loadingElement.innerHTML = "Loading..." + percentDisplay;
    };
    xhr.onload = function(data) {
      loadingElement.innerHTML = "Loading... 100.00%";
      var blob = new Blob([xhr.response], {type: "image/jpg"});
      image.src = window.URL.createObjectURL(blob);
      stopLoading();
    };
    xhr.send();
  }

  function startLoading() {
    loadingElement.className = "";
  }

  function stopLoading() {
    imageElement.className = "";
    loadingElement.className = "hidden";
  }

  function pageBack() {
    if (currentPage < 2) {
      if (currentChapter > 1) {
        switchChapter(currentChapter - 1);
      }
    }
    else {
      loadPage(currentPage - 1);
    }
  }

  function pageForward() {
    if (currentPage >= chapterSize) {
      if (currentChapter < lastChapter) {
        switchChapter(currentChapter + 1);
      }
    }
    else {
      loadPage(currentPage + 1);
    }
  }

  function keyCheck(e) {
    if (e.keyCode === 37) { // Left Arrow
      pageBack();
    }
    else if (e.keyCode === 39) { // Right Arrow
      pageForward();
    }
  }

  function setup() {
    document.removeEventListener("DOMContentLoaded", setup);
    imageElement = document.getElementById("image");
    loadingElement = document.getElementById("loading");
    leftElement = document.getElementById("left")
    rightElement = document.getElementById("right");
    leftElement.addEventListener("click", pageBack);
    rightElement.addEventListener("click", pageForward);
    //imageElement.addEventListener("load", stopLoading);
    document.addEventListener("keydown", keyCheck);
    switchChapter(1);
  }

  document.addEventListener("DOMContentLoaded", setup);
}).call(this);
<|endoftext|>


<commit_before>function Rect() {
  this.x = Math.floor(Math.random() * (640 - 30));;
  this.y = Math.floor(Math.random() * (480 - 30));;
  this.velocity = Math.random() > 0.5 ? -1 : 1;
  this.veleftright = 1;
};

Rect.prototype.draw = function(context) {
  context.fillRect(this.x, this.y, 30, 30);
};

Rect.prototype.update = function() {
  if (this.y < 0) {
    this.velocity = 1;
  } else if (this.y > 450) {
    this.velocity = -1;
  }
  if(player.input.jump == true){
    this.veleftright = -1;
  }else{
    this.veleftright = 0;
  }
  if(player.input.right == true){
    this.veleftright = 1;
  }else{
    this.veleftright = 0;
  }
  this.y += this.velocity;
  this.x += this.veleftright;
};
<commit_msg>Update rect.js<commit_after>function Rect() {
  this.x = Math.floor(Math.random() * (640 - 30));;
  this.y = Math.floor(Math.random() * (480 - 30));;
  this.velocity = Math.random() > 0.5 ? -1 : 1;
  this.veleftright = 1;
};

Rect.prototype.draw = function(context) {
  context.fillRect(this.x, this.y, 30, 30);
};

Rect.prototype.update = function() {
  if (this.y < 0) {
    this.velocity = 1;
  } else if (this.y > 450) {
    this.velocity = -1;
  }

  if(player.input.left == true){
    this.veleftright = -1;
  }

  if(player.input.right == true){
    this.veleftright = 1;
  }

  this.y += this.velocity;
  this.x += this.veleftright;
};
<|endoftext|>


<commit_before>var args = process.argv.slice(2);
if (args.length < 1) {
  args = ["config.toml"]
}

var Cookies = require('cookies');
var toml = require('toml');
var fs = require('fs');
var url = require('url');
var path = require('path');
var http = require('http');
var crypto = require('crypto');
var randomstring = require("randomstring");
var forever = require('forever-monitor');
var MongoClient = require('mongodb').MongoClient;

var configuration = null;
var routes = null;
var apps = null;
var auth = null;
var config = null;
var MongoDB = null;

var mongoCheckInterval = null;

function mongoCheck() {
    if (MongoDB == null){
	var mongoUrl = "mongodb://mongo:27017/MedBook";
	// defaults to auto_reconnect
	// http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect
	MongoClient.connect(mongoUrl, function(err, db) {
	    if (db == null) {
		console.log("still dead after connect");
	    } else {
		console.log("successfully connected to Mongo");
		MongoDB = db;
		//interval is failing to clear, annoying but not a huge deal
		//maybe related http://stackoverflow.com/questions/30465977/node-clearinterval-only-clearing-intervalobject-scoped-to-method-it-was-assigned
		clearInterval(mongoCheckInterval);
	    }
	});
    }
}
mongoCheckInterval = setInterval(mongoCheck, 1000);

var SECRET;
function changeSecret() {
    SECRET = randomstring.generate(7);
}
changeSecret();

setInterval(changeSecret, 30000);

function hash(pwd) {
    var hash = crypto.createHash('sha256').update(SECRET + pwd).digest('base64');
    return hash;
}

var server = null;

menuFile = null;
reloadFile = null;
postScript = null;

var getTarget = function(req) {
    var a = req.url.split("/");
    if (a.length > 1) {
        var service = routes["/" + a[1]];
	if (service){
	    var target = "http://" + service.containerName + ":" + service.port;
	} else {
	    //fall through to telescope
	    var telescope = config.apps.Telescope;
	    var target = "http://" + telescope.containerName + ":" + telescope.port;
	}
	return target;
    }
}

readMenu = function() {
  menuFile = fs.readFileSync("menu.html");
  reloadFile = fs.readFileSync("reload.html");
};

readMenu();

postScriptFilename = "postScript.js";
readPostScript = function() {
  postScript = fs.readFileSync(postScriptFilename);
};
readPostScript();

redirectServer = null;
readSSLcredentials = function() {
    if (config.server.ssl && config.server.nonssl)  {
      if (redirectServer)
          server.close();

      redirectServer = require('http').createServer(function(req, res) {
       var hostname = req.headers.host

       // redirect http://tumormap.ucsc.edu to https://medbook.ucsc.edu/hex  (change hex to tumormap later)
        if (hostname && hostname.indexOf("tumormap") == 0 ) {
            var red = "https://" + config.server.host + ":" + config.server.ssl + "/hex" + req.url;
            res.writeHead(307, {'Location': red});
            res.end();
        } else {
           var red = "https://" + config.server.host + ":" + config.server.ssl + req.url;
           res.writeHead(307, {'Location': red});
           res.end();
        }

      });
      redirectServer.listen(config.server.nonssl);
    }

    var options = {
         key: fs.readFileSync(config.server.key),
         cert: fs.readFileSync(config.server.cert),
    };

    if (config.server.chain) {
        var ca = []
        var chain = fs.readFileSync(config.server.chain, 'utf8');
        chain = chain.split("\n");
        var cert = [];
        for (var i =0; i < chain.length; i++) {
          var line = chain[i];
          if (line.length > 0) {
            cert.push(line);
            if (line.match(/-END CERTIFICATE-/)) {
                var c = cert.join("\n");
                ca.push(c);
                cert = [];
            }
          }
        }
        options.ca = ca;
    }
    return options;
}

run = function() {
  if (server) {
    server.close();
  }

  configApp(args[0]);

    function forward(req, res) {
	var target = getTarget(req);
	if (req.url.indexOf("/xena") == 0) {
            // console.log("xena directing to port", port, "mapping url", req.url, "to", req.url.replace("/xena","/"));
            req.url =  req.url.replace("/xena","");
        }
        proxy.web(req, res, {
            target: target,
        },function(e){
            log_error(e,req);
	    console.log("web error", e);
	    res.writeHead(500, { 'Content-Type': 'text/html' });
            res.write(reloadFile, "binary");
	    res.end();
	});
    }

  function signIn(req, res) {
      var host = null;
      if (config.server.ssl)
        host = "https://" + config.server.host + ":"+ config.server.ssl;
      else
        host = "http://" + config.server.host + ":"+ config.server.nonssl;

      var url = host + "/sign-in?RETURNTO="+encodeURI(req.url);
      res.writeHead(307, { location: url});
      res.end();
  }

  function mustLogin(firstPart, req, res) {
      var cookies = new Cookies(req, res);

      function checkCredentials(cache, gateway_token) {
         if (gateway_token)
           try {
               var gateway_credentials = JSON.parse(gateway_token);
               var obj = JSON.parse(gateway_credentials.json);

               if ( obj.collaborations.indexOf(firstPart) >= 0) {

                   var signature = hash( gateway_credentials.json );
                   if ( signature == gateway_credentials.signature ) {
                       if (cache) console.log("credentials cached");
                       return true;
                   }
               }
           } catch (err) {
               console.log("credential failure" , err);
               console.log("gateway_token" , gateway_token);
               console.log("gateway_credentials" , gateway_credentials);
           }
         return false;
      }

      function requestCredentials() {
        var options = {
          method: 'GET',
          path: '/medbookUser',
          port: final,
          headers: { 'cookie': req.headers.cookie, },
          keepAlive: true,
          keepAliveMsecs: 3600000, // an hour
         };
         var medbookUserReq = http.request(options, function(medbookUserRes) {
               medbookUserRes.setEncoding('utf8');
               var all = "";
               medbookUserRes.on("data", function(data) { all += data; });
               medbookUserRes.on("end", function(data) {
                   if (data != null) all += data;
                   var gateway_credentials = { signature: hash( all ), json: all, }
                   var gateway_token = JSON.stringify(gateway_credentials);
                   cookies.set("gateway_token", gateway_token);
                   if (checkCredentials(false, gateway_token))
                       forward(req, res);
                   else
                       signIn(req, res);
               });
         });
        medbookUserReq.on("error", function(err) {
             signIn(req, res);
        });
        medbookUserReq.end();
      }; // requestCredentials()

      if (checkCredentials(true, cookies.get("gateway_token")))
         forward(req, res);
      else
         requestCredentials();
  } // mustLogin

  function main(req, res) {
    var hostname = req.headers.host
    if (req.url == "/menu")
        return serveMenu(req, res);
    if (req.url.indexOf( "/postScript") == 0)
        return serveScript(req, res, postScript);

    if (req.url.indexOf(hostname.indexOf("tumormap")) == 0 ) {
        var red = "https://" + config.server.host + ":" + config.server.ssl + "/hex/" + req.url;
        res.writeHead(307, {'Location': red});
        res.end();
    }
    if (req.url.indexOf("/swat") == 0 ) {
        req.url = req.url.replace("/swat", "");
 	if (req.url.indexOf("/..") >=0 ) {
            console.log(".. not allowed: " + req.url);
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end();
	}
        return serveFile(req, res, '/data/home/galaxy/hexProxy/');
    }
    /*if (req.url.indexOf("/public") == 0)
        return serveFile(req, res, '/data/public/');*/

    var urlPath = req.url.split("/");
    var firstPart = "never match";
    if (urlPath && urlPath.length >= 2 && urlPath[1].length > 0)
        firstPart = urlPath[1];

    var sla = "/" + firstPart;

    if (sla in auth && auth[sla]) {
        mustLogin(firstPart, req, res);
    } else
        forward(req, res);
  } // main

  if (config.server.ssl)
      server = require('https').createServer(readSSLcredentials(), main);
  else
      server = require('http').createServer(main);

  var httpProxy = require('http-proxy')
  var proxy = httpProxy.createProxy({ ws : true });

  server.on('upgrade',function(req,res){
    var target = getTarget(req);
    proxy.ws(req, res, {
      target: target,
    },function(e){
      log_error(e, req);
	console.log("WS ERROR", e);
	/*
	res.writeHead(500, {
	  'Content-Type': 'text/plain'
	});
	res.end('Something went wrong. And we are reporting a custom error message.');
	*/
    });
  })

  if (config.server.ssl) {
      console.log("ssl listening on", config.server.ssl);
      server.listen(config.server.ssl)
  } else {
      console.log("nonssl listening on", config.server.nonssl);
      server.listen(config.server.nonssl)
  }

};

splitHostPort = function(s) {
  var parts, ret;
  parts = s.split(':', 2);
  ret = {
    host: parts[0]
  };
  if (parts.length > 1) {
    ret.port = parseInt(parts[1], 10);
  } else {
    ret.port = 80;
  }
  return ret;
};

configApp = function(path) {
  try {
    config = toml.parse(fs.readFileSync(path));
  } catch (_error) {
    console.log("Failed to parse configuration file " + path);
    return process.exit(1);
  }

  var appName, ca, link, menu, menuItem;
  menu = [];
  routes = {};
  apps = {};
  auth = {};
  final = config.final.port

  for (appName in config.apps) {
    var ca = config.apps[appName];
    routes[ca.route] = ca;
    apps[ca.route] = ca;
    auth[ca.route] = ca.auth;
  }
};

serveMenu = function(req, res) {
  var menu = [];
  var routeHacks = "";
  for (appName in config.apps) {
    var ca = config.apps[appName];
    menuItem = String(ca.menuItem);
    if (menuItem === null) {
      menuItem = ca.route;
    }
    menuItem = menuItem.replace(/\ /g, " ");
    href = ca.path ? ca.path : ca.route;

    link = "" + menuItem + "";
    routeHacks += "if (Router && !('" + ca.route + "' in  Router.routes)) Router.route('" + ca.route + "', function () {}, {where: 'server'});\n";
    if (ca.menuItem) {
      if (ca.menuPosition !== void 0) {
        menu.splice(ca.menuPosition, 0, link);
      } else {
        menu.push(link);
      }
    }
  }

  var text = String(menuFile).replace("LIST", (menu.map(function(a) {
    return "
" + a + "

";
  })).join(''));

  text += "";

  res.writeHead(200);
  res.write(text, "binary");
  return res.end();
};

serveScript = function(req, res, script) {
  res.writeHead(200, {'Content-Type': 'application/x-javascript'});
  res.write(script, "binary");
  return res.end();
};

var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"};

function serveFile(req, res, dir) {
    var uri = url.parse(req.url).pathname;
    // console.log("serveFile uri", uri);
    if (uri == null || uri == "" || uri == "/")
       uri = "index.html"
    var filename = path.join(dir, uri);
    fs.exists(filename, function(exists) {
        if(!exists) {
            console.log("not exists: " + filename);
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end();
            return;
        }
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        res.writeHead(200, mimeType);

        var fileStream = fs.createReadStream(filename);
        fileStream.pipe(res);

    }); //end fs.exists

};

console.log("watching", args[0]);

fs.watchFile(args[0], run);
fs.watchFile("/data/MedBook/Gateway/menu.html", readMenu);
fs.watchFile(postScriptFilename, readPostScript);

function log_error(e,req){
  if(e){
    /*
    console.log("log_error");
    console.error(e.message);
    console.log(req.headers.host,'-->');
    console.log('-----');
    */
  }
}

run();
<commit_msg>more accurate mongo errors<commit_after>var args = process.argv.slice(2);
if (args.length < 1) {
  args = ["config.toml"]
}

var Cookies = require('cookies');
var toml = require('toml');
var fs = require('fs');
var url = require('url');
var path = require('path');
var http = require('http');
var crypto = require('crypto');
var randomstring = require("randomstring");
var forever = require('forever-monitor');
var MongoClient = require('mongodb').MongoClient;

var configuration = null;
var routes = null;
var apps = null;
var auth = null;
var config = null;
var MongoDB = null;

var mongoCheckInterval = null;

function mongoCheck() {
    if (MongoDB == null){
	var mongoUrl = "mongodb://mongo:27017/MedBook";
	// defaults to auto_reconnect
	// http://mongodb.github.io/node-mongodb-native/driver-articles/mongoclient.html#mongoclient-connect
	MongoClient.connect(mongoUrl, function(err, db) {
	    if (db == null) {
		console.log("Error connecting to mongo", err);
	    } else {
		console.log("successfully connected to Mongo");
		MongoDB = db;
		//interval is failing to clear, annoying but not a huge deal
		//maybe related http://stackoverflow.com/questions/30465977/node-clearinterval-only-clearing-intervalobject-scoped-to-method-it-was-assigned
		clearInterval(mongoCheckInterval);
	    }
	});
    }
}
mongoCheckInterval = setInterval(mongoCheck, 1000);

var SECRET;
function changeSecret() {
    SECRET = randomstring.generate(7);
}
changeSecret();

setInterval(changeSecret, 30000);

function hash(pwd) {
    var hash = crypto.createHash('sha256').update(SECRET + pwd).digest('base64');
    return hash;
}

var server = null;

menuFile = null;
reloadFile = null;
postScript = null;

var getTarget = function(req) {
    var a = req.url.split("/");
    if (a.length > 1) {
        var service = routes["/" + a[1]];
	if (service){
	    var target = "http://" + service.containerName + ":" + service.port;
	} else {
	    //fall through to telescope
	    var telescope = config.apps.Telescope;
	    var target = "http://" + telescope.containerName + ":" + telescope.port;
	}
	return target;
    }
}

readMenu = function() {
  menuFile = fs.readFileSync("menu.html");
  reloadFile = fs.readFileSync("reload.html");
};

readMenu();

postScriptFilename = "postScript.js";
readPostScript = function() {
  postScript = fs.readFileSync(postScriptFilename);
};
readPostScript();

redirectServer = null;
readSSLcredentials = function() {
    if (config.server.ssl && config.server.nonssl)  {
      if (redirectServer)
          server.close();

      redirectServer = require('http').createServer(function(req, res) {
       var hostname = req.headers.host

       // redirect http://tumormap.ucsc.edu to https://medbook.ucsc.edu/hex  (change hex to tumormap later)
        if (hostname && hostname.indexOf("tumormap") == 0 ) {
            var red = "https://" + config.server.host + ":" + config.server.ssl + "/hex" + req.url;
            res.writeHead(307, {'Location': red});
            res.end();
        } else {
           var red = "https://" + config.server.host + ":" + config.server.ssl + req.url;
           res.writeHead(307, {'Location': red});
           res.end();
        }

      });
      redirectServer.listen(config.server.nonssl);
    }

    var options = {
         key: fs.readFileSync(config.server.key),
         cert: fs.readFileSync(config.server.cert),
    };

    if (config.server.chain) {
        var ca = []
        var chain = fs.readFileSync(config.server.chain, 'utf8');
        chain = chain.split("\n");
        var cert = [];
        for (var i =0; i < chain.length; i++) {
          var line = chain[i];
          if (line.length > 0) {
            cert.push(line);
            if (line.match(/-END CERTIFICATE-/)) {
                var c = cert.join("\n");
                ca.push(c);
                cert = [];
            }
          }
        }
        options.ca = ca;
    }
    return options;
}

run = function() {
  if (server) {
    server.close();
  }

  configApp(args[0]);

    function forward(req, res) {
	var target = getTarget(req);
	if (req.url.indexOf("/xena") == 0) {
            // console.log("xena directing to port", port, "mapping url", req.url, "to", req.url.replace("/xena","/"));
            req.url =  req.url.replace("/xena","");
        }
        proxy.web(req, res, {
            target: target,
        },function(e){
            log_error(e,req);
	    console.log("web error", e);
	    res.writeHead(500, { 'Content-Type': 'text/html' });
            res.write(reloadFile, "binary");
	    res.end();
	});
    }

  function signIn(req, res) {
      var host = null;
      if (config.server.ssl)
        host = "https://" + config.server.host + ":"+ config.server.ssl;
      else
        host = "http://" + config.server.host + ":"+ config.server.nonssl;

      var url = host + "/sign-in?RETURNTO="+encodeURI(req.url);
      res.writeHead(307, { location: url});
      res.end();
  }

  function mustLogin(firstPart, req, res) {
      var cookies = new Cookies(req, res);

      function checkCredentials(cache, gateway_token) {
         if (gateway_token)
           try {
               var gateway_credentials = JSON.parse(gateway_token);
               var obj = JSON.parse(gateway_credentials.json);

               if ( obj.collaborations.indexOf(firstPart) >= 0) {

                   var signature = hash( gateway_credentials.json );
                   if ( signature == gateway_credentials.signature ) {
                       if (cache) console.log("credentials cached");
                       return true;
                   }
               }
           } catch (err) {
               console.log("credential failure" , err);
               console.log("gateway_token" , gateway_token);
               console.log("gateway_credentials" , gateway_credentials);
           }
         return false;
      }

      function requestCredentials() {
        var options = {
          method: 'GET',
          path: '/medbookUser',
          port: final,
          headers: { 'cookie': req.headers.cookie, },
          keepAlive: true,
          keepAliveMsecs: 3600000, // an hour
         };
         var medbookUserReq = http.request(options, function(medbookUserRes) {
               medbookUserRes.setEncoding('utf8');
               var all = "";
               medbookUserRes.on("data", function(data) { all += data; });
               medbookUserRes.on("end", function(data) {
                   if (data != null) all += data;
                   var gateway_credentials = { signature: hash( all ), json: all, }
                   var gateway_token = JSON.stringify(gateway_credentials);
                   cookies.set("gateway_token", gateway_token);
                   if (checkCredentials(false, gateway_token))
                       forward(req, res);
                   else
                       signIn(req, res);
               });
         });
        medbookUserReq.on("error", function(err) {
             signIn(req, res);
        });
        medbookUserReq.end();
      }; // requestCredentials()

      if (checkCredentials(true, cookies.get("gateway_token")))
         forward(req, res);
      else
         requestCredentials();
  } // mustLogin

  function main(req, res) {
    var hostname = req.headers.host
    if (req.url == "/menu")
        return serveMenu(req, res);
    if (req.url.indexOf( "/postScript") == 0)
        return serveScript(req, res, postScript);

    if (req.url.indexOf(hostname.indexOf("tumormap")) == 0 ) {
        var red = "https://" + config.server.host + ":" + config.server.ssl + "/hex/" + req.url;
        res.writeHead(307, {'Location': red});
        res.end();
    }
    if (req.url.indexOf("/swat") == 0 ) {
        req.url = req.url.replace("/swat", "");
 	if (req.url.indexOf("/..") >=0 ) {
            console.log(".. not allowed: " + req.url);
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end();
	}
        return serveFile(req, res, '/data/home/galaxy/hexProxy/');
    }
    /*if (req.url.indexOf("/public") == 0)
        return serveFile(req, res, '/data/public/');*/

    var urlPath = req.url.split("/");
    var firstPart = "never match";
    if (urlPath && urlPath.length >= 2 && urlPath[1].length > 0)
        firstPart = urlPath[1];

    var sla = "/" + firstPart;

    if (sla in auth && auth[sla]) {
        mustLogin(firstPart, req, res);
    } else
        forward(req, res);
  } // main

  if (config.server.ssl)
      server = require('https').createServer(readSSLcredentials(), main);
  else
      server = require('http').createServer(main);

  var httpProxy = require('http-proxy')
  var proxy = httpProxy.createProxy({ ws : true });

  server.on('upgrade',function(req,res){
    var target = getTarget(req);
    proxy.ws(req, res, {
      target: target,
    },function(e){
      log_error(e, req);
	console.log("WS ERROR", e);
	/*
	res.writeHead(500, {
	  'Content-Type': 'text/plain'
	});
	res.end('Something went wrong. And we are reporting a custom error message.');
	*/
    });
  })

  if (config.server.ssl) {
      console.log("ssl listening on", config.server.ssl);
      server.listen(config.server.ssl)
  } else {
      console.log("nonssl listening on", config.server.nonssl);
      server.listen(config.server.nonssl)
  }

};

splitHostPort = function(s) {
  var parts, ret;
  parts = s.split(':', 2);
  ret = {
    host: parts[0]
  };
  if (parts.length > 1) {
    ret.port = parseInt(parts[1], 10);
  } else {
    ret.port = 80;
  }
  return ret;
};

configApp = function(path) {
  try {
    config = toml.parse(fs.readFileSync(path));
  } catch (_error) {
    console.log("Failed to parse configuration file " + path);
    return process.exit(1);
  }

  var appName, ca, link, menu, menuItem;
  menu = [];
  routes = {};
  apps = {};
  auth = {};
  final = config.final.port

  for (appName in config.apps) {
    var ca = config.apps[appName];
    routes[ca.route] = ca;
    apps[ca.route] = ca;
    auth[ca.route] = ca.auth;
  }
};

serveMenu = function(req, res) {
  var menu = [];
  var routeHacks = "";
  for (appName in config.apps) {
    var ca = config.apps[appName];
    menuItem = String(ca.menuItem);
    if (menuItem === null) {
      menuItem = ca.route;
    }
    menuItem = menuItem.replace(/\ /g, " ");
    href = ca.path ? ca.path : ca.route;

    link = "" + menuItem + "";
    routeHacks += "if (Router && !('" + ca.route + "' in  Router.routes)) Router.route('" + ca.route + "', function () {}, {where: 'server'});\n";
    if (ca.menuItem) {
      if (ca.menuPosition !== void 0) {
        menu.splice(ca.menuPosition, 0, link);
      } else {
        menu.push(link);
      }
    }
  }

  var text = String(menuFile).replace("LIST", (menu.map(function(a) {
    return "
" + a + "

";
  })).join(''));

  text += "";

  res.writeHead(200);
  res.write(text, "binary");
  return res.end();
};

serveScript = function(req, res, script) {
  res.writeHead(200, {'Content-Type': 'application/x-javascript'});
  res.write(script, "binary");
  return res.end();
};

var mimeTypes = {
    "html": "text/html",
    "jpeg": "image/jpeg",
    "jpg": "image/jpeg",
    "png": "image/png",
    "js": "text/javascript",
    "css": "text/css"};

function serveFile(req, res, dir) {
    var uri = url.parse(req.url).pathname;
    // console.log("serveFile uri", uri);
    if (uri == null || uri == "" || uri == "/")
       uri = "index.html"
    var filename = path.join(dir, uri);
    fs.exists(filename, function(exists) {
        if(!exists) {
            console.log("not exists: " + filename);
            res.writeHead(404, {'Content-Type': 'text/plain'});
            res.end();
            return;
        }
        var mimeType = mimeTypes[path.extname(filename).split(".")[1]];
        res.writeHead(200, mimeType);

        var fileStream = fs.createReadStream(filename);
        fileStream.pipe(res);

    }); //end fs.exists

};

console.log("watching", args[0]);

fs.watchFile(args[0], run);
fs.watchFile("/data/MedBook/Gateway/menu.html", readMenu);
fs.watchFile(postScriptFilename, readPostScript);

function log_error(e,req){
  if(e){
    /*
    console.log("log_error");
    console.error(e.message);
    console.log(req.headers.host,'-->');
    console.log('-----');
    */
  }
}

run();
<|endoftext|>


<commit_before>$(function(){

    var typedElement = $("#element span#header");

    var default_org = ["Hi^2000", "I'm Victor Niu.", "My friends call me Victor, because that is my name.", "This website is still under construction...", "But please check out my stuff :D"," Just head over to the lower right corner.", "...^1000", "......^5000", "Why are you still here?", "Ok I guess if you want to stay you can.", "I mean there's not much else for me to say.", "And there's going to be nothing at the end of this.", "You'll just be wasting your time.", "...^2000
....^2000
.....", "Well if you insist,", "I guess I can re-introduce myself."];

    var default_ = ["Hi^2000", "You've reached Victor Niu's website", "He is not here right now...", "But I'm here!", "If you're wondering about the normal stuff, ","Github, Resume, LinkedIn, that stuff you know?", "Just check in the bottom right corner where all the nifty icons are!", "Now if you have any questions I'd be happy to take them!", "If you just head down to the bottom, you can type things for me", "For example, you can ask me about Victor's projects", "or what he is currently up to right now", "Go ahead and try it out!", "...^2000
....^2000
.....", "You're still here?", "If you need help, just type help"]

    var help =  ["So you need help huh", "fine"]

    $("#input").on("keypress", function(e){
            if(e.keyCode == 13){
            e.preventDefault();
            var command = this.innerHTML;
            this.innerHTML = "";
            runCommand(command);

         }

     });

//    function runCommand(command){
//        console.log("command - " + command);
//        typedElement.typed({
//            strings: help,
//            typeSpeed: 10,
//            backDelay: 1500,
//    //        loop: true,
//            loopCount: false,
//
//        });
//
//
//    }

    /*
    To add:
    Who am I?
    Projects
    Politics
    help
    */

    typedElement.typed({
        strings: default_org,
        typeSpeed: 10,
        backDelay: 1500,
//        loop: true,
        loopCount: false,

    });

});<commit_msg>fixed a bug that's been there forever crap<commit_after>$(function(){

    var typedElement = $("#element span#header");

    var default_org = ["Hi^2000", "I'm Victor Niu.", "My friends call me Victor, because that is my name.", "This website is still under construction...", "But please check out my stuff :D"," Just head over to the lower right corner.", "...^1000", "......^5000", "Why are you still here?", "Ok I guess if you want to stay you can.", "I mean there's not much else for me to say.", "And there's going to be nothing at the end of this.", "You'll just be wasting your time.", "...^2000
....^2000
.....", "Well if you insist,", "I guess I can re-introduce myself."];

    var default_ = ["Hi^2000", "You've reached Victor Niu's website", "He is not here right now...", "But I'm here!", "If you're wondering about the normal stuff, ","Github, Resume, LinkedIn, that stuff you know?", "Just check in the bottom right corner where all the nifty icons are!", "Now if you have any questions I'd be happy to take them!", "If you just head down to the bottom, you can type things for me", "For example, you can ask me about Victor's projects", "or what he is currently up to right now", "Go ahead and try it out!", "...^2000
....^2000
.....", "You're still here?", "If you need help, just type help"]

    var help =  ["So you need help huh", "fine"]

    $("#input").on("keypress", function(e){
            if(e.keyCode == 13){
            e.preventDefault();
            var command = this.innerHTML;
            this.innerHTML = "";
            runCommand(command);

         }

     });

//    function runCommand(command){
//        console.log("command - " + command);
//        typedElement.typed({
//            strings: help,
//            typeSpeed: 10,
//            backDelay: 1500,
//    //        loop: true,
//            loopCount: false,
//
//        });
//
//
//    }

    /*
    To add:
    Who am I?
    Projects
    Politics
    help
    */

    typedElement.typed({
        strings: default_org,
        typeSpeed: 10,
        backDelay: 1500,
        loop: true,
        loopCount: false,

    });

});
<|endoftext|>