<commit_before>const User = (function(){
  function User(system, container, nick){
    this.container = container;
    this.isOp = false;
    this.isVoice = false;
    this.nick = nick;
    this.system = system;
  }

  User.prototype.remove = function(){
    this.system.gui.removeUser(this.container);
  };

  User.prototype.op = function(){
    this.system.gui.opUser(this.container, this.nick);
    this.isOp = true;
  };

  User.prototype.deop = function(){
    this.system.gui.deopUser(this.container, this.nick, this.isVoice);
    this.isOp = false;
  };

  User.prototype.voice = function(){
    this.system.gui.voiceUser(this.container, this.nick, this.isOp);
    this.isVoice = true;
  };

  User.prototype.devoice = function(){
    this.system.gui.devoiceUser(this.container, this.nick, this.isOp);
    this.isVoice = false;
  };

  User.prototype.inaktiv = function(){
    this.system.gui.inaktiv(this.container);
  };

  User.prototype.uninaktiv = function(){
    this.system.gui.uninaktiv(this.conatiner);
  };

  User.prototype.updateNick = function(nick){
    this.system.gui.updateNick(this.container, this.nick, this.isVoice, this.isOp);
    this.nick = nick;
  };

  return User;
})();
<commit_msg>Update user.js<commit_after>const User = (function(){
  function User(system, container, nick){
    this.container = container;
    this.isOp = false;
    this.isVoice = false;
    this.nick = nick;
    this.system = system;
  }

  User.prototype.remove = function(){
    this.system.gui.removeUser(this.container);
  };

  User.prototype.op = function(){
    this.system.gui.opUser(this.container, this.nick);
    this.isOp = true;
  };

  User.prototype.deop = function(){
    this.system.gui.deopUser(this.container, this.nick, this.isVoice);
    this.isOp = false;
  };

  User.prototype.voice = function(){
    this.system.gui.voiceUser(this.container, this.nick, this.isOp);
    this.isVoice = true;
  };

  User.prototype.devoice = function(){
    this.system.gui.devoiceUser(this.container, this.nick, this.isOp);
    this.isVoice = false;
  };

  User.prototype.inaktiv = function(){
    this.system.gui.inaktiv(this.container);
  };

  User.prototype.uninaktiv = function(){
    this.system.gui.uninaktiv(this.conatiner);
  };

  User.prototype.updateNick = function(nick){
    this.system.gui.updateNick(this.container, nick, this.isVoice, this.isOp);
    this.nick = nick;
  };

  return User;
})();
<|endoftext|>


<commit_before>function Dict() {
    this.items = {};
}

Dict.prototype = {

  prop: function(key) {
    return ':' + key;
  },

  get: function(key, def) {
    var p = this.prop(key),
        k = this.items;

    return k.hasOwnProperty(p) ? k[p] : def;
  },

  set: function(key, value) {
    var p = this.prop(key);

    this.items[p] = value;

    return value;
  },

  count: function() {
    return Object.keys(this.items).length;
  },

  has: function(key) {
    var p = this.prop(key);

    return this.items.hasOwnProperty(p);
  },

  del: function(key) {
    var p = this.prop(key),
        k = this.items;

    if(k.hasOwnProperty(p))
      delete k[p];
  },

  keys: function() {
    return Object.keys(this.items).map(function(key) {
      return key.substring(1);
    });
  }

};
<commit_msg>Indentation nit.<commit_after>function Dict() {
  this.items = {};
}

Dict.prototype = {

  prop: function(key) {
    return ':' + key;
  },

  get: function(key, def) {
    var p = this.prop(key),
        k = this.items;

    return k.hasOwnProperty(p) ? k[p] : def;
  },

  set: function(key, value) {
    var p = this.prop(key);

    this.items[p] = value;

    return value;
  },

  count: function() {
    return Object.keys(this.items).length;
  },

  has: function(key) {
    var p = this.prop(key);

    return this.items.hasOwnProperty(p);
  },

  del: function(key) {
    var p = this.prop(key),
        k = this.items;

    if(k.hasOwnProperty(p))
      delete k[p];
  },

  keys: function() {
    return Object.keys(this.items).map(function(key) {
      return key.substring(1);
    });
  }

};
<|endoftext|>


<commit_before>var util = {};

/**
 * @param {Event} e
 * @return {string} Human-readable error description.
 */
util.fsErrorStr = function(e) {
  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      return 'Quota exceeded';
    case FileError.NOT_FOUND_ERR:
      return 'File not found';
    case FileError.SECURITY_ERR:
      return 'Security error';
    case FileError.INVALID_MODIFICATION_ERR:
      return 'Invalid modification';
    case FileError.INVALID_STATE_ERR:
      return 'Invalid state';
    default:
      return 'Unknown Error';
  }
}

util.handleFSError = function(e) {
  $.event.trigger('filesystemerror');
  console.warn('FS Error:', util.fsErrorStr(e), e);
};

/**
 * @param {FileEntry} entry
 * @param {string} content
 * @param {Function} onsuccess
 * @param {Function?} opt_onerror
 * Truncate the file and write the content.
 */
util.writeFile = function(entry, content, onsuccess, opt_onerror) {
  var blob = new Blob([content], {type: 'text/plain'});
  entry.createWriter(function(writer) {
    writer.onerror = opt_onerror ? opt_onerror : util.handleFSError;
    writer.onwrite = util.writeToWriter_.bind(null, writer, blob, onsuccess);
    writer.truncate(blob.size);
  });
};

/**
 * @param {FileWriter} writer
 * @param {Blob} blob
 * @param {Function} onsuccess
 */
util.writeToWriter_ = function(writer, blob, onsuccess) {
  writer.onwrite = onsuccess;
  writer.write(blob);
};

/**
 * @param {string} File name.
 * @return {string} Sanitized File name.
 * Returns a sanitized version of a File Name.
 */
util.sanitizeFileName = function(fileName) {
  return fileName.replace(/[^a-z0-9\-]/gi, ' ').substr(0, 50).trim();
}

/**
 * @param {string} File name.
 * @return {string} Extension.
 * Returns the extension of a File Name or null if there's none.
 */
util.getExtension = function(fileName) {
  var match = /\.([^.\\\/]+)$/.exec(fileName);

  if (match) {
    return match[1];
  } else {
    return null;
  }
};

/*
 * @param {string} Optional raw text.
 * @return {string} Line endings.
 * Returns guessed line endings or LF if not successful.
*/
util.guessLineEndings = function(opt_text) {
  var indexOfLF = opt_text.indexOf('\n');
  var hasCRLF = (indexOfLF > 0) && (opt_text[indexOfLF - 1] === '\r');

  return (hasCRLF ? '\r\n' : '\n');
};
<commit_msg>Addresses last nits<commit_after>var util = {};

/**
 * @param {Event} e
 * @return {string} Human-readable error description.
 */
util.fsErrorStr = function(e) {
  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      return 'Quota exceeded';
    case FileError.NOT_FOUND_ERR:
      return 'File not found';
    case FileError.SECURITY_ERR:
      return 'Security error';
    case FileError.INVALID_MODIFICATION_ERR:
      return 'Invalid modification';
    case FileError.INVALID_STATE_ERR:
      return 'Invalid state';
    default:
      return 'Unknown Error';
  }
}

util.handleFSError = function(e) {
  $.event.trigger('filesystemerror');
  console.warn('FS Error:', util.fsErrorStr(e), e);
};

/**
 * @param {FileEntry} entry
 * @param {string} content
 * @param {Function} onsuccess
 * @param {Function?} opt_onerror
 * Truncate the file and write the content.
 */
util.writeFile = function(entry, content, onsuccess, opt_onerror) {
  var blob = new Blob([content], {type: 'text/plain'});
  entry.createWriter(function(writer) {
    writer.onerror = opt_onerror ? opt_onerror : util.handleFSError;
    writer.onwrite = util.writeToWriter_.bind(null, writer, blob, onsuccess);
    writer.truncate(blob.size);
  });
};

/**
 * @param {FileWriter} writer
 * @param {Blob} blob
 * @param {Function} onsuccess
 */
util.writeToWriter_ = function(writer, blob, onsuccess) {
  writer.onwrite = onsuccess;
  writer.write(blob);
};

/**
 * @param {string} File name.
 * @return {string} Sanitized File name.
 * Returns a sanitized version of a File Name.
 */
util.sanitizeFileName = function(fileName) {
  return fileName.replace(/[^a-z0-9\-]/gi, ' ').substr(0, 50).trim();
}

/**
 * @param {string} File name.
 * @return {string} Extension.
 * Returns the extension of a File Name or null if there's none.
 */
util.getExtension = function(fileName) {
  var match = /\.([^.\\\/]+)$/.exec(fileName);

  if (match) {
    return match[1];
  } else {
    return null;
  }
};

/*
 * @param {?string} [text] Text content.
 * @return {string} Line endings.
 * Returns guessed line endings or LF if not successful.
*/
util.guessLineEndings = function(text) {
  if (!text) {
    return '\n';
  }
  var indexOfLF = text.indexOf('\n');
  var hasCRLF = (indexOfLF > 0) && (opt_text[indexOfLF - 1] === '\r');

  return (hasCRLF ? '\r\n' : '\n');
};
<|endoftext|>


