<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;
		}
	},
	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'){
						$('div[data-id="' + folderid + '"] > ul').append(jsondata.data.listfolder);
						setupFeedList();
						OC.dialogs.confirm(t('news', 'Do you want to add another folder?'), t('news', 'Folder added!'), function(answer) {
							if(!answer) {
								$('#addfolder_dialog').dialog('destroy').remove();
							}
						});
					} 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) {
					var rightcontent = $('div.rightcontent');
					var shownfeedid = rightcontent.attr('data-id');
					$.post(OC.filePath('news', 'ajax', 'deletefolder.php'),{'folderid':folderid, 'shownfeedid':shownfeedid},function(jsondata){
						if(jsondata.status == 'success'){
							$('div.collapsable_container[data-id="' + jsondata.data.folderid + '"]').remove();
							if(jsondata.data.part_items) {
								rightcontent.empty();
								rightcontent.html(jsondata.data.part_items);
							}
						}
						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'){
						$('div[data-id="' + folderid + '"] > ul').append(jsondata.data.listfeed);
						setupFeedList();
						OC.dialogs.confirm(t('news', 'Do you want to add another feed?'), t('news', 'Feed added!'), function(answer) {
							if(!answer) {
								$('#addfeed_dialog').dialog('destroy').remove();
								var rightcontent = $('div.rightcontent');
								rightcontent.empty();
								rightcontent.html(jsondata.data.part_items);
								setupRightContent();
							}
						});
					} 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'){
							$('li.feeds_list[data-id="'+jsondata.data.feedid+'"]').remove();
							var rightcontent = $('div.rightcontent');
							if(rightcontent.attr('data-id') == feedid) {
								rightcontent.empty();
								rightcontent.html(jsondata.data.part_items);
							}
						}
						else{
							OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
						}
					});
				}
			});
			return false;
		},
		markItem:function(itemid, feedid) {
			var currentitem = $('#rightcontent [data-id="' + itemid + '"]');
			if (currentitem.hasClass('title_unread')) {
				$.post(OC.filePath('news', 'ajax', 'markitem.php'),{'itemid':itemid},function(jsondata){
					if(jsondata.status == 'success'){
						currentitem.removeClass('title_unread');
						currentitem.addClass('title_read');

						// decrement counter
						var counterplace = $('.feeds_list[data-id="'+feedid+'"]').find('#unreaditemcounter');
						var oldcount = counterplace.html();
						counterplace.empty();
						if (oldcount <= 1) {
							counterplace.removeClass('nonzero').addClass('zero');
						}
						else {
							counterplace.append(--oldcount);
						}
						//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.update(feeds[i]['id'], feeds[i]['url'], feeds[i]['folderid']);
					}
				}
				else {
					//TODO:handle error case
				}
			});
		},
		update:function(feedid, feedurl, folderid) {
			var counterplace = $('.feeds_list[data-id="'+feedid+'"]').find('#unreaditemcounter');
			var oldcount = counterplace.html();
			counterplace.removeClass();
			counterplace.html('');
			$.post(OC.filePath('news', 'ajax', 'updatefeed.php'),{'feedid':feedid, 'feedurl':feedurl, 'folderid':folderid},function(jsondata){
				if(jsondata.status == 'success'){
					var newcount = jsondata.data.unreadcount;
					if (newcount > 0) {
						counterplace.addClass('nonzero');
						counterplace.html(newcount);
					}
					else {
						counterplace.addClass('zero');
						counterplace.html('');
					}
				}
				else{
				  	if (oldcount > 0) {
						counterplace.addClass('nonzero');
						counterplace.html(oldcount);
					}
				}

			});
		}
	}
}

function setupFeedList() {
	$('.collapsable').click(function(){
		$(this).parent().children('ul').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();
}

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

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

$(document).ready(function(){

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

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

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

	$('#settingsbtn').on('click keydown', function() {
		try {
			OC.appSettings({appid:'news', loadJS:true});
		} catch(e) {
			alert(e);
		}
	});

	setupFeedList();
	setupRightContent();

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

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

<commit_msg>removes confirmation dialog when adding a folder<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'){
						$(dialogtype).dialog({
							dialogClass:'dialog',
							minWidth: 600,
							close: function(event, ui) {
								$(this).dialog('destroy').remove();
							}
						}).css('overflow','visible');
					} else {
						alert(jsondata.data.message);
					}
				});
			}
			return false;
		}
	},
	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'){
						$('div[data-id="' + folderid + '"] > ul').append(jsondata.data.listfolder);
						setupFeedList();
						//OC.dialogs.confirm(t('news', 'Do you want to add another folder?'), t('news', 'Folder added!'), function(answer) {
						//	if(!answer) {
								$('#addfolder_dialog').dialog('destroy').remove();
						//	}
						//});
					} 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) {
					var rightcontent = $('div.rightcontent');
					var shownfeedid = rightcontent.attr('data-id');
					$.post(OC.filePath('news', 'ajax', 'deletefolder.php'),{'folderid':folderid, 'shownfeedid':shownfeedid},function(jsondata){
						if(jsondata.status == 'success'){
							$('div.collapsable_container[data-id="' + jsondata.data.folderid + '"]').remove();
							if(jsondata.data.part_items) {
								rightcontent.empty();
								rightcontent.html(jsondata.data.part_items);
							}
						}
						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'){
						$('div[data-id="' + folderid + '"] > ul').append(jsondata.data.listfeed);
						setupFeedList();
						OC.dialogs.confirm(t('news', 'Do you want to add another feed?'), t('news', 'Feed added!'), function(answer) {
							if(!answer) {
								$('#addfeed_dialog').dialog('destroy').remove();
								var rightcontent = $('div.rightcontent');
								rightcontent.empty();
								rightcontent.html(jsondata.data.part_items);
								setupRightContent();
							}
						});
					} 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'){
							$('li.feeds_list[data-id="'+jsondata.data.feedid+'"]').remove();
							var rightcontent = $('div.rightcontent');
							if(rightcontent.attr('data-id') == feedid) {
								rightcontent.empty();
								rightcontent.html(jsondata.data.part_items);
							}
						}
						else{
							OC.dialogs.alert(jsondata.data.message, t('news', 'Error'));
						}
					});
				}
			});
			return false;
		},
		markItem:function(itemid, feedid) {
			var currentitem = $('#rightcontent [data-id="' + itemid + '"]');
			if (currentitem.hasClass('title_unread')) {
				$.post(OC.filePath('news', 'ajax', 'markitem.php'),{'itemid':itemid},function(jsondata){
					if(jsondata.status == 'success'){
						currentitem.removeClass('title_unread');
						currentitem.addClass('title_read');

						// decrement counter
						var counterplace = $('.feeds_list[data-id="'+feedid+'"]').find('#unreaditemcounter');
						var oldcount = counterplace.html();
						counterplace.empty();
						if (oldcount <= 1) {
							counterplace.removeClass('nonzero').addClass('zero');
						}
						else {
							counterplace.append(--oldcount);
						}
						//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.update(feeds[i]['id'], feeds[i]['url'], feeds[i]['folderid']);
					}
				}
				else {
					//TODO:handle error case
				}
			});
		},
		update:function(feedid, feedurl, folderid) {
			var counterplace = $('.feeds_list[data-id="'+feedid+'"]').find('#unreaditemcounter');
			var oldcount = counterplace.html();
			counterplace.removeClass();
			counterplace.html('');
			$.post(OC.filePath('news', 'ajax', 'updatefeed.php'),{'feedid':feedid, 'feedurl':feedurl, 'folderid':folderid},function(jsondata){
				if(jsondata.status == 'success'){
					var newcount = jsondata.data.unreadcount;
					if (newcount > 0) {
						counterplace.addClass('nonzero');
						counterplace.html(newcount);
					}
					else {
						counterplace.addClass('zero');
						counterplace.html('');
					}
				}
				else{
				  	if (oldcount > 0) {
						counterplace.addClass('nonzero');
						counterplace.html(oldcount);
					}
				}

			});
		}
	}
}