<commit_before>/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function(){
	// count character on keyup
	function counter(event){
		var maxLength = 140;
		var currentLength = $("#notice_data-text").val().length;
		var remaining = maxLength - currentLength;
		var counter = $("#notice_text-count");
		counter.text(remaining);

		if (remaining <= 0) {
			$("#form_notice").addClass("warning");
		} else {
			$("#form_notice").removeClass("warning");
		}
	}

	function submitonreturn(event) {
		if (event.keyCode == 13) {
			$("#form_notice").submit();
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		return true;
	}

	if ($("#notice_data-text").length) {
		$("#notice_data-text").bind("keyup", counter);
		$("#notice_data-text").bind("keydown", submitonreturn);

		// run once in case there's something in there
		counter();

		// set the focus
		$("#notice_data-text").focus();
	}

	// XXX: refactor this code

	var favoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var dis = new_form.id;
												var fav = dis.replace('disfavor', 'favor');
												$('form#'+fav).replaceWith(new_form);
												$('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
											  }
					 };

	var disoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var fav = new_form.id;
												var dis = fav.replace('favor', 'disfavor');
												$('form#'+dis).replaceWith(new_form);
												$('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);
											  }
					 };

	var joinoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var leave = new_form.id;
												var join = leave.replace('leave', 'join');
												$('form#'+join).replaceWith(new_form);
												$('form#'+leave).ajaxForm(leaveoptions).each(addAjaxHidden);
											  }
					 };

	var leaveoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var join = new_form.id;
												var leave = join.replace('join', 'leave');
												$('form#'+leave).replaceWith(new_form);
												$('form#'+join).ajaxForm(joinoptions).each(addAjaxHidden);
											  }
					 };

	function addAjaxHidden() {
		var ajax = document.createElement('input');
		ajax.setAttribute('type', 'hidden');
		ajax.setAttribute('name', 'ajax');
		ajax.setAttribute('value', 1);
		this.appendChild(ajax);
	}

	$("form.form_favor").ajaxForm(favoptions);
	$("form.form_disfavor").ajaxForm(disoptions);
	$("form.form_group_join").ajaxForm(joinoptions);
	$("form.form_group_leave").ajaxForm(leaveoptions);
	$("form.form_favor").each(addAjaxHidden);
	$("form.form_disfavor").each(addAjaxHidden);
	$("form.form_group_join").each(addAjaxHidden);
	$("form.form_group_leave").each(addAjaxHidden);

	$("#form_user_nudge").ajaxForm ({ dataType: 'xml',
		beforeSubmit: function(xml) { $("#form_user_nudge input[type=submit]").attr("disabled", "disabled");
									  $("#form_user_nudge input[type=submit]").addClass("disabled");
									},
		success: function(xml) { $("#form_user_nudge").replaceWith(document._importNode($("#nudge_response", xml).get(0),true));
							     $("#form_user_nudge input[type=submit]").removeAttr("disabled");
							     $("#form_user_nudge input[type=submit]").removeClass("disabled");
							   }
	 });
	$("#form_user_nudge").each(addAjaxHidden);

	var Subscribe = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { $(".form_user_subscribe input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_subscribe input[type=submit]").addClass("disabled");
																	    },
					  success: function(xml) { var form_unsubscribe = document._importNode($('form', xml).get(0), true);
										  	   var form_unsubscribe_id = form_unsubscribe.id;
											   var form_subscribe_id = form_unsubscribe_id.replace('unsubscribe', 'subscribe');
											   $("form#"+form_subscribe_id).replaceWith(form_unsubscribe);
											   $("form#"+form_unsubscribe_id).ajaxForm(UnSubscribe).each(addAjaxHidden);
											   $("dd.subscribers").text(parseInt($("dd.subscribers").text())+1);
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled");
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
										     }
					};

	var UnSubscribe = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { $(".form_user_unsubscribe input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unsubscribe input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { var form_subscribe = document._importNode($('form', xml).get(0), true);
										  		 var form_subscribe_id = form_subscribe.id;
												 var form_unsubscribe_id = form_subscribe_id.replace('subscribe', 'unsubscribe');
												 $("form#"+form_unsubscribe_id).replaceWith(form_subscribe);
												 $("form#"+form_subscribe_id).ajaxForm(Subscribe).each(addAjaxHidden);
												 $("#profile_send_a_new_message").remove();
												 $("#profile_nudge").remove();
											     $("dd.subscribers").text(parseInt($("dd.subscribers").text())-1);
												 $(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");
												 $(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
											   }
					  };

	$(".form_user_subscribe").ajaxForm(Subscribe);
	$(".form_user_unsubscribe").ajaxForm(UnSubscribe);
	$(".form_user_subscribe").each(addAjaxHidden);
	$(".form_user_unsubscribe").each(addAjaxHidden);

	var PostNotice = { dataType: 'xml',
					   beforeSubmit: function(formData, jqForm, options) { if ($("#notice_data-text").get(0).value.length == 0) {
																				$("#form_notice").addClass("warning");
																				return false;
																		   }
																		   $("#form_notice").addClass("processing");
																		   $("#notice_action-submit").attr("disabled", "disabled");
																		   $("#notice_action-submit").addClass("disabled");
																		   return true;
												 						 },
					   timeout: '60000',
					   error: function (xhr, textStatus, errorThrown) {	$("#form_notice").removeClass("processing");
																		$("#notice_action-submit").removeAttr("disabled");
																		$("#notice_action-submit").removeClass("disabled");
																		if (textStatus == "timeout") {
																			alert ("Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists");
																		}
																		else {
																			if ($(".error", xhr.responseXML).length > 0) {
																				$('#form_notice').append(document._importNode($(".error", xhr.responseXML).get(0), true));
																			}
																			else {
																				var HTTP20x30x = [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307];
																				if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																					alert("Sorry! We had trouble sending your notice ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
																				}
																				else {
																					$("#notice_data-text").val("");
																					counter();
																				}
																			}
																		}
																	  },
					   success: function(xml) {	if ($("#error", xml).length > 0) {
													var result = document._importNode($("p", xml).get(0), true);
													result = result.textContent || result.innerHTML;
													alert(result);
												}
												else {
												    if ($("#command_result", xml).length > 0) {
													    var result = document._importNode($("p", xml).get(0), true);
													    result = result.textContent || result.innerHTML;
													    alert(result);
                                                    }
                                                    else {
                                                         li = $("li", xml).get(0);
                                                         if ($("#"+li.id).length == 0) {
                                                            var notice_irt_value = $('#notice_in-reply-to').val();
                                                            var notice_irt = '#notices_primary #notice-'+notice_irt_value;
                                                            if($('body')[0].id == 'conversation') {
                                                                if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
                                                                    $(notice_irt).append('

');
                                                                }
                                                                $($(notice_irt+' .notices')[0]).append(document._importNode(li, true));
                                                            }
                                                            else {
                                                                $("#notices_primary .notices").prepend(document._importNode(li, true));
                                                            }
                                                            $('#'+li.id).css({display:'none'});
                                                            $('#'+li.id).fadeIn(2500);
                                                            NoticeReply();
                                                            NoticeAttachments();
                                                         }
													}
													$("#notice_data-text").val("");
    												$("#notice_data-attach").val("");
                                                    $('#notice_data-attach_selected').remove();
                                                    counter();
												}
												$("#form_notice").removeClass("processing");
												$("#notice_action-submit").removeAttr("disabled");
												$("#notice_action-submit").removeClass("disabled");
											 }
					   };
	$("#form_notice").ajaxForm(PostNotice);
	$("#form_notice").each(addAjaxHidden);
    NoticeReply();
    NoticeAttachments();
    NoticeDataAttach();
});

function NoticeReply() {
    if ($('#notice_data-text').length > 0 && $('#content .notice_reply').length > 0) {
        $('#content .notice').each(function() {
            var notice = $(this)[0];
            $($('.notice_reply', notice)[0]).click(function() {
                var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname');
                NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
                return false;
            });
        });
    }
}

function NoticeReplySet(nick,id) {
	rgx_username = /^[0-9a-zA-Z\-_.]*$/;
	if (nick.match(rgx_username)) {
		replyto = "@" + nick + " ";
		if ($("#notice_data-text").length) {
			$("#notice_data-text").val(replyto);
			$("#form_notice input#notice_in-reply-to").val(id);
			$("#notice_data-text").focus();
			return false;
		}
	}
	return true;
}

function NoticeAttachments() {
    $.fn.jOverlay.options = {
        method : 'GET',
        data : '',
        url : '',
        color : '#000',
        opacity : '0.6',
        zIndex : 99,
        center : false,
        imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
        bgClickToClose : true,
        success : function() {
            $('#jOverlayContent').append('<button>×</button>');
            $('#jOverlayContent button').click($.closeOverlay);
        },
        timeout : 0,
        autoHide : true,
        css : {'max-width':'502px', 'top':'22.5%', 'left':'32.5%'}
    };

    $('#content .notice a.attachment').click(function() {
        $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
        return false;
    });

    var t;
    $("body:not(#shownotice) #content .notice a.thumbnail").hover(
        function() {
            var anchor = $(this);
            $("a.thumbnail").children('img').hide();
            anchor.closest(".entry-title").addClass('ov');

            if (anchor.children('img').length == 0) {
                t = setTimeout(function() {
                    $.get($('address .url')[0].href+'/attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
                        anchor.append(data);
                    });
                }, 500);
            }
            else {
                anchor.children('img').show();
            }
        },
        function() {
            clearTimeout(t);
            $("a.thumbnail").children('img').hide();
            $(this).closest(".entry-title").removeClass('ov');
        }
    );
}

function NoticeDataAttach() {
    NDA = $('#notice_data-attach');
    NDA.change(function() {
        S = '
'+$(this).val()+' <button>×</button>
';
        NDAS = $('#notice_data-attach_selected');
        (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#form_notice').append(S);
        $('#notice_data-attach_selected button').click(function(){
            $('#notice_data-attach_selected').remove();
            NDA.val('');
        });
    });
}
<commit_msg>Removed extra slash<commit_after>/*
 * Laconica - a distributed open-source microblogging tool
 * Copyright (C) 2008, Controlez-Vous, Inc.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

$(document).ready(function(){
	// count character on keyup
	function counter(event){
		var maxLength = 140;
		var currentLength = $("#notice_data-text").val().length;
		var remaining = maxLength - currentLength;
		var counter = $("#notice_text-count");
		counter.text(remaining);

		if (remaining <= 0) {
			$("#form_notice").addClass("warning");
		} else {
			$("#form_notice").removeClass("warning");
		}
	}

	function submitonreturn(event) {
		if (event.keyCode == 13) {
			$("#form_notice").submit();
			event.preventDefault();
			event.stopPropagation();
			return false;
		}
		return true;
	}

	if ($("#notice_data-text").length) {
		$("#notice_data-text").bind("keyup", counter);
		$("#notice_data-text").bind("keydown", submitonreturn);

		// run once in case there's something in there
		counter();

		// set the focus
		$("#notice_data-text").focus();
	}

	// XXX: refactor this code

	var favoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var dis = new_form.id;
												var fav = dis.replace('disfavor', 'favor');
												$('form#'+fav).replaceWith(new_form);
												$('form#'+dis).ajaxForm(disoptions).each(addAjaxHidden);
											  }
					 };

	var disoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var fav = new_form.id;
												var dis = fav.replace('favor', 'disfavor');
												$('form#'+dis).replaceWith(new_form);
												$('form#'+fav).ajaxForm(favoptions).each(addAjaxHidden);
											  }
					 };

	var joinoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var leave = new_form.id;
												var join = leave.replace('leave', 'join');
												$('form#'+join).replaceWith(new_form);
												$('form#'+leave).ajaxForm(leaveoptions).each(addAjaxHidden);
											  }
					 };

	var leaveoptions = { dataType: 'xml',
					   success: function(xml) { var new_form = document._importNode($('form', xml).get(0), true);
												var join = new_form.id;
												var leave = join.replace('join', 'leave');
												$('form#'+leave).replaceWith(new_form);
												$('form#'+join).ajaxForm(joinoptions).each(addAjaxHidden);
											  }
					 };

	function addAjaxHidden() {
		var ajax = document.createElement('input');
		ajax.setAttribute('type', 'hidden');
		ajax.setAttribute('name', 'ajax');
		ajax.setAttribute('value', 1);
		this.appendChild(ajax);
	}

	$("form.form_favor").ajaxForm(favoptions);
	$("form.form_disfavor").ajaxForm(disoptions);
	$("form.form_group_join").ajaxForm(joinoptions);
	$("form.form_group_leave").ajaxForm(leaveoptions);
	$("form.form_favor").each(addAjaxHidden);
	$("form.form_disfavor").each(addAjaxHidden);
	$("form.form_group_join").each(addAjaxHidden);
	$("form.form_group_leave").each(addAjaxHidden);

	$("#form_user_nudge").ajaxForm ({ dataType: 'xml',
		beforeSubmit: function(xml) { $("#form_user_nudge input[type=submit]").attr("disabled", "disabled");
									  $("#form_user_nudge input[type=submit]").addClass("disabled");
									},
		success: function(xml) { $("#form_user_nudge").replaceWith(document._importNode($("#nudge_response", xml).get(0),true));
							     $("#form_user_nudge input[type=submit]").removeAttr("disabled");
							     $("#form_user_nudge input[type=submit]").removeClass("disabled");
							   }
	 });
	$("#form_user_nudge").each(addAjaxHidden);

	var Subscribe = { dataType: 'xml',
					  beforeSubmit: function(formData, jqForm, options) { $(".form_user_subscribe input[type=submit]").attr("disabled", "disabled");
																	      $(".form_user_subscribe input[type=submit]").addClass("disabled");
																	    },
					  success: function(xml) { var form_unsubscribe = document._importNode($('form', xml).get(0), true);
										  	   var form_unsubscribe_id = form_unsubscribe.id;
											   var form_subscribe_id = form_unsubscribe_id.replace('unsubscribe', 'subscribe');
											   $("form#"+form_subscribe_id).replaceWith(form_unsubscribe);
											   $("form#"+form_unsubscribe_id).ajaxForm(UnSubscribe).each(addAjaxHidden);
											   $("dd.subscribers").text(parseInt($("dd.subscribers").text())+1);
											   $(".form_user_subscribe input[type=submit]").removeAttr("disabled");
											   $(".form_user_subscribe input[type=submit]").removeClass("disabled");
										     }
					};

	var UnSubscribe = { dataType: 'xml',
						beforeSubmit: function(formData, jqForm, options) { $(".form_user_unsubscribe input[type=submit]").attr("disabled", "disabled");
																		    $(".form_user_unsubscribe input[type=submit]").addClass("disabled");
																		  },
					    success: function(xml) { var form_subscribe = document._importNode($('form', xml).get(0), true);
										  		 var form_subscribe_id = form_subscribe.id;
												 var form_unsubscribe_id = form_subscribe_id.replace('subscribe', 'unsubscribe');
												 $("form#"+form_unsubscribe_id).replaceWith(form_subscribe);
												 $("form#"+form_subscribe_id).ajaxForm(Subscribe).each(addAjaxHidden);
												 $("#profile_send_a_new_message").remove();
												 $("#profile_nudge").remove();
											     $("dd.subscribers").text(parseInt($("dd.subscribers").text())-1);
												 $(".form_user_unsubscribe input[type=submit]").removeAttr("disabled");
												 $(".form_user_unsubscribe input[type=submit]").removeClass("disabled");
											   }
					  };

	$(".form_user_subscribe").ajaxForm(Subscribe);
	$(".form_user_unsubscribe").ajaxForm(UnSubscribe);
	$(".form_user_subscribe").each(addAjaxHidden);
	$(".form_user_unsubscribe").each(addAjaxHidden);

	var PostNotice = { dataType: 'xml',
					   beforeSubmit: function(formData, jqForm, options) { if ($("#notice_data-text").get(0).value.length == 0) {
																				$("#form_notice").addClass("warning");
																				return false;
																		   }
																		   $("#form_notice").addClass("processing");
																		   $("#notice_action-submit").attr("disabled", "disabled");
																		   $("#notice_action-submit").addClass("disabled");
																		   return true;
												 						 },
					   timeout: '60000',
					   error: function (xhr, textStatus, errorThrown) {	$("#form_notice").removeClass("processing");
																		$("#notice_action-submit").removeAttr("disabled");
																		$("#notice_action-submit").removeClass("disabled");
																		if (textStatus == "timeout") {
																			alert ("Sorry! We had trouble sending your notice. The servers are overloaded. Please try again, and contact the site administrator if this problem persists");
																		}
																		else {
																			if ($(".error", xhr.responseXML).length > 0) {
																				$('#form_notice').append(document._importNode($(".error", xhr.responseXML).get(0), true));
																			}
																			else {
																				var HTTP20x30x = [200, 201, 202, 203, 204, 205, 206, 300, 301, 302, 303, 304, 305, 306, 307];
																				if(jQuery.inArray(parseInt(xhr.status), HTTP20x30x) < 0) {
																					alert("Sorry! We had trouble sending your notice ("+xhr.status+" "+xhr.statusText+"). Please report the problem to the site administrator if this happens again.");
																				}
																				else {
																					$("#notice_data-text").val("");
																					counter();
																				}
																			}
																		}
																	  },
					   success: function(xml) {	if ($("#error", xml).length > 0) {
													var result = document._importNode($("p", xml).get(0), true);
													result = result.textContent || result.innerHTML;
													alert(result);
												}
												else {
												    if ($("#command_result", xml).length > 0) {
													    var result = document._importNode($("p", xml).get(0), true);
													    result = result.textContent || result.innerHTML;
													    alert(result);
                                                    }
                                                    else {
                                                         li = $("li", xml).get(0);
                                                         if ($("#"+li.id).length == 0) {
                                                            var notice_irt_value = $('#notice_in-reply-to').val();
                                                            var notice_irt = '#notices_primary #notice-'+notice_irt_value;
                                                            if($('body')[0].id == 'conversation') {
                                                                if(notice_irt_value.length > 0 && $(notice_irt+' .notices').length < 1) {
                                                                    $(notice_irt).append('

');
                                                                }
                                                                $($(notice_irt+' .notices')[0]).append(document._importNode(li, true));
                                                            }
                                                            else {
                                                                $("#notices_primary .notices").prepend(document._importNode(li, true));
                                                            }
                                                            $('#'+li.id).css({display:'none'});
                                                            $('#'+li.id).fadeIn(2500);
                                                            NoticeReply();
                                                            NoticeAttachments();
                                                         }
													}
													$("#notice_data-text").val("");
    												$("#notice_data-attach").val("");
                                                    $('#notice_data-attach_selected').remove();
                                                    counter();
												}
												$("#form_notice").removeClass("processing");
												$("#notice_action-submit").removeAttr("disabled");
												$("#notice_action-submit").removeClass("disabled");
											 }
					   };
	$("#form_notice").ajaxForm(PostNotice);
	$("#form_notice").each(addAjaxHidden);
    NoticeReply();
    NoticeAttachments();
    NoticeDataAttach();
});

function NoticeReply() {
    if ($('#notice_data-text').length > 0 && $('#content .notice_reply').length > 0) {
        $('#content .notice').each(function() {
            var notice = $(this)[0];
            $($('.notice_reply', notice)[0]).click(function() {
                var nickname = ($('.author .nickname', notice).length > 0) ? $($('.author .nickname', notice)[0]) : $('.author .nickname');
                NoticeReplySet(nickname.text(), $($('.notice_id', notice)[0]).text());
                return false;
            });
        });
    }
}

function NoticeReplySet(nick,id) {
	rgx_username = /^[0-9a-zA-Z\-_.]*$/;
	if (nick.match(rgx_username)) {
		replyto = "@" + nick + " ";
		if ($("#notice_data-text").length) {
			$("#notice_data-text").val(replyto);
			$("#form_notice input#notice_in-reply-to").val(id);
			$("#notice_data-text").focus();
			return false;
		}
	}
	return true;
}

function NoticeAttachments() {
    $.fn.jOverlay.options = {
        method : 'GET',
        data : '',
        url : '',
        color : '#000',
        opacity : '0.6',
        zIndex : 99,
        center : false,
        imgLoading : $('address .url')[0].href+'theme/base/images/illustrations/illu_progress_loading-01.gif',
        bgClickToClose : true,
        success : function() {
            $('#jOverlayContent').append('<button>×</button>');
            $('#jOverlayContent button').click($.closeOverlay);
        },
        timeout : 0,
        autoHide : true,
        css : {'max-width':'502px', 'top':'22.5%', 'left':'32.5%'}
    };

    $('#content .notice a.attachment').click(function() {
        $().jOverlay({url: $('address .url')[0].href+'attachment/' + ($(this).attr('id').substring('attachment'.length + 1)) + '/ajax'});
        return false;
    });

    var t;
    $("body:not(#shownotice) #content .notice a.thumbnail").hover(
        function() {
            var anchor = $(this);
            $("a.thumbnail").children('img').hide();
            anchor.closest(".entry-title").addClass('ov');

            if (anchor.children('img').length == 0) {
                t = setTimeout(function() {
                    $.get($('address .url')[0].href+'attachment/' + (anchor.attr('id').substring('attachment'.length + 1)) + '/thumbnail', null, function(data) {
                        anchor.append(data);
                    });
                }, 500);
            }
            else {
                anchor.children('img').show();
            }
        },
        function() {
            clearTimeout(t);
            $("a.thumbnail").children('img').hide();
            $(this).closest(".entry-title").removeClass('ov');
        }
    );
}

function NoticeDataAttach() {
    NDA = $('#notice_data-attach');
    NDA.change(function() {
        S = '
'+$(this).val()+' <button>×</button>
';
        NDAS = $('#notice_data-attach_selected');
        (NDAS.length > 0) ? NDAS.replaceWith(S) : $('#form_notice').append(S);
        $('#notice_data-attach_selected button').click(function(){
            $('#notice_data-attach_selected').remove();
            NDA.val('');
        });
    });
}
<|endoftext|>


<commit_before>(function() {
    "use strict";
    var btn = document.getElementById('calc');

    btn.onclick = function(e){

        var startHourField = document.getElementById('start-hour'),
            startHour = parseInt(document.getElementById('start-hour').value),

            startMinuteField = document.getElementById('start-minute'),
            startMinute = parseInt(document.getElementById('start-minute').value),

            startAmPm = document.querySelector('input[name = start-am-pm]:checked').value,

            endHourField = document.getElementById('end-hour'),
            endHour = parseInt(document.getElementById('end-hour').value),

            endMinuteField = document.getElementById('end-minute'),
            endMinute = parseInt(document.getElementById('end-minute').value),

            endAmPm = document.querySelector('input[name = end-am-pm]:checked').value,

            lunchTaken = document.querySelector('input[name = lunch]:checked').value,
            validateHour = /^([1-9]|1[0-2])$/,
            validateMinute = /^[0-5]?[0-9]$/,
            hourError = '
Please enter a number from 1 to 12.
',
            minuteError = '
Please enter a number from 0 to 59.
',
            answer = document.getElementById('answer'),
            allTextInput = [startHourField, startMinuteField, endHourField, endMinuteField],
            errorCheck = true,
            startToMinutes,
            endToMinutes,
            minutesDiff,
            hourFinal,
            minuteFinal,
            hourOutput,
            minuteOutput;

            allTextInput.forEach(function(i) {
                i.classList.remove('error');
            });

            // Validate start hour entered
            if (isNaN(startHour) || !validateHour.test(startHour)) {
                startHourField.classList.add('error');
                answer.innerHTML = hourError;
                errorCheck = false;
                return false;
            }

            // Validate end hour entered
            if (isNaN(endHour) || !validateHour.test(endHour)) {
                endHourField.classList.add('error');
                answer.innerHTML = hourError;
                errorCheck = false;
                return false;
            }

            // Validate start minute entered
            if (isNaN(startMinute) || !validateMinute.test(startMinute)) {
                startMinuteField.classList.add('error');
                answer.innerHTML = minuteError;
                errorCheck = false;
                return false;
            }

            // Validate end minute entered
            if (isNaN(endMinute) || !validateMinute.test(endMinute)) {
                endMinuteField.classList.add('error');
                answer.innerHTML = minuteError;
                errorCheck = false;
                return false;
            }

            // Allows for AM/PM calculation
            if (startAmPm === 'pm' && startHour != 12) {
                startHour += 12;
            }

            // Allows for AM/PM calculation
            if (endAmPm === 'pm' && endHour != 12) {
                endHour += 12;
            }

            // Convert to total minutes
            startToMinutes = ((startHour * 60) + startMinute);
            endToMinutes = ((endHour * 60) + endMinute);

            minutesDiff = (endToMinutes - startToMinutes);

            // Removes 30 minutes if lunch was taken
            if (lunchTaken === 'yes') {
                minutesDiff -= 30;
            }

            hourFinal = Math.floor(minutesDiff / 60);
            minuteFinal = (minutesDiff % 60);

            // Determines proper output of hour/hours and minute/minutes
            if (hourFinal === 1) {
                hourOutput = 'hour';
            } else {
                hourOutput = 'hours';
            }

            if (minuteFinal === 1) {
                minuteOutput = 'minute';
            } else {
                minuteOutput = 'minutes';
            }

            // Outputs final answer

            if (errorCheck === true) {
                answer.innerHTML = '
Total time is ' + hourFinal + ' ' + hourOutput +
            ' and ' + minuteFinal + ' ' + minuteOutput + '.' + '
';
            } else {
                answer.innerHTML = '
Please enter a valid number.
';
                return false;
            };

        e.preventDefault();
    };

    var clr = document.getElementById('clear');

    clr.onclick = function(){

        // Removes previous output
        window.location.reload();
    };

})();<commit_msg>Accomodated for 0 hours or 0 minutes in final answer<commit_after>(function() {
    "use strict";
    var btn = document.getElementById('calc');

    btn.onclick = function(e){

        var startHourField = document.getElementById('start-hour'),
            startHour = parseInt(document.getElementById('start-hour').value),

            startMinuteField = document.getElementById('start-minute'),
            startMinute = parseInt(document.getElementById('start-minute').value),

            startAmPm = document.querySelector('input[name = start-am-pm]:checked').value,

            endHourField = document.getElementById('end-hour'),
            endHour = parseInt(document.getElementById('end-hour').value),

            endMinuteField = document.getElementById('end-minute'),
            endMinute = parseInt(document.getElementById('end-minute').value),

            endAmPm = document.querySelector('input[name = end-am-pm]:checked').value,

            lunchTaken = document.querySelector('input[name = lunch]:checked').value,
            validateHour = /^([1-9]|1[0-2])$/,
            validateMinute = /^[0-5]?[0-9]$/,
            hourError = '
Please enter a number from 1 to 12.
',
            minuteError = '
Please enter a number from 0 to 59.
',
            answer = document.getElementById('answer'),
            allTextInput = [startHourField, startMinuteField, endHourField, endMinuteField],
            errorCheck = true,
            startToMinutes,
            endToMinutes,
            minutesDiff,
            hourFinal,
            minuteFinal,
            hourOutput,
            minuteOutput;

            allTextInput.forEach(function(i) {
                i.classList.remove('error');
            });

            // Validate start hour entered
            if (isNaN(startHour) || !validateHour.test(startHour)) {
                startHourField.classList.add('error');
                answer.innerHTML = hourError;
                errorCheck = false;
                return false;
            }

            // Validate end hour entered
            if (isNaN(endHour) || !validateHour.test(endHour)) {
                endHourField.classList.add('error');
                answer.innerHTML = hourError;
                errorCheck = false;
                return false;
            }

            // Validate start minute entered
            if (isNaN(startMinute) || !validateMinute.test(startMinute)) {
                startMinuteField.classList.add('error');
                answer.innerHTML = minuteError;
                errorCheck = false;
                return false;
            }

            // Validate end minute entered
            if (isNaN(endMinute) || !validateMinute.test(endMinute)) {
                endMinuteField.classList.add('error');
                answer.innerHTML = minuteError;
                errorCheck = false;
                return false;
            }

            // Allows for AM/PM calculation
            if (startAmPm === 'pm' && startHour != 12) {
                startHour += 12;
            }

            // Allows for AM/PM calculation
            if (endAmPm === 'pm' && endHour != 12) {
                endHour += 12;
            }

            // Convert to total minutes
            startToMinutes = ((startHour * 60) + startMinute);
            endToMinutes = ((endHour * 60) + endMinute);

            minutesDiff = (endToMinutes - startToMinutes);

            // Removes 30 minutes if lunch was taken
            if (lunchTaken === 'yes') {
                minutesDiff -= 30;
            }

            hourFinal = Math.floor(minutesDiff / 60);
            minuteFinal = (minutesDiff % 60);

            // Determines proper output of hour/hours and minute/minutes
            if (hourFinal === 1) {
                hourOutput = 'hour';
            } else {
                hourOutput = 'hours';
            }

            if (minuteFinal === 1) {
                minuteOutput = 'minute';
            } else {
                minuteOutput = 'minutes';
            }

            // Outputs final answer
            if (errorCheck === true) {
                if (hourFinal === 0) {
                    answer.innerHTML = '
Total time is ' + minuteFinal + ' ' + minuteOutput + '.' + '
';
                } else if (minuteFinal === 0) {
                    answer.innerHTML = '
Total time is ' + hourFinal + ' ' + hourOutput + '.' + '
';
                } else {
                    answer.innerHTML = '
Total time is ' + hourFinal + ' ' + hourOutput +
                ' and ' + minuteFinal + ' ' + minuteOutput + '.' + '
';
                }
            } else {
                answer.innerHTML = '
Please enter a valid number.
';
                return false;
            }

        e.preventDefault();
    };

    var clr = document.getElementById('clear');

    clr.onclick = function(){

        // Removes previous output
        window.location.reload();
    };

})();<|endoftext|>


<commit_before>//Wait for the document to be ready
jQuery(document).ready(function($) {
	/**
	 *  ======== OPTIONS =======
	 */

	/** Pull in all of the data first
	* We have three sources of data
	*	- Top16Terms.tab: The definition of our top 20 categories - A list of the category ID and it's associated terms
	*	- xy_top100.json: The starting x,y position for each node, in JSON. The format is:
	*		- { nodeKey: [x, y] }
	*	- table.tsv: The full table with all information about each node. Will get pulled in as an array of nodes objects.
	*/
	d3.tsv("data/Top16Terms.tab", function(error, terms) {
		$.getJSON("data/xy_top100.json", function(coords){
			d3.tsv("data/filtered_table.txt", function(err, table){

				//Get the column names from the terms data
				categoryID = Object.keys(terms[0])[0];

				//Set up some basic configuration for the SVG
				var width  = 830,
				    height = 830,
				    scale = configuration.scale || 1,
				    radius = Math.min(width, height) / 2,
				    arcWidth = (Math.PI * 2 * radius)/terms.length;

				//Create the SVG element and center it in it's parent element
				var svg = d3.select(configuration.parentEl || "body").append("svg")
				    .attr("width",  width)
				    .attr("height", height)
				    .attr("viewBox", "0,0," + width + "," + height*scale)
				    .append("g")
				    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

				drawArcs();
				//drawNodes();

				/*
				 * drawArcs creates the SVG and draws the donut shape with each of the categories as an equally-sized arc of the donut.
				 */
				function drawArcs(){

					//Create a d3 arc shape with an inner and outer radius
					var arc = d3.svg.arc()
					    .outerRadius(radius)
					    .innerRadius(radius - (configuration.arcThickness || 70));

					//Create a d3 pie layout
					var pie = d3.layout.pie()
					    .value(function(d) { return 1; });

					  //Draw a group element to group our arcs
					  var g = svg.selectAll(".arc")
					      .data(pie(terms))
					      .enter().append("g")
					      .attr("class", "arcs");

					  //Draw the path for each arc
					  g.append("path")
					      .attr("d", arc)
					      .attr("class", "arc")
					      //Bind the categoryID to each arc so it is accessible via jQuery and d3
					      .attr("data-category", function(d){ return d.data[categoryID]; })
					      .attr("id", function(d){ return "arc-" + d.data[categoryID]; })
					      .style("fill", function(d) {
					    	  //Find the color for this arc by finding it in the category->color map
					    	  return colors[d.data[categoryID]][0];
					    	})
					      //This will happen when a user clicks on an arc
				          .on("click", function(d){
				        	  selectCategory(this, d.data.categoryID);
					      });

					  var labels = svg.selectAll(".arc-label")
								      .data(categoryLabels)
								      .enter().append("g");

				    var idsAdded = new Array();
					labels.append("text")
						  .attr("class", "arc-label category-label")
						  .style("fill", function(d){
							  return colors[d.id][1];
						  })
						  .attr("dy", function(d){
							  var i = 0,
							  	  count = 0;
							  while(i > -1){
								  i = idsAdded.indexOf(d.id, i+count);
								  if(i > -1) count++;
							  }
							  idsAdded.push(d.id);
							  return 20 + (20*count);
						  })
						  .attr("dx", function(d){
							  //Determine the horizontal offset by finding the leftover space in the arc width and divinding by two, essentially "centering" the text
							  //Create a DOM element with the label text inside in order to get a pixel width
							  var span = $(document.createElement("span")).text(d.text).addClass("arc-label");
							  $("body").append(span);
							  var textWidth = $(span).width();
							  $(span).detach(); //remove it, it was only temporary

							  var xOffset = (arcWidth - textWidth)/2;
							  if(xOffset < 0) return 0;
							  else return xOffset;
						  })
						  .attr("data-category", function(d){
							  return d.id;
						  })
						  .on("click", function(d){
							//Get the arc path that corresponds to this label
							selectCategory(document.getElementById("arc-" + d.id), d.id);
						  })
						  .append("textPath")
				   	      .text(function(d) {
				   	         return d.text;
						  })
						  .attr("xlink:href", function(d){ return "#arc-" + d.id; });
				}

				function drawNodes(){

					//Access the data with the object keys (unique ids)
					var keys = Object.keys(coords);

					var nodes = [];
					// The largest node for each cluster.
					var clusters = new Array(m);

					//Make an array of the coords
					$.each(keys, function(i, key){
						var node = $.grep(table, function(e){ return e.primaryKey == key; });
						var category100 = node[0].maxtopic100selected_id;
						var category20 = node[0].maxtopic20selected_id;

						var d = {
							x: coords[key][0],
							y: coords[key][1],
							px: coords[key][0],
							py: coords[key][1],
							key: key,
							cluster: category100,
							category: category20,
							color: category20,
							radius: 4
						};
						if (!clusters[i] || (r > clusters[i].radius)) clusters[i] = d;
						nodes.push(d);
					});

					//Set up the dimensions of our svg drawing
					//var margin = {left: 100, right: 100, top: 100, bottom: 100},
					var	padding = 2, // separation between same-color nodes
				    	clusterPadding = 4, // separation between different-color nodes
				    	maxRadius = 4;

					//Find the min and max values
					var xMin = d3.min(keys, function(d){ return coords[d][0]; }),
						xMax = d3.max(keys, function(d){ return coords[d][0]; }),
						yMin = d3.min(keys, function(d){ return coords[d][1]; }),
						yMax = d3.max(keys, function(d){ return coords[d][1]; });

					//Set up the scale on the x-axis using the min and max x values
					/*var xScale = d3.scale.linear()
					  			   .domain([xMin, xMax])
					  			   .range([margin.left, width - margin.right]);

					//Set up the scale on the y-axis using the min and max y values
					var yScale = d3.scale.linear()
								   .domain([yMin, yMax])
								   .range([margin.top, height - margin.bottom]);*/

					var n = keys.length, // total number of nodes
				    	m = 16; // number of distinct clusters

					var force = d3.layout.force()
								   .nodes(nodes)
								   .size([width, height])
								   .gravity(.60)
								 //.charge(50)
								 //.chargeDistance(10)
								 //.theta(.01)
								   .on("tick", tick)
								   .start();

					//Start the timeout so the animation doesn't last forever
					var timeout = window.setTimeout(start, 10000);

					var nodeGroup = svg.append("g")
					                   .attr("class", "node-group")
					                   .attr("transform", "translate(" + width/-2 + "," + height/-2 + ")");

					var node = nodeGroup.selectAll("circle")
				    			  .data(nodes)
				                  .enter().append("circle")
				  	              .attr("class", "node")
				  	              .attr("data-category", function(d){
				  	            	  return d.category;
				  	              })
				  	              .attr("data-key", function(d){
				  	            	  return d.key;
				  	              })
				  	              .style("fill", function(d) { return colors[d.color][0]; })
							   /* .attr("transform",  function(d){
							    	console.log("plotting");
							    	var value = "translate(";
							    	value += xScale(d.x);
							    	value += ",";
							    	value += yScale(d.y);
							    	value += ")";
							    	return value;
							    }); */
							    //.call(force.drag);

					function start(){
						force.stop();
						window.clearTimeout(timeout);
					}

					//force.start();

					node.transition()
					    .duration(5)
					    .delay(function(d, i) { return i * 2; })
					    .attrTween("r", function(d) {
					         var i = d3.interpolate(0, d.radius);
					         return function(t) { return d.radius = i(t); };
					    });

					function tick(e) {
					  node.each(cluster(10 * e.alpha * e.alpha))
					      .each(collide(.5))
					      .attr("cx", function(d) { return d.x; })
					      .attr("cy", function(d) { return d.y; });
					}

					// Move d to be adjacent to the cluster node.
					function cluster(alpha) {
					  return function(d) {
					    var cluster = clusters[d.cluster];
					    if (cluster === d) return;
					    var x = d.x - cluster.x,
					        y = d.y - cluster.y,
					        l = Math.sqrt(x * x + y * y),
					        r = d.radius + cluster.radius;
					    if (l != r) {
					      l = (l - r) / l * alpha;
					      d.x -= x *= l;
					      d.y -= y *= l;
					      cluster.x += x;
					      cluster.y += y;
					    }
					  };
					}

					// Resolves collisions between d and all other circles.
					function collide(alpha) {
					  var quadtree = d3.geom.quadtree(nodes);
					  return function(d) {
					    var r = d.radius + maxRadius + Math.max(padding, clusterPadding),
					        nx1 = d.x - r,
					        nx2 = d.x + r,
					        ny1 = d.y - r,
					        ny2 = d.y + r;
					    quadtree.visit(function(quad, x1, y1, x2, y2) {
					      if (quad.point && (quad.point !== d)) {
					        var x = d.x - quad.point.x,
					            y = d.y - quad.point.y,
					            l = Math.sqrt(x * x + y * y),
					            r = d.radius + quad.point.radius + (d.cluster === quad.point.cluster ? padding : clusterPadding);
					        if (l < r) {
					          l = (l - r) / l * alpha;
					          d.x -= x *= l;
					          d.y -= y *= l;
					          quad.point.x += x;
					          quad.point.y += y;
					        }
					      }
					      return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
					    });
					  };
					}
			}

			function selectNodes(category){
				d3.selectAll(".node")
				 // .attr("r", 2);
				  .style("opacity", function(d){
					  var key = $(this).attr("data-key");
					  var row = $.grep(table, function(e){ return e.primaryKey == key; });
					  var categoryName = "lda020selected_topicWeights_" + category;
					  return row[0][categoryName];
				  });

				/*d3.selectAll("[data-category='"+category+"']")
				  .attr("r", function(d){
					  return 6;
				  })
				  .attr("stroke", "#FFFFFF")
				  .attr("stroke-width", "2")
				  .style("opacity", function(d){
					  var key = $(this).attr("data-key");
					  var row = $.grep(table, function(e){ return e.primaryKey == key; });
					  var categoryName = "lda020selected_topicWeights_ " + category;
					  console.log(row[0][categoryName]);
					  return row[0][categoryName];
				  });*/
			}

			function resetNodes(){
				d3.selectAll(".node")
				  .style("opacity", "1");
			}

			/*
			 * Select the specified category and "filter" the nodes related to that category
			 */
			function selectCategory(element, category){
				  //If this arc is already selected...
	        	  if(d3.select(element).classed("selected")){

	        		  //Change all the other arc colors back to normal
	        		  $("path.arc").css("fill", function(){
	        			  return colors[$(this).attr("data-category")][0];
	        		  });

	        		  //Change all the other arc labels back to normal
	        		  $(".arc-label").css("fill", function(){
	        			 return colors[$(this).attr("data-category")][1];
	        		  });

	        		  //Make the new list of classes and add them
	        		  var newClasses = $(element).attr("class").replace("selected", "");
	        		  $(element).attr("class", newClasses);

	        		  //Reset the nodes
	        		  resetNodes();
	        	  }
	        	  // If this is a new selection...
	        	  else{
	        		  //Select all the other arcs and color them as inactive
	        		  $("path.arc").css("fill", (configuration.inactiveArcColor || "#F0F0F0"));
	        		  $(".arc-label").css("fill", (configuration.inactiveLabelColor || "#999999"));

	        		  //Select any other arc that is marked as "selected" and remove that class
	        		  $("path.arc.selected").each(function(i, arc){
	        			  var newClasses = $(arc).attr("class").replace("selected", "");
		    	          $(arc).attr("class", newClasses);
	        		  });

	        		  //Then select the active arc and recolor it as its original color
	        		  var currentClasses = $(element).attr("class");
	        		  $(element)
	    	            .css("fill", colors[category][0])
	    	            .attr("class", currentClasses + " selected");

	        		  //Find the arc label that goes with this arc and recolor it
	        		  $("[data-category='" + category + "'].arc-label")
	        		       .css("fill", colors[category][1]);

	    	          //Call our function that will manipulate the nodes for this category
	        		  selectNodes(category);
	        	  }
			}

			});
		});
	});
});<commit_msg>Remember to draw nodes<commit_after>//Wait for the document to be ready
jQuery(document).ready(function($) {
	/**
	 *  ======== OPTIONS =======
	 */

	/** Pull in all of the data first
	* We have three sources of data
	*	- Top16Terms.tab: The definition of our top 20 categories - A list of the category ID and it's associated terms
	*	- xy_top100.json: The starting x,y position for each node, in JSON. The format is:
	*		- { nodeKey: [x, y] }
	*	- table.tsv: The full table with all information about each node. Will get pulled in as an array of nodes objects.
	*/
	d3.tsv("data/Top16Terms.tab", function(error, terms) {
		$.getJSON("data/xy_top100.json", function(coords){
			d3.tsv("data/filtered_table.txt", function(err, table){

				//Get the column names from the terms data
				categoryID = Object.keys(terms[0])[0];

				//Set up some basic configuration for the SVG
				var width  = 830,
				    height = 830,
				    scale = configuration.scale || 1,
				    radius = Math.min(width, height) / 2,
				    arcWidth = (Math.PI * 2 * radius)/terms.length;

				//Create the SVG element and center it in it's parent element
				var svg = d3.select(configuration.parentEl || "body").append("svg")
				    .attr("width",  width)
				    .attr("height", height)
				    .attr("viewBox", "0,0," + width + "," + height*scale)
				    .append("g")
				    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

				drawArcs();
				drawNodes();

				/*
				 * drawArcs creates the SVG and draws the donut shape with each of the categories as an equally-sized arc of the donut.
				 */
				function drawArcs(){

					//Create a d3 arc shape with an inner and outer radius
					var arc = d3.svg.arc()
					    .outerRadius(radius)
					    .innerRadius(radius - (configuration.arcThickness || 70));

					//Create a d3 pie layout
					var pie = d3.layout.pie()
					    .value(function(d) { return 1; });

					  //Draw a group element to group our arcs
					  var g = svg.selectAll(".arc")
					      .data(pie(terms))
					      .enter().append("g")
					      .attr("class", "arcs");

					  //Draw the path for each arc
					  g.append("path")
					      .attr("d", arc)
					      .attr("class", "arc")
					      //Bind the categoryID to each arc so it is accessible via jQuery and d3
					      .attr("data-category", function(d){ return d.data[categoryID]; })
					      .attr("id", function(d){ return "arc-" + d.data[categoryID]; })
					      .style("fill", function(d) {
					    	  //Find the color for this arc by finding it in the category->color map
					    	  return colors[d.data[categoryID]][0];
					    	})
					      //This will happen when a user clicks on an arc
				          .on("click", function(d){
				        	  selectCategory(this, d.data.categoryID);
					      });

					  var labels = svg.selectAll(".arc-label")
								      .data(categoryLabels)
								      .enter().append("g");

				    var idsAdded = new Array();
					labels.append("text")
						  .attr("class", "arc-label category-label")
						  .style("fill", function(d){
							  return colors[d.id][1];
						  })
						  .attr("dy", function(d){
							  var i = 0,
							  	  count = 0;
							  while(i > -1){
								  i = idsAdded.indexOf(d.id, i+count);
								  if(i > -1) count++;
							  }
							  idsAdded.push(d.id);
							  return 20 + (20*count);
						  })
						  .attr("dx", function(d){
							  //Determine the horizontal offset by finding the leftover space in the arc width and divinding by two, essentially "centering" the text
							  //Create a DOM element with the label text inside in order to get a pixel width
							  var span = $(document.createElement("span")).text(d.text).addClass("arc-label");
							  $("body").append(span);
							  var textWidth = $(span).width();
							  $(span).detach(); //remove it, it was only temporary

							  var xOffset = (arcWidth - textWidth)/2;
							  if(xOffset < 0) return 0;
							  else return xOffset;
						  })
						  .attr("data-category", function(d){
							  return d.id;
						  })
						  .on("click", function(d){
							//Get the arc path that corresponds to this label
							selectCategory(document.getElementById("arc-" + d.id), d.id);
						  })
						  .append("textPath")
				   	      .text(function(d) {
				   	         return d.text;
						  })
						  .attr("xlink:href", function(d){ return "#arc-" + d.id; });
				}

				function drawNodes(){

					//Access the data with the object keys (unique ids)
					var keys = Object.keys(coords);

					var nodes = [];
					// The largest node for each cluster.
					var clusters = new Array(m);

					//Make an array of the coords
					$.each(keys, function(i, key){
						var node = $.grep(table, function(e){ return e.primaryKey == key; });
						var category100 = node[0].maxtopic100selected_id;
						var category20 = node[0].maxtopic20selected_id;

						var d = {
							x: coords[key][0],
							y: coords[key][1],
							px: coords[key][0],
							py: coords[key][1],
							key: key,
							cluster: category100,
							category: category20,
							color: category20,
							radius: 4
						};
						if (!clusters[i] || (r > clusters[i].radius)) clusters[i] = d;
						nodes.push(d);
					});

					//Set up the dimensions of our svg drawing
					//var margin = {left: 100, right: 100, top: 100, bottom: 100},
					var	padding = 2, // separation between same-color nodes
				    	clusterPadding = 4, // separation between different-color nodes
				    	maxRadius = 4;

					//Find the min and max values
					var xMin = d3.min(keys, function(d){ return coords[d][0]; }),
						xMax = d3.max(keys, function(d){ return coords[d][0]; }),
						yMin = d3.min(keys, function(d){ return coords[d][1]; }),
						yMax = d3.max(keys, function(d){ return coords[d][1]; });

					//Set up the scale on the x-axis using the min and max x values
					/*var xScale = d3.scale.linear()
					  			   .domain([xMin, xMax])
					  			   .range([margin.left, width - margin.right]);

					//Set up the scale on the y-axis using the min and max y values
					var yScale = d3.scale.linear()
								   .domain([yMin, yMax])
								   .range([margin.top, height - margin.bottom]);*/

					var n = keys.length, // total number of nodes
				    	m = 16; // number of distinct clusters

					var force = d3.layout.force()
								   .nodes(nodes)
								   .size([width, height])
								   .gravity(.60)
								 //.charge(50)
								 //.chargeDistance(10)
								 //.theta(.01)
								   .on("tick", tick)
								   .start();

					//Start the timeout so the animation doesn't last forever
					var timeout = window.setTimeout(start, 10000);

					var nodeGroup = svg.append("g")
					                   .attr("class", "node-group")
					                   .attr("transform", "translate(" + width/-2 + "," + height/-2 + ")");

					var node = nodeGroup.selectAll("circle")
				    			  .data(nodes)
				                  .enter().append("circle")
				  	              .attr("class", "node")
				  	              .attr("data-category", function(d){
				  	            	  return d.category;
				  	              })
				  	              .attr("data-key", function(d){
				  	            	  return d.key;
				  	              })
				  	              .style("fill", function(d) { return colors[d.color][0]; })
							   /* .attr("transform",  function(d){
							    	console.log("plotting");
							    	var value = "translate(";
							    	value += xScale(d.x);
							    	value += ",";
							    	value += yScale(d.y);
							    	value += ")";
							    	return value;
							    }); */
							    //.call(force.drag);

					function start(){
						force.stop();
						window.clearTimeout(timeout);
					}

					//force.start();

					node.transition()
					    .duration(5)
					    .delay(function(d, i) { return i * 2; })
					    .attrTween("r", function(d) {
					         var i = d3.interpolate(0, d.radius);
					         return function(t) { return d.radius = i(t); };
					    });

					function tick(e) {
					  node.each(cluster(10 * e.alpha * e.alpha))
					      .each(collide(.5))
					      .attr("cx", function(d) { return d.x; })
					      .attr("cy", function(d) { return d.y; });
					}

					// Move d to be adjacent to the cluster node.
					function cluster(alpha) {
					  return function(d) {
					    var cluster = clusters[d.cluster];
					    if (cluster === d) return;
					    var x = d.x - cluster.x,
					        y = d.y - cluster.y,
					        l = Math.sqrt(x * x + y * y),
					        r = d.radius + cluster.radius;
					    if (l != r) {
					      l = (l - r) / l * alpha;
					      d.x -= x *= l;
					      d.y -= y *= l;
					      cluster.x += x;
					      cluster.y += y;
					    }
					  };
					}

					// Resolves collisions between d and all other circles.
					function collide(alpha) {
					  var quadtree = d3.geom.quadtree(nodes);
					  return function(d) {
					    var r = d.radius + maxRadius + Math.max(padding, clusterPadding),
					        nx1 = d.x - r,
					        nx2 = d.x + r,
					        ny1 = d.y - r,
					        ny2 = d.y + r;
					    quadtree.visit(function(quad, x1, y1, x2, y2) {
					      if (quad.point && (quad.point !== d)) {
					        var x = d.x - quad.point.x,
					            y = d.y - quad.point.y,
					            l = Math.sqrt(x * x + y * y),
					            r = d.radius + quad.point.radius + (d.cluster === quad.point.cluster ? padding : clusterPadding);
					        if (l < r) {
					          l = (l - r) / l * alpha;
					          d.x -= x *= l;
					          d.y -= y *= l;
					          quad.point.x += x;
					          quad.point.y += y;
					        }
					      }
					      return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
					    });
					  };
					}
			}

			function selectNodes(category){
				d3.selectAll(".node")
				 // .attr("r", 2);
				  .style("opacity", function(d){
					  var key = $(this).attr("data-key");
					  var row = $.grep(table, function(e){ return e.primaryKey == key; });
					  var categoryName = "lda020selected_topicWeights_" + category;
					  return row[0][categoryName];
				  });

				/*d3.selectAll("[data-category='"+category+"']")
				  .attr("r", function(d){
					  return 6;
				  })
				  .attr("stroke", "#FFFFFF")
				  .attr("stroke-width", "2")
				  .style("opacity", function(d){
					  var key = $(this).attr("data-key");
					  var row = $.grep(table, function(e){ return e.primaryKey == key; });
					  var categoryName = "lda020selected_topicWeights_ " + category;
					  console.log(row[0][categoryName]);
					  return row[0][categoryName];
				  });*/
			}

			function resetNodes(){
				d3.selectAll(".node")
				  .style("opacity", "1");
			}

			/*
			 * Select the specified category and "filter" the nodes related to that category
			 */
			function selectCategory(element, category){
				  //If this arc is already selected...
	        	  if(d3.select(element).classed("selected")){

	        		  //Change all the other arc colors back to normal
	        		  $("path.arc").css("fill", function(){
	        			  return colors[$(this).attr("data-category")][0];
	        		  });

	        		  //Change all the other arc labels back to normal
	        		  $(".arc-label").css("fill", function(){
	        			 return colors[$(this).attr("data-category")][1];
	        		  });

	        		  //Make the new list of classes and add them
	        		  var newClasses = $(element).attr("class").replace("selected", "");
	        		  $(element).attr("class", newClasses);

	        		  //Reset the nodes
	        		  resetNodes();
	        	  }
	        	  // If this is a new selection...
	        	  else{
	        		  //Select all the other arcs and color them as inactive
	        		  $("path.arc").css("fill", (configuration.inactiveArcColor || "#F0F0F0"));
	        		  $(".arc-label").css("fill", (configuration.inactiveLabelColor || "#999999"));

	        		  //Select any other arc that is marked as "selected" and remove that class
	        		  $("path.arc.selected").each(function(i, arc){
	        			  var newClasses = $(arc).attr("class").replace("selected", "");
		    	          $(arc).attr("class", newClasses);
	        		  });

	        		  //Then select the active arc and recolor it as its original color
	        		  var currentClasses = $(element).attr("class");
	        		  $(element)
	    	            .css("fill", colors[category][0])
	    	            .attr("class", currentClasses + " selected");

	        		  //Find the arc label that goes with this arc and recolor it
	        		  $("[data-category='" + category + "'].arc-label")
	        		       .css("fill", colors[category][1]);

	    	          //Call our function that will manipulate the nodes for this category
	        		  selectNodes(category);
	        	  }
			}

			});
		});
	});
});<|endoftext|>