function setupFeedList() {
	$('.collapsable').click(function(){
		$(this).parent().children('ul').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();
}

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

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

$(document).ready(function(){

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

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

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

	$('#settingsbtn').on('click keydown', function() {
		try {
			OC.appSettings({appid:'news', loadJS:true});
		} catch(e) {
			alert(e);
		}
	});

	setupFeedList();
	setupRightContent();

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

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

<|endoftext|>


<commit_before>"use strict";

var AnyfetchClient = require('anyfetch');
var fs = require('fs');
var path = require('path');
var async = require('async');

var uploadFile = function(dir, filePath, accessToken, baseIdentifier, creationDate, cb) {
  var anyfetch = new AnyfetchClient();
  anyfetch.setAccessToken(accessToken);

  // Send a document to anyFetch
  var document = {
    identifier: baseIdentifier + filePath,
    document_type: 'file',
    creation_date: creationDate
  };

  var fileConfig = function() {
    // Wrap this in a function to avoid creating the stream before reading it.
    return {
      file: fs.createReadStream(dir + filePath),
      filename: path.basename(dir + filePath),
    };
  };

  anyfetch.sendDocumentAndFile(document, fileConfig, function(err) {
    console.log("UPPING ", dir + filePath);
    if(err) {
      console.warn(err);
    }
    cb();
  });
};

var deleteFile = function(filePath, accessToken, baseIdentifier, cb) {
  var anyfetch = new AnyfetchClient();
  anyfetch.setAccessToken(accessToken);

  anyfetch.deleteDocument(baseIdentifier + filePath, function(err) {
    console.log("DELETING", filePath);
    console.warn(err);
    if(err) {
      console.warn(err);
    }
    cb();
  });
};

var uploadQueue = async.queue(function worker(task, cb) {
  uploadFile(task.dir || "", task.filePath, task.accessToken, task.baseIdentifier, task.creationDate, cb);
}, 4);

var deleteQueue = async.queue(function worker(task, cb) {
  deleteFile(task.filePath, task.accessToken, task.baseIdentifier, cb);
}, 4);

module.exports.pushToUploadQueue = function pushToUploadQueue(tasks) {
  uploadQueue.push(tasks);
};

module.exports.pushToDeleteQueue = function pushToDeleteQueue(tasks) {
  deleteQueue.push(tasks);
};

module.exports.uploadFile = uploadFile;
module.exports.deleteFile = deleteFile;<commit_msg>exit on API error<commit_after>"use strict";

var AnyfetchClient = require('anyfetch');
var fs = require('fs');
var path = require('path');
var async = require('async');

var uploadFile = function(dir, filePath, accessToken, baseIdentifier, creationDate, cb) {
  var anyfetch = new AnyfetchClient();
  anyfetch.setAccessToken(accessToken);

  // Send a document to anyFetch
  var document = {
    identifier: baseIdentifier + filePath,
    document_type: 'file',
    creation_date: creationDate
  };

  var fileConfig = function() {
    // Wrap this in a function to avoid creating the stream before reading it.
    return {
      file: fs.createReadStream(dir + filePath),
      filename: path.basename(dir + filePath),
    };
  };

  anyfetch.sendDocumentAndFile(document, fileConfig, function(err) {
    console.log("UPPING ", dir + filePath);
    if(err) {
      console.warn(err);
      process.exit(1);
    }
    cb();
  });
};

var deleteFile = function(filePath, accessToken, baseIdentifier, cb) {
  var anyfetch = new AnyfetchClient();
  anyfetch.setAccessToken(accessToken);

  anyfetch.deleteDocument(baseIdentifier + filePath, function(err) {
    console.log("DELETING", filePath);
    console.warn(err);
    if(err) {
      console.warn(err);
      process.exit(1);
    }
    cb();
  });
};

var uploadQueue = async.queue(function worker(task, cb) {
  uploadFile(task.dir || "", task.filePath, task.accessToken, task.baseIdentifier, task.creationDate, cb);
}, 4);

var deleteQueue = async.queue(function worker(task, cb) {
  deleteFile(task.filePath, task.accessToken, task.baseIdentifier, cb);
}, 4);

module.exports.pushToUploadQueue = function pushToUploadQueue(tasks) {
  uploadQueue.push(tasks);
};

module.exports.pushToDeleteQueue = function pushToDeleteQueue(tasks) {
  deleteQueue.push(tasks);
};

module.exports.uploadFile = uploadFile;
module.exports.deleteFile = deleteFile;<|endoftext|>


<commit_before>// game.js
// ========
"use strict";
module.exports = {
  map: function(size) {
   this.size = size || 70;
   function tile(properties) {
     //constructor
       if (properties.hasOwnProperty("x") && properties.hasOwnProperty("y")) {
           if(properties.x >= 0 && properties.y >= 0) {
             this.x = properties.x || 0;
             this.y = properties.y || 0;
           }
       }
     if (properties.hasOwnProperty("color")) {
         this.color = properties.color || "#ffffff";
     }
     if (properties.hasOwnProperty("kind")) {
       this.kind = null;
       switch (properties.Type) {
         case "floor":
         //floor
           this.kind = 0;
           break;
         default:
         //wall
         this.kind = 1;

       }
     }
     //Construct the list of items and players on the tile
     if (properties.hasOwnProperty("objects")) {
       this.objects =  new Array();
       if (Array.isArray(properties.objects)) {
           for (var i = 0; i < properties.objects.length; i++) {
             this.objects.push(properties.objects[i]);
           }
       }
     }
   }
   tile.prototype.getTile = function () {
    var objectKey = "__NONE__";
    for (var key in this.objects) {
      console.log(this.objects[key]);
        objectKey =  this.objects[key];
    }

      return {
            "objects":objectKey,
            "color": this.color
      }
   };
   //create map
  this.mapArray = new Array();
   for (var i = 0; i < size; i++) {
     this.mapArray[i] =  new Array();
     for (var l = 0; l < size; l++) {
       var tileType = 0;
       var colorVal = "#ffffff";
       if ((i === 0) || (l === 0) || (i === this.size-1) || (l === this.size-1) ) {
         tileType = 1;
         colorVal = "#000000";
       }
      this.mapArray[i][l] = new tile({
         "x": i,
         "y": l,
         "color": colorVal,
         "objects": {},
         "kind": tileType
       });
      console.log(tileType);
     }
   }
 }
};
module.exports.map.prototype.getAbove = function (x,y) {
  console.log(this.mapArray.length,x,y)
 /*if (y > this.mapArray.length) {
    return this.mapArray[x][0];
  }
  if (y < 0) {
    return this.mapArray[x][this.mapArray.length];
  } else {

  }*/
  return this.mapArray[x][y-1];
};
module.exports.map.prototype.getBelow = function (x,y) {
       return this.mapArray[x][y+1];
};
module.exports.map.prototype.getRight = function (x,y) {
      return this.mapArray[x+1][y];
};
module.exports.map.prototype.getLeft = function (x,y) {
      return this.mapArray[x-1][y];
};
module.exports.map.prototype.getTile = function (x,y) {
return this.mapArray[x][y];
};
module.exports.map.prototype.setTile = function (x,y,element) {
 this.mapArray[x][y] = element;
};
module.exports.map.prototype.setPlayer = function (x,y,player) {
    function getRandomColor() {
     var letters = '0123456789ABCDEF'.split('');
     var color = '#';
     for (var i = 0; i < 6; i++ ) {
         color += letters[Math.floor(Math.random() * 16)];
     }
     return color;
   }
 this.mapArray[x][y].objects[String(player)] = getRandomColor();
};
module.exports.map.prototype.movePlayer = function (x,y,direction,player) {
  console.log(x,y,direction,player);
  console.log(this.mapArray[x][y].objects);
  //first verify that player is on the tile
  if (this.mapArray[x][y].objects.hasOwnProperty(String(player.username))) {
    switch(direction) {
    case "up":
    if( this.mapArray[x][y-1].kind != 1) {
     this.mapArray[x][y-1].objects[String(player.username)] = this.mapArray[x][y].objects[String(player.username)];
     console.log(this.mapArray[x][y-1].objects);
     delete this.mapArray[x][y].objects[String(player.username)]; // remove reference to player on previous tile

   }
        break;
    case "down":
    if( this.mapArray[x][y+1].kind != 1) {
     this.mapArray[x][y+1].objects[String(player.username)] = this.mapArray[x][y].objects[String(player.username)];
     delete this.mapArray[x][y].objects[String(player.username)]; // remove reference to player on previous tile

   }
        break;
    default:

}
  }
    console.log(x,y,direction,player);
};
module.exports.map.prototype.printMap = function() {
var mapVals = new Array();
  for (var i = 0; i < this.mapArray.length; i++) {
    mapVals[i] = [];
      for (var l = 0; l < this.mapArray[i].length; l++) {

            mapVals[i][l] = this.mapArray[i][l].getTile();

      }
  }
  return mapVals;
};
<commit_msg>test1<commit_after>// game.js
// ========
"use strict";
module.exports = {
  map: function(size) {
   this.size = size || 70;
   function tile(properties) {
     //constructor
       if (properties.hasOwnProperty("x") && properties.hasOwnProperty("y")) {
           if(properties.x >= 0 && properties.y >= 0) {
             this.x = properties.x || 0;
             this.y = properties.y || 0;
           }
       }
     if (properties.hasOwnProperty("color")) {
         this.color = properties.color || "#ffffff";
     }
     if (properties.hasOwnProperty("kind")) {
       this.kind = null;
       switch (properties.Type) {
         case "floor":
         //floor
           this.kind = 0;
           break;
         default:
         //wall
         this.kind = 1;

       }
     }
     //Construct the list of items and players on the tile
     if (properties.hasOwnProperty("objects")) {
       this.objects =  new Array();
       if (Array.isArray(properties.objects)) {
           for (var i = 0; i < properties.objects.length; i++) {
             this.objects.push(properties.objects[i]);
           }
       }
     }
   }
   tile.prototype.getTile = function () {
    var objectKey = "__NONE__";
    for (var key in this.objects) {
      console.log(this.objects[key]);
        objectKey =  this.objects[key];
    }

      return {
            "objects":objectKey,
            "color": this.color
      }
   };
   //create map
  this.mapArray = new Array();
   for (var i = 0; i < size; i++) {
     this.mapArray[i] =  new Array();
     for (var l = 0; l < size; l++) {
       var tileType = 0;
       var colorVal = "#ffffff";
       if ((i === 0) || (l === 0) || (i === this.size-1) || (l === this.size-1) ) {
         tileType = 1;
         colorVal = "#000000";
       }
      this.mapArray[i][l] = new tile({
         "x": i,
         "y": l,
         "color": colorVal,
         "objects": {},
         "kind": tileType
       });
      console.log(tileType);
     }
   }
 }
};
module.exports.map.prototype.getAbove = function (x,y) {
  console.log(this.mapArray.length,x,y)
 /*if (y > this.mapArray.length) {
    return this.mapArray[x][0];
  }
  if (y < 0) {
    return this.mapArray[x][this.mapArray.length];
  } else {

  }*/
  return this.mapArray[x][y-1];
};
module.exports.map.prototype.getBelow = function (x,y) {
       return this.mapArray[x][y+1];
};
module.exports.map.prototype.getRight = function (x,y) {
      return this.mapArray[x+1][y];
};
module.exports.map.prototype.getLeft = function (x,y) {
      return this.mapArray[x-1][y];
};
module.exports.map.prototype.getTile = function (x,y) {
return this.mapArray[x][y];
};
module.exports.map.prototype.setTile = function (x,y,element) {
 this.mapArray[x][y] = element;
};
module.exports.map.prototype.setPlayer = function (x,y,player) {
    function getRandomColor() {
     var letters = '0123456789ABCDEF'.split('');
     var color = '#';
     for (var i = 0; i < 6; i++ ) {
         color += letters[Math.floor(Math.random() * 16)];
     }
     return color;
   }
 this.mapArray[x][y].objects[String(player)] = getRandomColor();
};
module.exports.map.prototype.movePlayer = function (x,y,direction,player) {
  console.log(x,y,direction,player);
  console.log(this.mapArray[x][y].objects);
  //first verify that player is on the tile
  if (this.mapArray[x][y].objects.hasOwnProperty(String(player.username))) {
    switch(direction) {
    case "up":
    if( this.mapArray[x][y-1].kind != 1) {
      console.log(this.mapArray[x][y-1].kind != 1);
     this.mapArray[x][y-1].objects[String(player.username)] = this.mapArray[x][y].objects[String(player.username)];
     console.log(this.mapArray[x][y-1].objects);
     delete this.mapArray[x][y].objects[String(player.username)]; // remove reference to player on previous tile

   }
        break;
    case "down":
    if( this.mapArray[x][y+1].kind != 1) {
     this.mapArray[x][y+1].objects[String(player.username)] = this.mapArray[x][y].objects[String(player.username)];
     delete this.mapArray[x][y].objects[String(player.username)]; // remove reference to player on previous tile

   }
        break;
    default:

}
  }
    console.log(x,y,direction,player);
};
module.exports.map.prototype.printMap = function() {
var mapVals = new Array();
  for (var i = 0; i < this.mapArray.length; i++) {
    mapVals[i] = [];
      for (var l = 0; l < this.mapArray[i].length; l++) {

            mapVals[i][l] = this.mapArray[i][l].getTile();

      }
  }
  return mapVals;
};
<|endoftext|>


<commit_before>var News = {
  newsMinLimit: 1,
  newsMaxLimit: 15,
  msgNewsLimit: 'Nyhetsantall må være et tall mellom '+this.newsMinLimit+' og '+this.newsMaxLimit,
  msgConnectionError: 'Frakoblet fra feed: ',
  msgUnsupportedFeed: 'Feeden støttes ikke',
  msgCallbackRequired: 'Callback er påkrevd, legg resultatene inn i DOMen',

  debug: 1,

  feeds: {
    // Linjeforeninger
    'berg': 'http://bergstud.no/feed/',
    'delta': 'http://org.ntnu.no/delta/wp/?feed=rss2',
    'emil': 'http://emilweb.no/feed/',
    'online': 'https://online.ntnu.no/feeds/news/',
    'nabla': 'http://nabla.no/feed/',
    'spanskrøret': 'http://spanskroret.no/feed/',
    // Medier
    'dusken': 'http://dusken.no/feed/',
    'universitetsavisa': 'http://www.universitetsavisa.no/?service=rss',
    // Store studentorganisasjoner
    'samfundet': 'http://www.samfundet.no/arrangement/rss',
    // Studentdemokrati
    'studenttinget': 'http://www.studenttinget.no/feed/',
    'velferdstinget': 'http://www.velferdstinget.no/feed/rss/',
    // NTNU
    'ntnu': 'https://www.retriever-info.com/feed/2002900/generell_arkiv166/index.xml',
    'rektoratet': 'http://www.ntnu.no/blogger/rektoratet/feed/',
  },

  images: {
    // Linjeforeninger
    'berg': 'img/logo-sponsor-placeholder.png',
    'delta': 'img/logo-sponsor-placeholder.png',
    'emil': 'img/logo-sponsor-placeholder.png',
    'online': 'img/logo-sponsor-placeholder.png',
    'nabla': 'img/logo-sponsor-placeholder.png',
    'spanskrøret': 'img/logo-sponsor-placeholder.png',
    // Medier
    'dusken': 'img/logo-sponsor-placeholder.png',
    'universitetsavisa': 'img/logo-sponsor-placeholder.png',
    // Store studentorganisasjoner
    'samfundet': 'img/logo-sponsor-placeholder.png',
    // Studentdemokrati
    'studenttinget': 'img/logo-sponsor-placeholder.png',
    'velferdstinget': 'img/logo-sponsor-placeholder.png',
    // NTNU
    'ntnu': 'img/logo-sponsor-placeholder.png',
    'rektoratet': 'img/logo-sponsor-placeholder.png',
  }

  // 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(feedName, limit, callback) {
    if (this.feeds[feedName] === undefined) {
      if (this.debug) console.log('ERROR:', this.msgUnsupportedFeed);
      callback(this.msgUnsupportedFeed);
      return;
    }
    if (isNaN(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;
    }

    feedName = feedName.toLowerCase();
    var rssUrl = this.feeds[feedName];

    var self = this;
    $.ajax({
      url: rssUrl, // permission to use url granted in manifest.json
      dataType: 'xml',
      success: function(xml) {
        // ls.lastResponseData = xmlstring;
        self.parseFeed(xml, feedName, limit, callback);
      },
      error: function(jqXHR, text, err) {
        if (self.debug) console.log('ERROR:', self.msgConnectionError, feedName);
        callback(self.msgConnectionError);
      },
    });
  },

  parseFeed: function(xml, feedName, limit, callback) {
    var items = [];
    var self = this;
    var count = 0;
    $(xml).find('item').each( function() {
      if (count++ < limit) {
        var item = self.parseItem(this, feedName);
        items.push(item);
      }
    });
    callback(items);
  },

  // NOT DONE YET ///////////////////////////////////////////////////////////////////
  // todo: this function only handles the online-feed, make sure it handles all feeds
  parseItem: function(item, feedName) {
    var post = {};
    post.title = $(item).find("title").text();
    post.link = $(item).find("link").text();
    post.description = $(item).find("description").text();
    post.creator = $(item).find("dc:creator").text();

    post.date = $(item).find("pubDate").text().substr(5, 11); /////////////////////
    post.image = this.images[feedName];

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

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

    // Remove excessive whitespace...
    if (post.description.match(/<\w+>|<\/\w+>/g) !== null) { // Check if string contains markup
      // ...and ludicrous formatting (HTML)
      post.description = $.trim($(post.description).text());
    }
    else {
      post.description = post.description.trim();
    }

    // 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();
      });
    }
    // Didn't find a creator, set the feedname as creator
    if (post.creator.length == 0) {
      post.creator = feedName.capitalize();
    }
    // Abbreviate long creator names
    post.creator = this.abbreviateName(post.creator);

    // 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;
  },

  // NOT DONE YET ///////////////////////////////////////////////////////////////////
  // todo: this function only handles the online-feed, make sure it handles all feeds
  unreadCount: function(xmlstring) {

    return; //

    var unread_count = 0;

    // Parse the feed
    var xmldoc = $.parseXML(xmlstring);
    $xml = $(xmldoc);
    var items = $xml.find("item");
    var idList = []; // New || Updated

    // Count feed items
    items.each( function(index, element) {

      var id = $(element).find("guid").text().split('/')[4];

      // Counting...
      if (id != localStorage.mostRecentRead) {
        unread_count++;
        idList.push(id); // New || Updated
        // Send a desktop notification about the first unread element
        if (unread_count == 1) {
          if (localStorage.lastNotified != id) {
            this.showNotification(element);
          }
          localStorage.mostRecentUnread = id;
        }
      }
      // All counted :)
      else {
        if (unread_count == 0) {
          if (this.debug) console.log('no new posts');
          Browser.setBadgeText('');
        }
        else if (unread_count >= this.maxNewsAmount) {
          if (this.debug) console.log(this.maxNewsAmount + '+ unread posts');
          Browser.setBadgeText(this.maxNewsAmount + '+');
        }
        else {
          if (this.debug) console.log('1-' + (this.maxNewsAmount - 1) + ' unread posts');
          Browser.setBadgeText(String(unread_count));
        }
        localStorage.unreadCount = unread_count;
        localStorage.mostRecentIdList = JSON.stringify(idList); // New || Updated
        return false;
      }

      // Stop counting if unread number is greater than 9
      if (index > (this.maxNewsAmount - 1)) { // Remember index is counting 0
        if (this.debug) console.log(this.maxNewsAmount + '+ unread posts (stopped counting)');
        Browser.setBadgeText(this.maxNewsAmount + '+');
        localStorage.unreadCount = this.maxNewsAmount;
        // New or updated?
        localStorage.mostRecentIdList = JSON.stringify(idList); // New || Updated
        return false;
      }
    });
  },

  showNotification: function(item) {
    if (localStorage.showNotifications == 'true') {
      var post = this.parseItem(item);
      // Remember this
      localStorage.lastNotified = post.link;
      // Get content
      localStorage.notificationTitle = post.title;
      localStorage.notificationLink = post.link;
      localStorage.notificationDescription = post.description;
      localStorage.notificationCreator = post.creator;
      // 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;
  },

  // Organization specific functions

  online_getImage: function(link, callback) {
    var id = link.split('/')[4]; // id is stored in the link
    var image = 'undefined';
    var api = 'https://online.ntnu.no/api/f5be90e5ec1d2d454ae9/news_image_by_id/';
    $.getJSON(api + id, function(json) {
      if (json['online_news_image']) {
        image = json['online_news_image']['0']['image'];
        callback(link, image);
      }
      else {
        image = this.images['online'];
        if (this.debug) console.log('ERROR: no image exists for id: ' + id);
        callback(link, image);
      }
    })
    .error(function() {
      image = this.images['online'];
      if (this.debug) console.log('ERROR: couldn\'t connect API to get image links, returning default image');
      callback(link, image);
    });
  },

}
<commit_msg>news: finishing date support<commit_after>var News = {
  newsMinLimit: 1,
  newsMaxLimit: 15,
  msgNewsLimit: 'Nyhetsantall må være et tall mellom '+this.newsMinLimit+' og '+this.newsMaxLimit,
  msgConnectionError: 'Frakoblet fra feed: ',
  msgUnsupportedFeed: 'Feeden støttes ikke',
  msgCallbackRequired: 'Callback er påkrevd, legg resultatene inn i DOMen',

  debug: 1,

  feeds: {
    // Linjeforeninger
    'berg': 'http://bergstud.no/feed/',
    'delta': 'http://org.ntnu.no/delta/wp/?feed=rss2',
    'emil': 'http://emilweb.no/feed/',
    'online': 'https://online.ntnu.no/feeds/news/',
    'nabla': 'http://nabla.no/feed/',
    'spanskrøret': 'http://spanskroret.no/feed/',
    // Medier
    'dusken': 'http://dusken.no/feed/',
    'universitetsavisa': 'http://www.universitetsavisa.no/?service=rss',
    // Store studentorganisasjoner
    'samfundet': 'http://www.samfundet.no/arrangement/rss',
    // Studentdemokrati
    'studenttinget': 'http://www.studenttinget.no/feed/',
    'velferdstinget': 'http://www.velferdstinget.no/feed/rss/',
    // NTNU
    'ntnu': 'https://www.retriever-info.com/feed/2002900/generell_arkiv166/index.xml',
    'rektoratet': 'http://www.ntnu.no/blogger/rektoratet/feed/',
  },

  images: {
    // Linjeforeninger
    'berg': 'img/logo-sponsor-placeholder.png',
    'delta': 'img/logo-sponsor-placeholder.png',
    'emil': 'img/logo-sponsor-placeholder.png',
    'online': 'img/logo-sponsor-placeholder.png',
    'nabla': 'img/logo-sponsor-placeholder.png',
    'spanskrøret': 'img/logo-sponsor-placeholder.png',
    // Medier
    'dusken': 'img/logo-sponsor-placeholder.png',
    'universitetsavisa': 'img/logo-sponsor-placeholder.png',
    // Store studentorganisasjoner
    'samfundet': 'img/logo-sponsor-placeholder.png',
    // Studentdemokrati
    'studenttinget': 'img/logo-sponsor-placeholder.png',
    'velferdstinget': 'img/logo-sponsor-placeholder.png',
    // NTNU
    'ntnu': 'img/logo-sponsor-placeholder.png',
    'rektoratet': 'img/logo-sponsor-placeholder.png',
  },

  // 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(feedName, limit, callback) {
    if (this.feeds[feedName] === undefined) {
      if (this.debug) console.log('ERROR:', this.msgUnsupportedFeed);
      callback(this.msgUnsupportedFeed);
      return;
    }
    if (isNaN(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;
    }

    feedName = feedName.toLowerCase();
    var rssUrl = this.feeds[feedName];

    var self = this;
    $.ajax({
      url: rssUrl, // permission to use url granted in manifest.json
      dataType: 'xml',
      success: function(xml) {
        // ls.lastResponseData = xmlstring;
        self.parseFeed(xml, feedName, limit, callback);
      },
      error: function(jqXHR, text, err) {
        if (self.debug) console.log('ERROR:', self.msgConnectionError, feedName);
        callback(self.msgConnectionError);
      },
    });
  },

  parseFeed: function(xml, feedName, limit, callback) {
    var items = [];
    var self = this;
    var count = 0;
    $(xml).find('item').each( function() {
      if (count++ < limit) {
        var item = self.parseItem(this, feedName);
        items.push(item);
      }
    });
    callback(items);
  },

  parseItem: function(item, feedName) {
    var post = {};
    post.title = $(item).find("title").text();
    post.link = $(item).find("link").text();
    post.description = $(item).find("description").text();
    post.creator = $(item).find("dc:creator").text();

    post.date = $(item).find("pubDate").text().substr(5, 11);
    post.image = this.images[feedName];

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

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

    // Remove excessive whitespace...
    if (post.description.match(/<\w+>|<\/\w+>/g) !== null) { // Check if string contains markup
      // ...and ludicrous formatting (HTML)
      post.description = $.trim($(post.description).text());
    }
    else {
      post.description = post.description.trim();
    }

    // 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();
      });
    }
    // Didn't find a creator, set the feedname as creator
    if (post.creator.length == 0) {
      post.creator = feedName.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;
    }

    // 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;
  },

  // NOT DONE YET ///////////////////////////////////////////////////////////////////
  // todo: this function only handles the online-feed, make sure it handles all feeds
  unreadCount: function(xmlstring) {

    return; //

    var unread_count = 0;

    // Parse the feed
    var xmldoc = $.parseXML(xmlstring);
    $xml = $(xmldoc);
    var items = $xml.find("item");
    var idList = []; // New || Updated

    // Count feed items
    items.each( function(index, element) {

      var id = $(element).find("guid").text().split('/')[4];

      // Counting...
      if (id != localStorage.mostRecentRead) {
        unread_count++;
        idList.push(id); // New || Updated
        // Send a desktop notification about the first unread element
        if (unread_count == 1) {
          if (localStorage.lastNotified != id) {
            this.showNotification(element);
          }
          localStorage.mostRecentUnread = id;
        }
      }
      // All counted :)
      else {
        if (unread_count == 0) {
          if (this.debug) console.log('no new posts');
          Browser.setBadgeText('');
        }
        else if (unread_count >= this.maxNewsAmount) {
          if (this.debug) console.log(this.maxNewsAmount + '+ unread posts');
          Browser.setBadgeText(this.maxNewsAmount + '+');
        }
        else {
          if (this.debug) console.log('1-' + (this.maxNewsAmount - 1) + ' unread posts');
          Browser.setBadgeText(String(unread_count));
        }
        localStorage.unreadCount = unread_count;
        localStorage.mostRecentIdList = JSON.stringify(idList); // New || Updated
        return false;
      }

      // Stop counting if unread number is greater than 9
      if (index > (this.maxNewsAmount - 1)) { // Remember index is counting 0
        if (this.debug) console.log(this.maxNewsAmount + '+ unread posts (stopped counting)');
        Browser.setBadgeText(this.maxNewsAmount + '+');
        localStorage.unreadCount = this.maxNewsAmount;
        // New or updated?
        localStorage.mostRecentIdList = JSON.stringify(idList); // New || Updated
        return false;
      }
    });
  },

  showNotification: function(item) {
    if (localStorage.showNotifications == 'true') {
      var post = this.parseItem(item);
      // Remember this
      localStorage.lastNotified = post.link;
      // Get content
      localStorage.notificationTitle = post.title;
      localStorage.notificationLink = post.link;
      localStorage.notificationDescription = post.description;
      localStorage.notificationCreator = post.creator;
      // 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;
  },

  // Organization specific functions

  online_getImage: function(link, callback) {
    var id = link.split('/')[4]; // id is stored in the link
    var image = 'undefined';
    var api = 'https://online.ntnu.no/api/f5be90e5ec1d2d454ae9/news_image_by_id/';
    $.getJSON(api + id, function(json) {
      if (json['online_news_image']) {
        image = json['online_news_image']['0']['image'];
        callback(link, image);
      }
      else {
        image = this.images['online'];
        if (this.debug) console.log('ERROR: no image exists for id: ' + id);
        callback(link, image);
      }
    })
    .error(function() {
      image = this.images['online'];
      if (this.debug) console.log('ERROR: couldn\'t connect API to get image links, returning default image');
      callback(link, image);
    });
  },

}
<|endoftext|>


<commit_before>// --------------------
// Sequelize hierarchy
// Hooks
// --------------------

// exports

module.exports = function(Sequelize) {
	var Promise = Sequelize.Promise,
		Utils = Sequelize.Utils,
		_ = Utils._;

	// return hooks
	return {
		afterDefine: function(model) {
			if (model.options.hierarchy) model.isHierarchy(model.options.hierarchy);
		},

		beforeFind: function(options) {
			// check options do not include illegal hierarchies
			if (options.hierarchy && !this.hierarchy) throw new Error('You cannot get hierarchy of ' + this.name + ' - it is not hierarchical');
			checkHierarchy(options, this);
		},
		afterFind: function(result, options) {
			var parent;

			// where called from getDescendents, find id of parent
			if (options.hierarchy && options.includeMap) {
				var include = options.includeMap[Utils.singularize(this.hierarchy.through.name)];

				if (include && include._pseudo && include.where && include.where[this.hierarchy.throughForeignKey]) {
					parent = {dataValues: {}};
					parent[this.primaryKeyAttribute] = include.where[this.hierarchy.throughForeignKey];
				}
			}

			// convert hierarchies into trees
			convertHierarchies(result, options, this, parent);
		}
	};

	function checkHierarchy(options, model)
	{
		// check options do not include illegal hierarchies - throw error if so
		if (!options.include) return;

		options.include.forEach(function(include) {
			var includeModel = include.model;

			// if hierarchy set, check is legal
			if (include.hierarchy) {
				if (!includeModel.hierarchy) throw new Error('You cannot get hierarchy of ' + includeModel.name + ' - it is not hierarchical');
				if (includeModel !== model) throw new Error('You cannot get a hierarchy of ' + includeModel.name + ' without including it from a parent');
				if (include.as !== model.hierarchy.descendentsAs) throw new Error('You cannot set hierarchy on ' + model.name + ' without using the ' + model.hierarchy.descendentsAs + ' accessor');
			}

			// check includes
			checkHierarchy(include, includeModel);
		});
	}

	function convertHierarchies(results, options, model, parent)
	{
		// convert hierarchies into trees
		if (options.include) {
			options.include.forEach(function(include) {
				var includeModel = include.model,
					accessor = include.as;

				if (!Array.isArray(results)) results = [results];

				results.forEach(function(result) {
					convertHierarchies(result[accessor], include, includeModel, result);
				});
			});
		}

		if (options.hierarchy) convertHierarchy(results, model, parent);
	}

	function convertHierarchy(results, model, parent)
	{
		var hierarchy = model.hierarchy,
			primaryKey = model.primaryKeyAttribute,
			foreignKey = hierarchy.foreignKey,
			childrenAccessor = hierarchy.childrenAs,
			descendentsAccessor = hierarchy.descendentsAs,
			throughAccessor = Utils.singularize(hierarchy.through.name);

		// get parent id and move results from parent.descendents to parent.children
		var parentId = null;
		if (parent) {
			parentId = parent[primaryKey];

			parent.dataValues[childrenAccessor] = parent[childrenAccessor] = results;
			delete parent[descendentsAccessor];
			delete parent.dataValues[descendentsAccessor];
		}

		// run through all results, turning into tree

		// find rows which are not top level and move into references
		var references = {};

		for (var i = 0; i < results.length; i++) {
			var item = results[i];

			// remove reference to through table
			delete item[throughAccessor];
			delete item.dataValues[throughAccessor];

			// add into references
			references[item[primaryKey]] = item;

			// if not a root-level item, remove from results
			if (item[foreignKey] !== parentId) {
				results.splice(i, 1);
				i--;
			}
		}

		// run through references, nesting within parents
		_.forIn(references, function(item) {
			// nest inside parent
			var thisParentId = item[foreignKey];
			if (thisParentId !== parentId) {
				var parent = references[thisParentId];
				if (!parent[childrenAccessor]) parent.dataValues[childrenAccessor] = parent[childrenAccessor] = [];
				parent[childrenAccessor].push(item);
			}
		});
	}
};
<commit_msg>Spacing<commit_after>// --------------------
// Sequelize hierarchy
// Hooks
// --------------------