<commit_before>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	//enable typewatch
	$('#street').typeWatch({
		captureLength: 2,
		wait: 1750,
    		highlight: true,
		callback: function(value) {
			//alert("typing finished");
			street_to_geo(value);
		}
	});
});

stop_loader(){
	$('#loader').fadeOut('slow');
	$('#overlay').fadeOut('slow');

}

function street_to_geo(street){
      //encodes the street string into url friendly format
      var street_encoded = encodeURIComponent(street);
      var uri = "https://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
      //alert(uri);
      //makes the the jquery call and gets json back
      $.getJSON(uri, function(data) {
        //make js obj containing lat and long
        var obj = {latitude: data[0].lat, longitude: data[0].lon};
        alert(obj.latitude + " " + obj.longitude);
        //return obj;
      });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long, category) {
	var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
	var method = "POST";
	var postData = "";	// TODO get key
	postData += "location=" + lat + "," + long;
	postData += "radius=5000";	// 5km, could be changed or added as a configurable later
	postData += "type=" + category;

	// if it is not true, it'll block ALL execution waiting for server response.
	var shouldBeAsync = true;

	var request = new XMLHttpRequest();

	// This function attached to the XMLHttpRequest "onload" property specifies how the HTTP response will be handled.
	// request.onreadystatechange can also be used if this doesn't work
	request.onload = function () {
		// You can get all kinds of information about the HTTP response.
		var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
		var data = request.responseText; // Returned data, e.g., an HTML document.

		var jsObj = null;

		if (status == 200) {
			jsObj = data.results;
			add_details(jsObj, lat, long);
			sort_json(jsObj, 'rating_over_distance', false);	// false because we want descending order
		}

		// TODO: call whatever needs to use the jsObj
	}

	request.open(method, url, shouldBeAsync);

	request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

	// Actually sends the request to the server.
	request.send(postData);
}

function add_details(json_object, lat, long) {
	for ( x in json_object) {
		json_object[x].distance = calc_distance(lat, lon, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng);
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }

    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	var options = {
	  enableHighAccuracy: true
	};
	if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

	      //return pos;
		var location = pos.lat + " " + pos.lng;
		alert(location);
      },
      function(err){},
      options);
    }

}

function get_weather(lat, lon){

	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php

    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });

}
<commit_msg>Update main.js<commit_after>
// Wait for user to finish typing
// callback: The callback function
// wait: The number of milliseconds to wait after the the last key press before firing the callback
// highlight: Highlights the element when it receives focus
// allowSubmit: Allows a non-multiline element to be submitted (enter key) regardless of captureLength
// captureLength: Minimum # of characters necessary to fire the callback

$(document).ready(function() {

	//stop loader.gif and overlay
	stop_loader();

	//enable typewatch
	$('#street').typeWatch({
		captureLength: 2,
		wait: 1750,
    		highlight: true,
		callback: function(value) {
			//alert("typing finished");
			street_to_geo(value);
		}
	});
});

function start_loader(){
	$('#loader').fadeIn('slow');
	$('#overlay').fadeIn('slow');
}

function stop_loader(){
	$('#loader').fadeOut('slow');
	$('#overlay').fadeOut('slow');

}