// exports

module.exports = function(Sequelize) {
	var Promise = Sequelize.Promise,
		Utils = Sequelize.Utils,
		_ = Utils._;

	// return hooks
	return {
		afterDefine: function(model) {
			if (model.options.hierarchy) model.isHierarchy(model.options.hierarchy);
		},

		beforeFind: function(options) {
			// check options do not include illegal hierarchies
			if (options.hierarchy && !this.hierarchy) throw new Error('You cannot get hierarchy of ' + this.name + ' - it is not hierarchical');
			checkHierarchy(options, this);
		},
		afterFind: function(result, options) {
			var parent;

			// where called from getDescendents, find id of parent
			if (options.hierarchy && options.includeMap) {
				var include = options.includeMap[Utils.singularize(this.hierarchy.through.name)];

				if (include && include._pseudo && include.where && include.where[this.hierarchy.throughForeignKey]) {
					parent = {dataValues: {}};
					parent[this.primaryKeyAttribute] = include.where[this.hierarchy.throughForeignKey];
				}
			}

			// convert hierarchies into trees
			convertHierarchies(result, options, this, parent);
		}
	};

	function checkHierarchy(options, model)
	{
		// check options do not include illegal hierarchies - throw error if so
		if (!options.include) return;

		options.include.forEach(function(include) {
			var includeModel = include.model;

			// if hierarchy set, check is legal
			if (include.hierarchy) {
				if (!includeModel.hierarchy) throw new Error('You cannot get hierarchy of ' + includeModel.name + ' - it is not hierarchical');
				if (includeModel !== model) throw new Error('You cannot get a hierarchy of ' + includeModel.name + ' without including it from a parent');
				if (include.as !== model.hierarchy.descendentsAs) throw new Error('You cannot set hierarchy on ' + model.name + ' without using the ' + model.hierarchy.descendentsAs + ' accessor');
			}

			// check includes
			checkHierarchy(include, includeModel);
		});
	}

	function convertHierarchies(results, options, model, parent)
	{
		// convert hierarchies into trees
		if (options.include) {
			options.include.forEach(function(include) {
				var includeModel = include.model,
					accessor = include.as;

				if (!Array.isArray(results)) results = [results];

				results.forEach(function(result) {
					convertHierarchies(result[accessor], include, includeModel, result);
				});
			});
		}

		if (options.hierarchy) convertHierarchy(results, model, parent);
	}

	function convertHierarchy(results, model, parent)
	{
		var hierarchy = model.hierarchy,
			primaryKey = model.primaryKeyAttribute,
			foreignKey = hierarchy.foreignKey,
			childrenAccessor = hierarchy.childrenAs,
			descendentsAccessor = hierarchy.descendentsAs,
			throughAccessor = Utils.singularize(hierarchy.through.name);

		// get parent id and move results from parent.descendents to parent.children
		var parentId = null;
		if (parent) {
			parentId = parent[primaryKey];

			parent.dataValues[childrenAccessor] = parent[childrenAccessor] = results;
			delete parent[descendentsAccessor];
			delete parent.dataValues[descendentsAccessor];
		}

		// run through all results, turning into tree

		// find rows which are not top level and move into references
		var references = {};

		for (var i = 0; i < results.length; i++) {
			var item = results[i];

			// remove reference to through table
			delete item[throughAccessor];
			delete item.dataValues[throughAccessor];

			// add into references
			references[item[primaryKey]] = item;

			// if not a root-level item, remove from results
			if (item[foreignKey] !== parentId) {
				results.splice(i, 1);
				i--;
			}
		}

		// run through references, nesting within parents
		_.forIn(references, function(item) {
			// nest inside parent
			var thisParentId = item[foreignKey];
			if (thisParentId !== parentId) {
				var parent = references[thisParentId];
				if (!parent[childrenAccessor]) parent.dataValues[childrenAccessor] = parent[childrenAccessor] = [];
				parent[childrenAccessor].push(item);
			}
		});
	}
};
<|endoftext|>