function street_to_geo(street){
      //encodes the street string into url friendly format
      var street_encoded = encodeURIComponent(street);
      var uri = "https://nominatim.openstreetmap.org/search/" + street_encoded + "?format=json";
      //alert(uri);
      //makes the the jquery call and gets json back
      $.getJSON(uri, function(data) {
        //make js obj containing lat and long
        var obj = {latitude: data[0].lat, longitude: data[0].lon};
        alert(obj.latitude + " " + obj.longitude);
        //return obj;
      });
}

function calc_distance(lat1, lon1, lat2, lon2) {
	var unit = "K";
	var radlat1 = Math.PI * lat1/180;
	var radlat2 = Math.PI * lat2/180;
	var theta = lon1-lon2;
	var radtheta = Math.PI * theta/180;
	var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
	dist = Math.acos(dist);
	dist = dist * 180/Math.PI;
	dist = dist * 60 * 1.1515;
	if (unit=="K") { dist = dist * 1.609344; }
	if (unit=="N") { dist = dist * 0.8684; }
	return dist;
}

function get_places(lat, long, category) {
	var url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json";
	var method = "POST";
	var postData = "";	// TODO get key
	postData += "location=" + lat + "," + long;
	postData += "radius=5000";	// 5km, could be changed or added as a configurable later
	postData += "type=" + category;

	// if it is not true, it'll block ALL execution waiting for server response.
	var shouldBeAsync = true;

	var request = new XMLHttpRequest();

	// This function attached to the XMLHttpRequest "onload" property specifies how the HTTP response will be handled.
	// request.onreadystatechange can also be used if this doesn't work
	request.onload = function () {
		// You can get all kinds of information about the HTTP response.
		var status = request.status; // HTTP response status, e.g., 200 for "200 OK"
		var data = request.responseText; // Returned data, e.g., an HTML document.

		var jsObj = null;

		if (status == 200) {
			jsObj = data.results;
			add_details(jsObj, lat, long);
			sort_json(jsObj, 'rating_over_distance', false);	// false because we want descending order
		}

		// TODO: call whatever needs to use the jsObj
	}

	request.open(method, url, shouldBeAsync);

	request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");

	// Actually sends the request to the server.
	request.send(postData);
}

function add_details(json_object, lat, long) {
	for ( x in json_object) {
		json_object[x].distance = calc_distance(lat, lon, json_object[x].geometry.location.lat, json_object[x].geometry.location.lng);
		json_object[x].rating_over_distance = json_object[x].rating/json_object[x].distance;
	}
}

function sort_json(json_object, key_to_sort_by, ascending) {
    function sortByKey(a, b) {
        var x = a[key_to_sort_by];
        var y = b[key_to_sort_by];
        if (ascending ==  true) {
        	return ((x < y) ? -1 : ((x > y) ? 1 : 0));
        } else {
        	return ((x > y) ? -1 : ((x < y) ? 1 : 0));
        }
    }

    json_object.sort(sortByKey);
}

//returns a Coordinate, could add some other functionality of what to do when geolocation is not supported
var pos;
function get_my_location(){
	var options = {
	  enableHighAccuracy: true
	};
	if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(function(position) {
        pos = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        };

	      //return pos;
		var location = pos.lat + " " + pos.lng;
		alert(location);
      },
      function(err){},
      options);
    }

}

function get_weather(lat, lon){

	//if the function does not work, maybe the get_json.php should be in root, or path should be js/get_json.php

    var api_url = "js/get_json.php?";
    var type = "type=weather"

	api_request = api_url;
    api_request += type;
    api_request += "&lat="
    api_request += lat;
    api_request += "&lon="
    api_request += lon;

    //document.write(api_request);

    $(function () {
        $.getJSON(
            api_request,
            function (data) {
                $("#reply").html(JSON.stringify(data));
                return(JSON.stringify(data.weather[0].main));
            });
    });

}
<|endoftext|>