<commit_before>var iconCache = {};

function getIcon(freeBikes, emptySlots) {
  var cacheKey = freeBikes + '-' + emptySlots;
  if (iconCache[cacheKey]) {
    return iconCache[cacheKey];
  }

  var imageCanvas, context;
  var radius;
  var alpha;
  if (freeBikes == 0 && emptySlots == 0) {
    // edge case: station with nothing in it
    radius = 5;
    alpha = 0.0;
  } else {
    radius = (freeBikes+emptySlots)/2;
    if (radius > 20) {
      radius = 20;
    } else if (radius < 5) {
      radius = 8;
    }

    alpha = freeBikes / (freeBikes+emptySlots);
    if (alpha > 0.5 && alpha < 1.0) {
      alpha=0.5;
    } else if (alpha < 0.1 && alpha > 0.0) {
      alpha = 0.1;
    }
  }

  imageCanvas = document.createElement("canvas");
  context = imageCanvas.getContext("2d");
  imageCanvas.width = radius*2+4;
  imageCanvas.height = radius*2+4;

  context.clearRect(0,0,radius*2, radius*2);

  context.fillStyle = "rgba(255,0,0," + alpha + ")";
  context.beginPath();
  context.arc(imageCanvas.width/2,imageCanvas.height/2,radius,0,Math.PI*2,true);
  context.fill();

  context.strokeStyle = "#f00";
  context.beginPath();
  context.arc(imageCanvas.width/2,imageCanvas.height/2,radius,0,Math.PI*2,true);
  context.stroke();

  iconCache[cacheKey] = imageCanvas.toDataURL();
  return iconCache[cacheKey];
}