<commit_before>$(document).ready(function() {

	var $bodytag = $('html, body');
	var $tags = $('#goto-who, #goto-what, #goto-committees, #goto-team');
	$tags.click(function(e) {
		var elementName = e.target.id.substr(5);
		console.log(e);
		$bodytag.animate({
			scrollTop: $('#'+elementName).offset().top
		}, 300);
	});

	$('#down').click(function() {
		$('html, body').animate({
			scrollTop: $('#who').offset().top
		}, 300);
	});

	$('.person').hover(function(){
		$(this).find('.overlay').fadeIn('fast');
	},
	function(){
		$(this).find('.overlay').fadeOut('fast');
	});

	var tStart = 0
		, tEnd = 4*$(window).height()+70
		, cStart = [29,29,29]
		, cEnd = [32,78,160]
		, cDiff = [cEnd[0] - cStart[0], cEnd[1] - cStart[1], cEnd[2] - cStart[2]];

	$(document).scroll(function() {
		var p = ($(this).scrollTop() - tStart) / (tEnd - tStart);
		p = Math.min(1, Math.max(0, p));
		var cBg = [Math.round(cStart[0] + cDiff[0] * p), Math.round(cStart[1] + cDiff[1] * p), Math.round(cStart[2] + cDiff[2] * p)];
		$('body').css('background-color', 'rgb(' + cBg.join(',') +')');
		$('nav.navbar.navbar-inverse').css('background-color', 'rgb(' + cBg.join(',') +')');
	});
});<commit_msg>variable names<commit_after>$(document).ready(function() {

	var $bodytag = $('html, body');
	var $tags = $('#goto-who, #goto-what, #goto-committees, #goto-team');
	$tags.click(function(e) {
		var elementName = e.target.id.substr(5);
		console.log(e);
		$bodytag.animate({
			scrollTop: $('#'+elementName).offset().top
		}, 300);
	});

	$('#down').click(function() {
		$('html, body').animate({
			scrollTop: $('#who').offset().top
		}, 300);
	});

	$('.person').hover(function(){
		$(this).find('.overlay').fadeIn('fast');
	},
	function(){
		$(this).find('.overlay').fadeOut('fast');
	});

	var startPos = 0
		, endPos = 4*$(window).height()+70
		, startColor = [29,29,29]
		, endColor = [32,78,160]
		, diffColor = [endColor[0] - startColor[0], endColor[1] - startColor[1], endColor[2] - startColor[2]];

	$(document).scroll(function() {
		var pos = ($(this).scrollTop() - startPos) / (endPos - startPos);
		pos = Math.min(1, Math.max(0, pos));
		var bgColor = [Math.round(startColor[0] + diffColor[0] * pos), Math.round(startColor[1] + diffColor[1] * pos), Math.round(startColor[2] + diffColor[2] * pos)];
		$('body').css('background-color', 'rgb(' + bgColor.join(',') +')');
		$('nav.navbar.navbar-inverse').css('background-color', 'rgb(' + bgColor.join(',') +')');
	});
});<|endoftext|>


<commit_before>    (function (angular) {
    'use strict';

    var xmas = angular.module('xmas', ['angularMoment', 'ticker', 'storage']);

    var SANTAS_MOODS = [
        {label: 'Picky (fewest children get presents)', factor: 0.5},
        {label: 'Meh!', factor: 0.6},
        {label: 'Easy-going (most children get presents)', factor: 0.7},
    ];

    xmas.controller('GameCtrl', function ($scope, Ticker) {
        $scope.ticks = [];
        $scope.is_running = false;
        $scope.date = new Date(2013, 11, 26);

        $scope.sleigh = {capacity: 0, power: 0, presents: 0};

        $scope.items = [
            {
                id: 'elf',
                base_cost: 10,
                label: 'Elf',
                effect: 'Makes 20 presents per day',
                quantity: 0,
                unit_presents: 10,
                on_tick: function () {
                    $scope.sleigh.presents += (this.quantity * this.unit_presents);
                }
            },
            {
                id: 'santa',
                base_cost: 1000,
                label: 'Santa upgrade',
                effect: 'Increase Santa\'s efficiency 2%',
                quantity: 0,
                unit_effect: 1.02,
                on_presents_making: function () {
                    $scope.sleigh.presents += pow(this.unit_effect, this.quantity);
                }
            },
            {
                id: 'reindeer',
                base_cost: 100,
                label: 'Reindeer',
                effect: 'Pull a sleigh containing 10,000 presents',
                quantity: 0,
                unit_effect: 10000,
                on_buy: function () {
                    $scope.sleigh.power += (this.unit_effect * this.quantity);
                }

            },
            {
                id: 'elf-trainer',
                base_cost: 100,
                label: 'Reindeer trainer',
                effect: 'Increases the ability of reindeer to pull the sleigh over time',
                quantity: 0,
                unit_effect: 1.02,
                on_tick: function () {
                    if (this.quantity) {
                        $scope.sleigh.power += pow(this.unit_effect, this.quantity);
                    }
                }
            },
            {
                id: 'sleigh',
                base_cost: 10000,
                label: 'Sleigh upgrade',
                effect: 'Store 100,000 presents for delivery',
                quantity: 0,
                unit_effect: 100000,
                on_buy: function () {
                    $scope.sleigh.capacity += (this.unit_effect * this.quantity);
                }
            },
            {
                id: 'elf-mechanic',
                base_cost: 100,
                label: 'Sleigh mechanic',
                effect: 'Increases the capacity of the sleigh over time',
                quantity: 0,
                unit_effect: 1.02,
                on_tick: function () {
                    if (this.quantity) {
                        $scope.sleigh.capacity += pow(this.unit_effect, this.quantity);
                    }
                }
            }
        ];

        Ticker.tick(function () {
            if ($scope.is_running) {
                $scope.date = moment($scope.date).add(12, 'hours');

                angular.forEach($scope.items, function (item) {
                    if (angular.isFunction(item.on_tick)) {
                        item.on_tick();
                    };
                });
            }
        });

        this.start = function () {
            $scope.is_running = true;
        };

        this.pause = function () {
            $scope.is_running = false;
        };

        this.make_presents = function () {
            angular.forEach($scope.items, function (item) {
                if (angular.isFunction(item.on_presents_making)) {
                    item.on_presents_making();
                }
            });
        };

        this.buy_item = function (item) {
            var item_cost = get_item_cost(item);
            if (item_cost <= $scope.sleigh.presents) {
                $scope.sleigh.presents -= item_cost;
                item.quantity += 1;
                if (angular.isFunction(item.on_buy)) {
                    item.on_buy();
                };
            }
        };
    });

    var get_item_cost = function (item) {
        var item_cost = item.base_cost * Math.pow(1.15, item.quantity);
        return parseInt(item_cost, 10);
    };

    xmas.controller('SetupCtrl', function ($scope) {
        $scope.santas_moods = SANTAS_MOODS;
        $scope.santas_mood = SANTAS_MOODS[0];
    });

    xmas.filter('cost', function () {
        return get_item_cost;
    });

    var pow = function (base, power) {
        return parseInt(Math.pow(base, power), 10);
    }

}(window.angular));
<commit_msg>Fixed time-based calculations of power and capacity<commit_after>    (function (angular) {
    'use strict';

    var xmas = angular.module('xmas', ['angularMoment', 'ticker', 'storage']);

    var SANTAS_MOODS = [
        {label: 'Picky (fewest children get presents)', factor: 0.5},
        {label: 'Meh!', factor: 0.6},
        {label: 'Easy-going (most children get presents)', factor: 0.7},
    ];

    xmas.controller('GameCtrl', function ($scope, Ticker) {
        $scope.ticks = [];
        $scope.is_running = false;
        $scope.date = new Date(2013, 11, 26);

        $scope.sleigh = {capacity: 0, power: 0, presents: 0};

        $scope.items = [
            {
                id: 'elf',
                base_cost: 10,
                label: 'Elf',
                effect: 'Makes 20 presents per day',
                quantity: 0,
                unit_presents: 10,
                on_tick: function () {
                    $scope.sleigh.presents += (this.quantity * this.unit_presents);
                }
            },
            {
                id: 'santa',
                base_cost: 500,
                label: 'Santa upgrade',
                effect: 'Increase Santa\'s efficiency 2%',
                quantity: 0,
                unit_effect: 1.02,
                on_presents_making: function () {
                    $scope.sleigh.presents += pow(this.unit_effect, this.quantity);
                }
            },
            {
                id: 'reindeer',
                base_cost: 100,
                label: 'Reindeer',
                effect: 'Pull a sleigh containing 10,000 presents',
                quantity: 0,
                unit_effect: 10000,
                on_buy: function () {
                    $scope.sleigh.power += (this.unit_effect * this.quantity);
                }

            },
            {
                id: 'elf-trainer',
                base_cost: 250,
                label: 'Reindeer trainer',
                effect: 'Increases the ability of reindeer to pull the sleigh over time',
                quantity: 0,
                unit_effect: 1.02,
                on_tick: function () {
                    if (this.quantity) {
                        $scope.sleigh.power = parseInt($scope.sleigh.power * Math.pow(this.unit_effect, this.quantity), 10);
                    }
                }
            },
            {
                id: 'sleigh',
                base_cost: 1000,
                label: 'Sleigh upgrade',
                effect: 'Store 100,000 presents for delivery',
                quantity: 0,
                unit_effect: 100000,
                on_buy: function () {
                    $scope.sleigh.capacity += (this.unit_effect * this.quantity);
                }
            },
            {
                id: 'elf-mechanic',
                base_cost: 2500,
                label: 'Sleigh mechanic',
                effect: 'Increases the capacity of the sleigh over time',
                quantity: 0,
                unit_effect: 1.02,
                on_tick: function () {
                    if (this.quantity) {
                        $scope.sleigh.capacity = parseInt($scope.sleigh.capacity * Math.pow(this.unit_effect, this.quantity), 10);
                    }
                }
            }
        ];

        Ticker.tick(function () {
            if ($scope.is_running) {
                $scope.date = moment($scope.date).add(12, 'hours');

                angular.forEach($scope.items, function (item) {
                    if (angular.isFunction(item.on_tick)) {
                        item.on_tick();
                    };
                });
            }
        });

        this.start = function () {
            $scope.is_running = true;
        };

        this.pause = function () {
            $scope.is_running = false;
        };

        this.make_presents = function () {
            angular.forEach($scope.items, function (item) {
                if (angular.isFunction(item.on_presents_making)) {
                    item.on_presents_making();
                }
            });
        };

        this.buy_item = function (item) {
            var item_cost = get_item_cost(item);
            if (item_cost <= $scope.sleigh.presents) {
                $scope.sleigh.presents -= item_cost;
                item.quantity += 1;
                if (angular.isFunction(item.on_buy)) {
                    item.on_buy();
                };
            }
        };
    });

    var get_item_cost = function (item) {
        var item_cost = item.base_cost * Math.pow(1.15, item.quantity);
        return parseInt(item_cost, 10);
    };

    xmas.controller('SetupCtrl', function ($scope) {
        $scope.santas_moods = SANTAS_MOODS;
        $scope.santas_mood = SANTAS_MOODS[0];
    });

    xmas.filter('cost', function () {
        return get_item_cost;
    });

    var pow = function (base, power) {
        return parseInt(Math.pow(base, power), 10);
    }

}(window.angular));
<|endoftext|>