$(document).ready(function () {
  var currentNetworkId = null;

  for (var i in networks) {
    $("#network-menu").append('
' + networks[i].name + '
');
  }
  $('#network-menu').on('touchstart.dropdown.data-api', function(e) { e.stopPropagation() });

  var bixiStations = [];

  var map;

  var geocoder = new google.maps.Geocoder();
  var bixiBounds;

  function updateDisplay() {
    $("#sidebar").show();

    if ($(window).width() < 800) {
      // just the "sidebar" (no map)
      $("#map-container").hide();
      $("#sidebar").toggleClass("sidebar-fixed", false);
      $("#sidebar").toggleClass("sidebar-full", true);
      $("#sidebar").height(null);
    } else {
      // sidebar + map
      $("#sidebar").toggleClass("sidebar-fixed", true);
      $("#sidebar").toggleClass("sidebar-full", false);

      $("#sidebar").height($(window).height() - 60);
      $("#map-container").height($(window).height() - 40);
      $("#map-container").width($(window).width() - $("#sidebar").width() - 40);

      if (currentNetworkId) {
        if (!map) {
          map = {};
          map.map = new google.maps.Map(document.getElementById("map"), {
            zoom: 1,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: new google.maps.LatLng(networks[currentNetworkId].latitude,
                                           networks[currentNetworkId].longitude)
          });
          map.map.setZoom(14);

          map.directionsService = new google.maps.DirectionsService();
          map.walkingDirectionsDisplay = new google.maps.DirectionsRenderer({
            markerOptions: { zIndex: google.maps.Marker.MAX_ZINDEX } });
          map.bikeLayer = new google.maps.BicyclingLayer();
          map.bikeLayer.setMap(map.map);
          map.locationMarker = new google.maps.Marker({
            map: map.map,
            visible: false
          });
          map.infoWindow = new google.maps.InfoWindow();
          google.maps.event.addListener(map.map, 'click', function() {
            map.infoWindow.close();
          });
        }
        // resize map to fit
        google.maps.event.trigger(map.map, "resize");
      }
      $("#map-container").show();
    }
  }

  updateDisplay();

  $(window).resize(function() {
    updateDisplay();
  });

  function updatePlace(placeName) {
    _gaq.push(['_trackPageview', '/find-nearby']);
    $("#nearby-input").val(placeName)
    $("#nearby-input").blur();

    $("#network-hint-widget").hide();
    $("#nearby-error-widget").remove();
    $("#nearby").hide();

    map.walkingDirectionsDisplay.setMap(null);

    var oldFindButtonVal = $("#find-nearby-button").val();

    $("#find-nearby-button").attr('disabled', 'disabled');
    $("#find-nearby-button").val("Working...");
    geocoder.geocode( {'address': placeName, 'bounds': bixiBounds }, function(results, status) {
      $("#find-nearby-button").val(oldFindButtonVal);
      $("#find-nearby-button").removeAttr('disabled');

      if (results.length > 0) {
	var latlng = results[0].geometry.location;
	map.locationMarker.setPosition(latlng);
	map.locationMarker.setVisible(true);
	map.map.setCenter(latlng);
	map.map.setZoom(15);

	var nearby_stations = bixiStations.map(function(station) {
	  var distance = google.maps.geometry.spherical.computeDistanceBetween(latlng,
									       station.latlng);
	  return jQuery.extend({ distance: parseInt(distance) }, station);
	}).filter(function(station) {
	  return station.distance < 1000;
	}).sort(function(station1, station2) {
	  return station1.distance - station2.distance;
	}).slice(0,5);

	if (nearby_stations.length === 0) {
	  document.title = "No stations within 1000 meters of location. :-(";

	  $("#nearby-panel div.content").prepend(ich.error_widget({
	    id: "nearby-error-widget",
	    description: document.title
	  }));

	  return false;
	}

	document.title = "Stations near " + results[0].formatted_address;
	$('#nearby-content').replaceWith(ich.stations({
	  title: document.title,
	  stations: nearby_stations }));

	nearby_stations.map(function(station) {
	  $('#station-' + station.id).hover(function() {
	  }, function() {
	  }).click(function(e) {
	    $('.nearby-station').removeClass("active");
	    $(this).addClass("active");
	    map.directionsService.route({
	      origin: latlng,
	      destination: station.latlng,
	      travelMode: google.maps.DirectionsTravelMode.WALKING
	    }, function(response, status) {
	      if (status == google.maps.DirectionsStatus.OK) {
		map.locationMarker.setVisible(false);
		map.walkingDirectionsDisplay.setDirections(response);
		map.walkingDirectionsDisplay.setMap(map.map);
	      } else {
		console.log("Error processing directions to station!");
	      }
	    });
            e.preventDefault(); // prevent scrolling to top
	  });

	  // Create pie chart

	  if (station.freeBikes == 0 && station.emptySlots == 0) {
	    return;
	  }
	  var data = {
	    items: []
	  };

	  if (station.freeBikes > 0) {
	    data.items[data.items.length] = {label: 'bikes', data: station.freeBikes };
	  } else {
	  }
	  if (station.emptySlots > 0) {
	    data.items[data.items.length] = {label: 'stations', data: station.emptySlots };
	  }

	  var pieChart = new Bluff.Pie('station-graph-' + station.id, '40x40');
	  if (station.freeBikes == 0) {
	    pieChart.set_theme({
	      colors: ['#fbb' ],
	      background_colors: ['rgba(0,0,0,0)', 'rgba(0,0,0,0)']
	    });
	  } else {
	    pieChart.set_theme({
	      colors: ['#f00', '#fbb' ],
	      background_colors: ['rgba(0,0,0,0)', 'rgba(0,0,0,0)']
	    });
	  }

	  pieChart.hide_labels_less_than = 100;
	  pieChart.hide_legend = true;
	  for (i in data.items) {
	    var item = data.items[i];
	    pieChart.data(item.label, item.data);
	  }

	  pieChart.draw();
	});

	$("#nearby").show();
      } else {

	$("#nearby-panel div.content").prepend(ich.error_widget({
	  id: "nearby-error-widget",
	  description: "Unable to find location. Please make sure you are connected to the Internet and double check the wording."
	}));
      }
    });

    $("#nearby-input").show();

    return false;
  }

  function updateNetwork(networkId, placeName) {
    if (networkId === currentNetworkId) {
      if (placeName) {
        updatePlace(placeName);
      }
      return;
    }

    $("#nearby-content").hide();
    $("#nearby-input").val("");

    $("#selected-network").html(networks[networkId].name);
    $.ajax({
      type: "GET",
      url: networkId + ".json",
      dataType: "json",
      success: function(stations) {
        currentNetworkId = networkId;
        updateDisplay();

	bixiStations = [];
        bixiBounds = new google.maps.LatLngBounds();

        // convert installed station json data into our own format
	stations.forEach(function(stationDict, i, a) {
	  var station = {
            id: stationDict.id,
	    name: stationDict.name,
	    freeBikes: stationDict.freeBikes,
	    emptySlots: stationDict.emptySlots,
	    latlng: new google.maps.LatLng(stationDict.latitude,
					   stationDict.longitude),
	  };
	  station.marker = new google.maps.Marker({
	    position: station.latlng,
	    map: map.map,
	    icon: getIcon(station.freeBikes, station.emptySlots)
	  });

	  bixiStations[bixiStations.length] = station;
	  bixiBounds.extend(station.latlng);
	  google.maps.event.addListener(station.marker, 'click', function() {
	    map.infoWindow.setContent("" + station.name +
				  "
Bikes: " +
				  station.freeBikes + ' - ' +
				  "Docks: " + station.emptySlots);
	    map.infoWindow.open(map.map, station.marker);
	  });
	});

        if (placeName) {
          updatePlace(placeName);
        } else {
	  map.map.setCenter(new google.maps.LatLng(networks[currentNetworkId].latitude,
                                                   networks[currentNetworkId].longitude));
          document.title = "Nixi Bike Station Finder - " + networks[networkId].name;
        }

	$("form#nearby-form").unbind();
	$("form#nearby-form").submit(function() {
            window.location.hash = '/' + ['networks', currentNetworkId, 'places', $("#nearby-input").val()].join('/');

          return false;
	});

        $("#nearby-input").typeahead({
          source: function (query, process) {
	    geocoder.geocode({'address': query, 'bounds': bixiBounds },
                             function(results, status) {
                               var results = $.map(results.filter(function(item) {
			         return bixiBounds.contains(item.geometry.location);
			       }), function(item) {
			         return item.formatted_address;
                               });
                               return process(results);
                             });
          },
          matcher: function(query) {
            return isNaN(query); // by definition true if we have more than a number
          }
        });
      }
    });
  }

  // get network preference from user and update to it. you might think it
  // would make sense to use geolocation for this, but that's actually
  // kinda slow at least with Firefox
  var networkId = localStorage["defaultNetworkId"];
  if (networkId == undefined) {
    networkId = "bixi-montreal";
    $("#network-hint-widget").show();
  }

  var router = Router({
    '/networks/:networkId': {
      on: function(networkId) {
        updateNetwork(networkId, null);
      },
      '/places/(.+)': {
        on: function(networkId, placeName) {
          var decodedPlaceName = decodeURI(placeName);
          updateNetwork(networkId, decodedPlaceName);
        }
      }
    }
  }).configure({ 'notfound': function() { window.location.hash = "/networks/" + networkId; } });

  router.init("/networks/" + networkId);
});

<commit_msg>Need to update the default network id<commit_after>var iconCache = {};

function getIcon(freeBikes, emptySlots) {
  var cacheKey = freeBikes + '-' + emptySlots;
  if (iconCache[cacheKey]) {
    return iconCache[cacheKey];
  }

  var imageCanvas, context;
  var radius;
  var alpha;
  if (freeBikes == 0 && emptySlots == 0) {
    // edge case: station with nothing in it
    radius = 5;
    alpha = 0.0;
  } else {
    radius = (freeBikes+emptySlots)/2;
    if (radius > 20) {
      radius = 20;
    } else if (radius < 5) {
      radius = 8;
    }

    alpha = freeBikes / (freeBikes+emptySlots);
    if (alpha > 0.5 && alpha < 1.0) {
      alpha=0.5;
    } else if (alpha < 0.1 && alpha > 0.0) {
      alpha = 0.1;
    }
  }

  imageCanvas = document.createElement("canvas");
  context = imageCanvas.getContext("2d");
  imageCanvas.width = radius*2+4;
  imageCanvas.height = radius*2+4;

  context.clearRect(0,0,radius*2, radius*2);

  context.fillStyle = "rgba(255,0,0," + alpha + ")";
  context.beginPath();
  context.arc(imageCanvas.width/2,imageCanvas.height/2,radius,0,Math.PI*2,true);
  context.fill();

  context.strokeStyle = "#f00";
  context.beginPath();
  context.arc(imageCanvas.width/2,imageCanvas.height/2,radius,0,Math.PI*2,true);
  context.stroke();

  iconCache[cacheKey] = imageCanvas.toDataURL();
  return iconCache[cacheKey];
}

$(document).ready(function () {
  var currentNetworkId = null;

  for (var i in networks) {
    $("#network-menu").append('
' + networks[i].name + '
');
  }
  $('#network-menu').on('touchstart.dropdown.data-api', function(e) { e.stopPropagation() });

  var bixiStations = [];

  var map;

  var geocoder = new google.maps.Geocoder();
  var bixiBounds;

  function updateDisplay() {
    $("#sidebar").show();

    if ($(window).width() < 800) {
      // just the "sidebar" (no map)
      $("#map-container").hide();
      $("#sidebar").toggleClass("sidebar-fixed", false);
      $("#sidebar").toggleClass("sidebar-full", true);
      $("#sidebar").height(null);
    } else {
      // sidebar + map
      $("#sidebar").toggleClass("sidebar-fixed", true);
      $("#sidebar").toggleClass("sidebar-full", false);

      $("#sidebar").height($(window).height() - 60);
      $("#map-container").height($(window).height() - 40);
      $("#map-container").width($(window).width() - $("#sidebar").width() - 40);

      if (currentNetworkId) {
        if (!map) {
          map = {};
          map.map = new google.maps.Map(document.getElementById("map"), {
            zoom: 1,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            center: new google.maps.LatLng(networks[currentNetworkId].latitude,
                                           networks[currentNetworkId].longitude)
          });
          map.map.setZoom(14);

          map.directionsService = new google.maps.DirectionsService();
          map.walkingDirectionsDisplay = new google.maps.DirectionsRenderer({
            markerOptions: { zIndex: google.maps.Marker.MAX_ZINDEX } });
          map.bikeLayer = new google.maps.BicyclingLayer();
          map.bikeLayer.setMap(map.map);
          map.locationMarker = new google.maps.Marker({
            map: map.map,
            visible: false
          });
          map.infoWindow = new google.maps.InfoWindow();
          google.maps.event.addListener(map.map, 'click', function() {
            map.infoWindow.close();
          });
        }
        // resize map to fit
        google.maps.event.trigger(map.map, "resize");
      }
      $("#map-container").show();
    }
  }

  updateDisplay();

  $(window).resize(function() {
    updateDisplay();
  });

  function updatePlace(placeName) {
    _gaq.push(['_trackPageview', '/find-nearby']);
    $("#nearby-input").val(placeName)
    $("#nearby-input").blur();

    $("#network-hint-widget").hide();
    $("#nearby-error-widget").remove();
    $("#nearby").hide();

    map.walkingDirectionsDisplay.setMap(null);

    var oldFindButtonVal = $("#find-nearby-button").val();

    $("#find-nearby-button").attr('disabled', 'disabled');
    $("#find-nearby-button").val("Working...");
    geocoder.geocode( {'address': placeName, 'bounds': bixiBounds }, function(results, status) {
      $("#find-nearby-button").val(oldFindButtonVal);
      $("#find-nearby-button").removeAttr('disabled');

      if (results.length > 0) {
	var latlng = results[0].geometry.location;
	map.locationMarker.setPosition(latlng);
	map.locationMarker.setVisible(true);
	map.map.setCenter(latlng);
	map.map.setZoom(15);

	var nearby_stations = bixiStations.map(function(station) {
	  var distance = google.maps.geometry.spherical.computeDistanceBetween(latlng,
									       station.latlng);
	  return jQuery.extend({ distance: parseInt(distance) }, station);
	}).filter(function(station) {
	  return station.distance < 1000;
	}).sort(function(station1, station2) {
	  return station1.distance - station2.distance;
	}).slice(0,5);

	if (nearby_stations.length === 0) {
	  document.title = "No stations within 1000 meters of location. :-(";

	  $("#nearby-panel div.content").prepend(ich.error_widget({
	    id: "nearby-error-widget",
	    description: document.title
	  }));

	  return false;
	}

	document.title = "Stations near " + results[0].formatted_address;
	$('#nearby-content').replaceWith(ich.stations({
	  title: document.title,
	  stations: nearby_stations }));

	nearby_stations.map(function(station) {
	  $('#station-' + station.id).hover(function() {
	  }, function() {
	  }).click(function(e) {
	    $('.nearby-station').removeClass("active");
	    $(this).addClass("active");
	    map.directionsService.route({
	      origin: latlng,
	      destination: station.latlng,
	      travelMode: google.maps.DirectionsTravelMode.WALKING
	    }, function(response, status) {
	      if (status == google.maps.DirectionsStatus.OK) {
		map.locationMarker.setVisible(false);
		map.walkingDirectionsDisplay.setDirections(response);
		map.walkingDirectionsDisplay.setMap(map.map);
	      } else {
		console.log("Error processing directions to station!");
	      }
	    });
            e.preventDefault(); // prevent scrolling to top
	  });

	  // Create pie chart

	  if (station.freeBikes == 0 && station.emptySlots == 0) {
	    return;
	  }
	  var data = {
	    items: []
	  };

	  if (station.freeBikes > 0) {
	    data.items[data.items.length] = {label: 'bikes', data: station.freeBikes };
	  } else {
	  }
	  if (station.emptySlots > 0) {
	    data.items[data.items.length] = {label: 'stations', data: station.emptySlots };
	  }

	  var pieChart = new Bluff.Pie('station-graph-' + station.id, '40x40');
	  if (station.freeBikes == 0) {
	    pieChart.set_theme({
	      colors: ['#fbb' ],
	      background_colors: ['rgba(0,0,0,0)', 'rgba(0,0,0,0)']
	    });
	  } else {
	    pieChart.set_theme({
	      colors: ['#f00', '#fbb' ],
	      background_colors: ['rgba(0,0,0,0)', 'rgba(0,0,0,0)']
	    });
	  }

	  pieChart.hide_labels_less_than = 100;
	  pieChart.hide_legend = true;
	  for (i in data.items) {
	    var item = data.items[i];
	    pieChart.data(item.label, item.data);
	  }

	  pieChart.draw();
	});

	$("#nearby").show();
      } else {

	$("#nearby-panel div.content").prepend(ich.error_widget({
	  id: "nearby-error-widget",
	  description: "Unable to find location. Please make sure you are connected to the Internet and double check the wording."
	}));
      }
    });

    $("#nearby-input").show();

    return false;
  }

  function updateNetwork(networkId, placeName) {
    localStorage["defaultNetworkId"] = networkId;
    if (networkId === currentNetworkId) {
      if (placeName) {
        updatePlace(placeName);
      }
      return;
    }

    $("#nearby-content").hide();
    $("#nearby-input").val("");

    $("#selected-network").html(networks[networkId].name);
    $.ajax({
      type: "GET",
      url: networkId + ".json",
      dataType: "json",
      success: function(stations) {
        currentNetworkId = networkId;
        updateDisplay();

	bixiStations = [];
        bixiBounds = new google.maps.LatLngBounds();

        // convert installed station json data into our own format
	stations.forEach(function(stationDict, i, a) {
	  var station = {
            id: stationDict.id,
	    name: stationDict.name,
	    freeBikes: stationDict.freeBikes,
	    emptySlots: stationDict.emptySlots,
	    latlng: new google.maps.LatLng(stationDict.latitude,
					   stationDict.longitude),
	  };
	  station.marker = new google.maps.Marker({
	    position: station.latlng,
	    map: map.map,
	    icon: getIcon(station.freeBikes, station.emptySlots)
	  });

	  bixiStations[bixiStations.length] = station;
	  bixiBounds.extend(station.latlng);
	  google.maps.event.addListener(station.marker, 'click', function() {
	    map.infoWindow.setContent("" + station.name +
				  "
Bikes: " +
				  station.freeBikes + ' - ' +
				  "Docks: " + station.emptySlots);
	    map.infoWindow.open(map.map, station.marker);
	  });
	});

        if (placeName) {
          updatePlace(placeName);
        } else {
	  map.map.setCenter(new google.maps.LatLng(networks[currentNetworkId].latitude,
                                                   networks[currentNetworkId].longitude));
          document.title = "Nixi Bike Station Finder - " + networks[networkId].name;
        }

	$("form#nearby-form").unbind();
	$("form#nearby-form").submit(function() {
            window.location.hash = '/' + ['networks', currentNetworkId, 'places', $("#nearby-input").val()].join('/');

          return false;
	});

        $("#nearby-input").typeahead({
          source: function (query, process) {
	    geocoder.geocode({'address': query, 'bounds': bixiBounds },
                             function(results, status) {
                               var results = $.map(results.filter(function(item) {
			         return bixiBounds.contains(item.geometry.location);
			       }), function(item) {
			         return item.formatted_address;
                               });
                               return process(results);
                             });
          },
          matcher: function(query) {
            return isNaN(query); // by definition true if we have more than a number
          }
        });
      }
    });
  }

  // get network preference from user and update to it. you might think it
  // would make sense to use geolocation for this, but that's actually
  // kinda slow at least with Firefox
  var networkId = localStorage["defaultNetworkId"];
  if (networkId == undefined) {
    networkId = "bixi-montreal";
    $("#network-hint-widget").show();
  }

  var router = Router({
    '/networks/:networkId': {
      on: function(networkId) {
        updateNetwork(networkId, null);
      },
      '/places/(.+)': {
        on: function(networkId, placeName) {
          var decodedPlaceName = decodeURI(placeName);
          updateNetwork(networkId, decodedPlaceName);
        }
      }
    }
  }).configure({ 'notfound': function() { window.location.hash = "/networks/" + networkId; } });

  router.init("/networks/" + networkId);
});

<|endoftext|>


<commit_before>$(document).ready(function() {
    var animate = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
        window.setTimeout(callback, 1000 / 60)
    };

    $(document).keyup(function(e) {
        if (e.keyCode == 27) { // escape key maps to keycode `27`
            $("#pong").hide();
            $("#modal-wrapper").hide();
            gameStarted = false;
        }
    });

    function pongHandler() {
        $("#pong").show();
        $("#pong").focus();
        paintStartBackground();
        player1 = new Player(30, height / 2 - 50, 15, 100);
        player2 = new Player(width - 45, height / 2 - 50, 15, 100);
        ball = new Ball(width / 2, height / 2);

        p1Score = 0;
        p2Score = 0;
    }

    function parseInput(command) {
        switch (command) {
            case "ls":
            case "dir":
                // list dirs/files
                break;
            case "cd..":
                // go up dir
                break;
            case "cd blah":
                // enter dir
                break;
            case "open blah":
                // open blah
            case "pong":
                pongHandler();
                break;
            case "help":
                helpHandler();
                break;
            default:
                defaultHandler();
                break;
        }
    }

    $("#pong-file").dblclick(function() {
      $("#modal-wrapper").show();
      $("#pong").show();
      pongHandler();
      $("#modal-title").html("Pong");
    });

    var width = 800;
    var height = 600;
    var canvas = document.getElementById("pong");
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");

    //Game objects
    var player1 = new Player(30, height / 2 - 50, 15, 100);
    var player2 = new Player(width - 45, height / 2 - 50, 15, 100);
    var ball = new Ball(width / 2, height / 2);

    var gameStarted = false;

    var p1Score = 0;
    var p2Score = 0;

    var keysDown = {};

    function paintStartBackground() {
        ctx.background = "black";
        ctx.beginPath();
        ctx.strokeStyle = "black";
        ctx.fillStyle = "black";
        ctx.rect(0, 0, width, height);
        ctx.fill();
        ctx.stroke();

        ctx.beginPath();
        ctx.font = "18px PT Sans, sans-serif";
        ctx.fillStyle = 'white';
        ctx.fillText("Press Enter to Start", 255, 50);
        ctx.fillText("Press Esc to leave", 5, 20);
        ctx.stroke();
        canvas.onkeydown = function(event) {
            event = event || window.event;
            enterKeyHandler(event.keyCode);
        };
    }

    function paintGameOverBackground() {
        ctx.beginPath();
        ctx.background = "black";
        ctx.strokeStyle = "white";
        ctx.fillStyle = "black";
        ctx.rect(0, 0, width, height);
        ctx.fill();
        ctx.stroke();

        ctx.beginPath();
        ctx.font = "18px PT Sans, sans-serif";
        ctx.fillStyle = "white";
        ctx.fillText("P1 Score: " + p1Score, 100, 50);
        ctx.fillText("Press Esc to leave", 5, 20);
        ctx.fillText("P2 Score: " + p2Score, 600, 50);
        if (p1Score == 10) {
            ctx.fillText("P1 Wins!!", 320, 50);
        } else if (p2Score == 10) {
            ctx.fillText("P2 Wins!!", 320, 50);
        }
        ctx.fillText("Press Enter to play again!", 190, 80);
        ctx.stroke();

        player1 = new Player(30, height / 2 - 50, 15, 100);
        player2 = new Player(width - 45, height / 2 - 50, 15, 100);
        ball = new Ball(width / 2, height / 2);

        gameStarted = false;

        p1Score = 0;
        p2Score = 0;

        player1.keyPress();
    }

    function paintBackground() {
        ctx.beginPath();
        ctx.background = "black";
        ctx.strokeStyle = "white";
        ctx.rect(0, 0, width, height);
        ctx.fillStyle = "black";
        ctx.fill();
        ctx.stroke();

        ctx.beginPath();
        ctx.font = "18px PT Sans, sans-serif";
        ctx.fillStyle = "#D3D3D3";
        ctx.fillText("P1 Score: " + p1Score, 100, 50);
        ctx.fillText("Press Esc to leave", 5, 20);
        ctx.fillText("P2 Score: " + p2Score, 600, 50);
        ctx.stroke();
    }

    function Player(x, y, width, height) {
        this.paddle = new Paddle(x, y, width, height);
    }

    function Paddle(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.x_speed = 0;
        this.y_speed = 0;
    }

    function Ball(x, y) {
        this.x = x;
        this.y = y;
        this.x_speed = 10;
        this.y_speed = 0;
    }

    var render = function() {
        player1.render();
        player2.render();
        ball.render();
    };

    var update = function() {
        player1.update();
        player2.update();
        ball.update(player1.paddle, player2.paddle);
    };

    var step = function() {
        if (gameStarted) {
            console.log("animating");
            paintBackground();
            player1.keyPress();
            ball.update(player1.paddle, player2.paddle);
            render();
            animate(step);

            if (p1Score === 10 || p2Score === 10) {
                gameStarted = false;
                paintGameOverBackground();
                return;
            }
        }
    };

    Paddle.prototype.render = function() {
        ctx.beginPath();
        ctx.strokeStyle = "white";
        ctx.rect(this.x, this.y, this.width, this.height);
        ctx.stroke();
    };

    Paddle.prototype.move = function(x, y) {
        this.x += 2 * x;
        this.y += 2 * y;
        this.x_speed = x;
        this.y_speed = y;
        if (this.y < 0) {
            this.y = 0;
            this.y_speed = 0;
        } else if (this.y + this.height > 600) {
            this.y = 600 - this.height;
            this.y_speed = 0;
        }
    };

    Player.prototype.render = function() {
        this.paddle.render();
    };

    Player.prototype.keyPress = function() {
        var playerMoveSpeed = 2.3;
        for (var key in keysDown) {
            var value = Number(key);
            if (value === 87 && gameStarted) {
                //w
                player1.paddle.move(0, -playerMoveSpeed);
            } else if (value === 83 && gameStarted) {
                //s
                player1.paddle.move(0, playerMoveSpeed);
            } else if (value === 38 && gameStarted) {
                //up arrow
                player2.paddle.move(0, -playerMoveSpeed);
            } else if (value === 40 && gameStarted) {
                //down arrow
                player2.paddle.move(0, playerMoveSpeed);
            } else if (value === 13 && gameStarted === false) {
                //enter
                gameStarted = true;
                animate(step);
            }
        }
    };

    function enterKeyHandler(keyCode) {
        if (keyCode == 13 && gameStarted == false) {
            gameStarted = true;
            animate(step);
        }
    }

    Ball.prototype.render = function() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, 5, 2 * Math.PI, false);
        ctx.fillStyle = "#FFFFFF";
        ctx.fill();
        ctx.stroke();
    };

    Ball.prototype.update = function(paddle1, paddle2) {
        this.x += this.x_speed;
        this.y += this.y_speed;
        var right_x = this.x + 5;
        var top_y = this.y - 5;
        var bottom_x = this.x + 5;
        var bottom_y = this.y + 5;

        //top boundry
        if (this.y - 5 < 0) {
            this.y = 5;
            this.y_speed = -this.y_speed;
        }
        //bottom boundry
        else if (this.y + 5 > 600) {
            this.y = 595;
            this.y_speed = -this.y_speed;
        }

        //respawn ball
        if (this.x < 0) {
            this.y_speed = 0;
            this.x_speed = 10;
            this.x = 400;
            this.y = 300;
            p2Score++;
        } else if (this.x > 800) {
            this.y_speed = 0;
            this.x_speed = -10;
            this.x = 400;
            this.y = 300;
            p1Score++;
        }

        //hits right paddle
        if (right_x == paddle2.x && this.y >= paddle2.y && this.y <= paddle2.y + paddle2.height) {
            this.x_speed = -this.x_speed;
            if (paddle2.y_speed != 0) {
                this.y_speed = 1.5 * paddle2.y_speed;
            }
        }
        //hits left paddle
        else if (right_x == paddle1.x + 25 && this.y >= paddle1.y && this.y <= paddle1.y + paddle1.height) {
            this.x_speed = -this.x_speed;
            if (paddle1.y_speed != 0) {
                this.y_speed = 1.5 * paddle1.y_speed;
            }
        }
    };

    window.addEventListener("keydown", function(event) {
        keysDown[event.keyCode] = true;
    });

    window.addEventListener("keyup", function(event) {
        delete keysDown[event.keyCode];
    });
});
<commit_msg>esc has the same functionality as the red x now<commit_after>$(document).ready(function() {
    var animate = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || function(callback) {
        window.setTimeout(callback, 1000 / 60)
    };

    $(document).keyup(function(e) {
        if (e.keyCode == 27) { // escape key maps to keycode `27`
            $("#pong").hide();
            $("#modal-wrapper").hide();
            $("#modal-bar").hide();
            $("#java-folder-modal").hide();
            $("#c-folder-modal").hide();
            $("#python-folder-modal").hide();
            $("#web-folder-modal").hide();
            $("#instructions-modal").hide();
            $("#work-history").hide();
            gameStarted = false;
        }
    });

    function pongHandler() {
        $("#pong").show();
        $("#pong").focus();
        paintStartBackground();
        player1 = new Player(30, height / 2 - 50, 15, 100);
        player2 = new Player(width - 45, height / 2 - 50, 15, 100);
        ball = new Ball(width / 2, height / 2);

        p1Score = 0;
        p2Score = 0;
    }

    function parseInput(command) {
        switch (command) {
            case "ls":
            case "dir":
                // list dirs/files
                break;
            case "cd..":
                // go up dir
                break;
            case "cd blah":
                // enter dir
                break;
            case "open blah":
                // open blah
            case "pong":
                pongHandler();
                break;
            case "help":
                helpHandler();
                break;
            default:
                defaultHandler();
                break;
        }
    }

    $("#pong-file").dblclick(function() {
      $("#modal-wrapper").show();
      $("#pong").show();
      pongHandler();
      $("#modal-title").html("Pong");
    });

    var width = 800;
    var height = 600;
    var canvas = document.getElementById("pong");
    canvas.width = width;
    canvas.height = height;
    var ctx = canvas.getContext("2d");

    //Game objects
    var player1 = new Player(30, height / 2 - 50, 15, 100);
    var player2 = new Player(width - 45, height / 2 - 50, 15, 100);
    var ball = new Ball(width / 2, height / 2);

    var gameStarted = false;

    var p1Score = 0;
    var p2Score = 0;

    var keysDown = {};

    function paintStartBackground() {
        ctx.background = "black";
        ctx.beginPath();
        ctx.strokeStyle = "black";
        ctx.fillStyle = "black";
        ctx.rect(0, 0, width, height);
        ctx.fill();
        ctx.stroke();

        ctx.beginPath();
        ctx.font = "18px PT Sans, sans-serif";
        ctx.fillStyle = 'white';
        ctx.fillText("Press Enter to Start", 255, 50);
        ctx.fillText("Press Esc to leave", 5, 20);
        ctx.stroke();
        canvas.onkeydown = function(event) {
            event = event || window.event;
            enterKeyHandler(event.keyCode);
        };
    }

    function paintGameOverBackground() {
        ctx.beginPath();
        ctx.background = "black";
        ctx.strokeStyle = "white";
        ctx.fillStyle = "black";
        ctx.rect(0, 0, width, height);
        ctx.fill();
        ctx.stroke();

        ctx.beginPath();
        ctx.font = "18px PT Sans, sans-serif";
        ctx.fillStyle = "white";
        ctx.fillText("P1 Score: " + p1Score, 100, 50);
        ctx.fillText("Press Esc to leave", 5, 20);
        ctx.fillText("P2 Score: " + p2Score, 600, 50);
        if (p1Score == 10) {
            ctx.fillText("P1 Wins!!", 320, 50);
        } else if (p2Score == 10) {
            ctx.fillText("P2 Wins!!", 320, 50);
        }
        ctx.fillText("Press Enter to play again!", 190, 80);
        ctx.stroke();

        player1 = new Player(30, height / 2 - 50, 15, 100);
        player2 = new Player(width - 45, height / 2 - 50, 15, 100);
        ball = new Ball(width / 2, height / 2);

        gameStarted = false;

        p1Score = 0;
        p2Score = 0;

        player1.keyPress();
    }

    function paintBackground() {
        ctx.beginPath();
        ctx.background = "black";
        ctx.strokeStyle = "white";
        ctx.rect(0, 0, width, height);
        ctx.fillStyle = "black";
        ctx.fill();
        ctx.stroke();

        ctx.beginPath();
        ctx.font = "18px PT Sans, sans-serif";
        ctx.fillStyle = "#D3D3D3";
        ctx.fillText("P1 Score: " + p1Score, 100, 50);
        ctx.fillText("Press Esc to leave", 5, 20);
        ctx.fillText("P2 Score: " + p2Score, 600, 50);
        ctx.stroke();
    }

    function Player(x, y, width, height) {
        this.paddle = new Paddle(x, y, width, height);
    }

    function Paddle(x, y, width, height) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.x_speed = 0;
        this.y_speed = 0;
    }

    function Ball(x, y) {
        this.x = x;
        this.y = y;
        this.x_speed = 10;
        this.y_speed = 0;
    }

    var render = function() {
        player1.render();
        player2.render();
        ball.render();
    };

    var update = function() {
        player1.update();
        player2.update();
        ball.update(player1.paddle, player2.paddle);
    };

    var step = function() {
        if (gameStarted) {
            console.log("animating");
            paintBackground();
            player1.keyPress();
            ball.update(player1.paddle, player2.paddle);
            render();
            animate(step);

            if (p1Score === 10 || p2Score === 10) {
                gameStarted = false;
                paintGameOverBackground();
                return;
            }
        }
    };

    Paddle.prototype.render = function() {
        ctx.beginPath();
        ctx.strokeStyle = "white";
        ctx.rect(this.x, this.y, this.width, this.height);
        ctx.stroke();
    };

    Paddle.prototype.move = function(x, y) {
        this.x += 2 * x;
        this.y += 2 * y;
        this.x_speed = x;
        this.y_speed = y;
        if (this.y < 0) {
            this.y = 0;
            this.y_speed = 0;
        } else if (this.y + this.height > 600) {
            this.y = 600 - this.height;
            this.y_speed = 0;
        }
    };

    Player.prototype.render = function() {
        this.paddle.render();
    };

    Player.prototype.keyPress = function() {
        var playerMoveSpeed = 2.3;
        for (var key in keysDown) {
            var value = Number(key);
            if (value === 87 && gameStarted) {
                //w
                player1.paddle.move(0, -playerMoveSpeed);
            } else if (value === 83 && gameStarted) {
                //s
                player1.paddle.move(0, playerMoveSpeed);
            } else if (value === 38 && gameStarted) {
                //up arrow
                player2.paddle.move(0, -playerMoveSpeed);
            } else if (value === 40 && gameStarted) {
                //down arrow
                player2.paddle.move(0, playerMoveSpeed);
            } else if (value === 13 && gameStarted === false) {
                //enter
                gameStarted = true;
                animate(step);
            }
        }
    };

    function enterKeyHandler(keyCode) {
        if (keyCode == 13 && gameStarted == false) {
            gameStarted = true;
            animate(step);
        }
    }

    Ball.prototype.render = function() {
        ctx.beginPath();
        ctx.arc(this.x, this.y, 5, 2 * Math.PI, false);
        ctx.fillStyle = "#FFFFFF";
        ctx.fill();
        ctx.stroke();
    };

    Ball.prototype.update = function(paddle1, paddle2) {
        this.x += this.x_speed;
        this.y += this.y_speed;
        var right_x = this.x + 5;
        var top_y = this.y - 5;
        var bottom_x = this.x + 5;
        var bottom_y = this.y + 5;

        //top boundry
        if (this.y - 5 < 0) {
            this.y = 5;
            this.y_speed = -this.y_speed;
        }
        //bottom boundry
        else if (this.y + 5 > 600) {
            this.y = 595;
            this.y_speed = -this.y_speed;
        }

        //respawn ball
        if (this.x < 0) {
            this.y_speed = 0;
            this.x_speed = 10;
            this.x = 400;
            this.y = 300;
            p2Score++;
        } else if (this.x > 800) {
            this.y_speed = 0;
            this.x_speed = -10;
            this.x = 400;
            this.y = 300;
            p1Score++;
        }

        //hits right paddle
        if (right_x == paddle2.x && this.y >= paddle2.y && this.y <= paddle2.y + paddle2.height) {
            this.x_speed = -this.x_speed;
            if (paddle2.y_speed != 0) {
                this.y_speed = 1.5 * paddle2.y_speed;
            }
        }
        //hits left paddle
        else if (right_x == paddle1.x + 25 && this.y >= paddle1.y && this.y <= paddle1.y + paddle1.height) {
            this.x_speed = -this.x_speed;
            if (paddle1.y_speed != 0) {
                this.y_speed = 1.5 * paddle1.y_speed;
            }
        }
    };

    window.addEventListener("keydown", function(event) {
        keysDown[event.keyCode] = true;
    });

    window.addEventListener("keyup", function(event) {
        delete keysDown[event.keyCode];
    });
});
<|endoftext|>