<commit_before>var $quiz = $('#slickQuiz');
var timer;
var downtime = 30;
var device = false;

$(function () {
// Wrapper

// Init quiz
function startQuiz() {
  $quiz.slickQuiz({
    numberOfQuestions: 10,
    randomSortQuestions: true,
    preventUnanswered: true,
    perQuestionResponseMessaging: true,
    completionResponseMessaging: true,
    showScore: true
  });
}
startQuiz();
app.initialize();

// Handle restarts and saving data
function restartQuiz(action) {
  /*
  console.log($quiz.data('slickQuiz'));
  var quiz = $quiz.data('slickQuiz');
  $('.quizScore .score-value').text('');
  $quiz.find('.questions').remove();
  quiz.method.resetQuiz();
  quiz.method.setupQuiz();
  $('body').addClass('front');
  //startQuiz();
  */
  if (device) {
    writeFile(param);
  }

  if (!$('body').hasClass('front')) {
    location.reload();
  }
}
$('.restart').bind('click', function() {
  restartQuiz('click');
});

// Automatically restart after x seconds of downtime
function resetTimer() {
  window.clearTimeout(timer);
  timer = setTimeout(function() {
    restartQuiz('timeout');
  }, downtime*1000);
}
resetTimer();
$('a, label, input').bind('click', resetTimer);

// change away from front-page stlying

$('a.startQuiz').click(function() {
  $('body').removeClass('front');

  // Create a new record
  uuid = guid();
  var d = new Date();
  Lawnchair(function() {
    this.save({key: uuid, start: d.getTime(), totalQuestions: 10});
  });
});

// handle question actions

var $questLi = $('.questions ul.answers > li');

$questLi.append('');

$questLi.children().click(function () {
  $(this).parents('li.question').addClass('selected');
});

$('a.checkAnswer').click(function () {
  $(this).parent('.selected').addClass('revealing');
});

$('a.nextQuestion').click(function () {
  if($(this).parent().is(':last-child')) {
    $('body').addClass('complete');
  }
});

// Generate uuid, from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
             .toString(16)
             .substring(1);
};
function guid() {
  return s4() + s4();
  //return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  //       s4() + '-' + s4() + s4() + s4();
}

// Wrapper
});

//
// Phonegap integration
//

// See if we need to save data onload
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
  device = device.uuid;

  // Check network status
  if (navigator.connection.type != Connection.NONE) {
    firebaseSave();
  }
}
//firebaseSave();

function firebaseSave() {
  var fb = new Firebase('https://dazzling-fire-8476.firebaseio.com/');
  Lawnchair(function(){
    var that = this;
    this.batch({saved: 0}, function() {
      this.each(function(record, index) {
        if (record.end != undefined) {
          record.time = record.end - record.start;
        }
        record.device = device;
        fb.push(record);
        that.remove(record.key, function() {
          //console.log('removed');
        });
      })
    })
  })
}

// Save the record in local cache
// This is called from slickQuiz.js
function lawnchairSave(data) {
  Lawnchair(function() {
    var that = this;
    this.get(uuid, function(record) {
      for (var attrname in data) { record[attrname] = data[attrname]; }
      var d = new Date();
      record.end = d.getTime();
      that.save(record);
    })
  })
}

<commit_msg>Saving records via firebase<commit_after>var $quiz = $('#slickQuiz');
var timer;
var downtime = 30;
var device = false;

$(function () {
// Wrapper

// Init quiz
function startQuiz() {
  $quiz.slickQuiz({
    numberOfQuestions: 10,
    randomSortQuestions: true,
    preventUnanswered: true,
    perQuestionResponseMessaging: true,
    completionResponseMessaging: true,
    showScore: true
  });
}
startQuiz();
app.initialize();

// Handle restarts and saving data
function restartQuiz(action) {
  /*
  console.log($quiz.data('slickQuiz'));
  var quiz = $quiz.data('slickQuiz');
  $('.quizScore .score-value').text('');
  $quiz.find('.questions').remove();
  quiz.method.resetQuiz();
  quiz.method.setupQuiz();
  $('body').addClass('front');
  //startQuiz();
  */

  // Save how the quiz ended on the row
  lawnchairSave({'action': action});

  if (!$('body').hasClass('front')) {
    location.reload();
  }
}
$('.restart').bind('click', function() {
  restartQuiz('click');
});

// Automatically restart after x seconds of downtime
function resetTimer() {
  window.clearTimeout(timer);
  timer = setTimeout(function() {
    restartQuiz('timeout');
  }, downtime*1000);
}
resetTimer();
$('a, label, input').bind('click', resetTimer);

// change away from front-page stlying

$('a.startQuiz').click(function() {
  $('body').removeClass('front');

  // Create a new record
  uuid = guid();
  var d = new Date();
  Lawnchair(function() {
    this.save({key: uuid, start: d.getTime(), totalQuestions: 10});
  });
});

// handle question actions

var $questLi = $('.questions ul.answers > li');

$questLi.append('');

$questLi.children().click(function () {
  $(this).parents('li.question').addClass('selected');
});

$('a.checkAnswer').click(function () {
  $(this).parent('.selected').addClass('revealing');
});

$('a.nextQuestion').click(function () {
  if($(this).parent().is(':last-child')) {
    $('body').addClass('complete');
  }
});

// Generate uuid, from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript
function s4() {
  return Math.floor((1 + Math.random()) * 0x10000)
             .toString(16)
             .substring(1);
};
function guid() {
  return s4() + s4();
  //return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  //       s4() + '-' + s4() + s4() + s4();
}

// Wrapper
});

//
// Phonegap integration
//

// See if we need to save data onload
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
  device = device.uuid;

  // Check network status
  if (navigator.connection.type != Connection.NONE) {
    firebaseSave();
  }
}
//firebaseSave();

function firebaseSave() {
  var fb = new Firebase('https://dazzling-fire-8476.firebaseio.com/');
  Lawnchair(function(){
    var that = this;
    this.batch({saved: 0}, function() {
      this.each(function(record, index) {
        if (record.end != undefined) {
          record.time = record.end - record.start;
        }
        record.device = device;
        fb.push(record);
        that.remove(record.key, function() {
          //console.log('removed');
        });
      })
    })
  })
}

// Save the record in local cache
// This is called from slickQuiz.js
function lawnchairSave(data) {
  Lawnchair(function() {
    var that = this;
    this.get(uuid, function(record) {
      for (var attrname in data) { record[attrname] = data[attrname]; }
      var d = new Date();
      record.end = d.getTime();
      that.save(record);
    })
  })
}

<|endoftext|>


<commit_before>/*
Copyright (C) 2008-2009  Arne Goedeke

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.

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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
  throw new Error( "This browser does not support XMLHttpRequest." )
};
/**
 * @namespace Meteor js connection namespace.
 */
meteor = new Object();
/**
 * Limit for the incoming buffer. When the incoming XMLHttpRequest object buffer grows larger than this, the connection is reinitiated.
 */
meteor.BUFFER_MAX = 1 << 16; // limit for incoming buffer, exceeding this buffer triggers a reconnect
meteor.dismantle = function(xhr) {
	delete xhr.onreadystatechange;
	delete xhr.onerror;
	if (xhr.readyState < 4) {
	    try { xhr.abort(); } catch (e) {};
	}
};
meteor.debug = function() {
	if (window.console && window.console.log) {
		if (window.console.firebug) {
			window.console.log.apply(window, arguments);
		} else { //this is IE
			window.console.log(arguments[0]);
		}
	}
};
/**
 * Meteor connection class. This is usually used with Atom serialization on top. Use psyc.Client if unsure.
 * @param {String} url URL of the Meteor connection endpoint.
 * @param {Function} callback Function to be called when data has been received.
 * @param {Function} error Function to be called when a fatal error occures.
 * @constructor
 * @example
 * var connection;
 * var incoming = function(data) {
 * 	document.write("Received data: " + data);
 * 	connection.send("Hello World.\n");
 * }
 * connection = new meteor.Connection("http://example.org/meteor/", incoming, alert);
 * connection.init();
 */
meteor.Connection = function(url, vars, callback, error) {
    this.url = url;
    this.vars = vars;
    this.buffer = "";
    this.callback = callback;
    this.error = error;
    this.async = true;
    this.pos = 0;
    this.reconnect = 1; // do a reconnect on close
};
meteor.Connection.prototype = {
	reconnect_incoming : function() {
		meteor.debug("reconnecting due to timeout.\n");
		if (this.new_incoming) {
			meteor.dismantle(this.new_incoming);
			delete this.new_incoming;
		}
		if (this.incoming) {
			meteor.dismantle(this.incoming);
			delete this.incoming;
		}
		this.connect_new_incoming();
	},
	new_incoming_state_change : function(xhr) {
		meteor.debug("new_incoming state is " + xhr.readyState);
		// we should check here for buffer length. maybe set a max
		// amount to shut down the main one ungracefully
		if (xhr.readyState >= 3) {
			this.connect_incoming();
		}
	},
	connect_new_incoming : function() {
		if (this.new_incoming) {
			// we already have one new incoming and are waiting for the
			// main one to shut down

			if (this.new_incoming.readyState == 4) {
			// someone is too fast for us.
			// TODO: we have to check for data in new_incoming,
			// not sure what to do with it. we can probably savely
			// parse it in case of atoms.
				meteor.debug("New connection already finished.\n");
			} else return this.connect_incoming();
		}

		meteor.debug("Connecting new incoming.\n");

		var xhr = new XMLHttpRequest();
		this.new_incoming = xhr;

		xhr.open("POST", UTIL.make_url(this.url, this.vars), true);
		// both opera and IE dont handle binary data correctly.
		if (!window.opera && navigator.appName != 'Microsoft Internet Explorer') {
			xhr.setRequestHeader("Content-Type", "application/octet-stream");
		}
		//xhr.overrideMimeType("text/plain; charset=ISO-8859-1");
		if (xhr.overrideMimeType) xhr.overrideMimeType('text/plain; charset=x-user-defined');
		xhr.onreadystatechange = UTIL.make_callback(this, this.new_incoming_state_change);
		xhr.send("");
	},
	set_nonblocking : function() {
		this.async = true;
	},
	set_blocking : function() {
		this.async = false;
	},
	incoming_state_change : function(xhr) {
		var s;

		//meteor.debug("incoming state is "+xhr.readyState);

		if (xhr.readyState >= 3) {
			// workaround for IE
			try {
				s = xhr.status;
			} catch(e) {
				// this is ie country
				// this is ie
				meteor.debug("fucking ie");
			}

			if (s == 200) {
				var length = xhr.responseBody ? xhr.responseBody.length : xhr.responseText.length;

				if (length > this.pos) {
					meteor.debug((length-this.pos)+" bytes received in readyState "+xhr.readyState);
					var str;

					try {
						if (window.opera) {
							str = xhr.responseText.slice(this.pos);
						} else if (xhr.responseBody) {
							str = xhr.responseBody.join("");
						} else {
							str = xhr.responseText.slice(this.pos);
							var t = str.split("");
							for (var i = 0; i < str.length; i++) {
								t[i] = t[i].charCodeAt(0) & 0xff;
							}
							str = String.fromCharCode.apply(window, t);
						}

						meteor.debug("calling callback: %o with %db of data", this.callback, str.length);
						this.callback(str);
					} catch (error) {
						meteor.debug("ERROR: "+error);
					}

					this.pos = length;
				}

				//meteor.debug("position %d (max %d)", this.pos, meteor.BUFFER_MAX);

				if (xhr.readyState == 4 || this.pos >= meteor.BUFFER_MAX) {
					if (this.operatimer) {
						clearTimeout(this.operatimer);
						delete this.operatimer;
					}
					if (this.reconnect) this.connect_new_incoming();
				}
			} else {
			// this throws an exception in firefox. brain
			//	con.error(this.statusText);
			}
		}
	},
	incoming_on_error : function() {
		meteor.debug("INCOMING ERROR!");
		window.setTimeout(UTIL.make_callback(this, this.connect_new_incoming), 500);
	},
	connect_incoming : function(xhr) {
		if (!xhr) {
			if (this.new_incoming) {
				xhr = this.new_incoming;
			} else throw("you need to call new_incoming() first. no this.new_incoming.");
		}

		if (this.incoming) {
		    	if (this.incoming.readyState != 4) {
			    // we lost some data here. we will still connect the new one because we dont expect it
			    // to be closed properly. we need to implement _id in order to fix this properly.
			    meteor.debug("Lost data on incoming connection (probably).");
			}
			meteor.dismantle(this.incoming);
		}

		if (this.operatimer) {
			clearTimeout(this.operatimer);
			delete this.operatimer;
		}

		xhr.onreadystatechange = UTIL.make_callback(this, this.incoming_state_change);
		xhr.onerror = UTIL.make_callback(this, this.incoming_on_error);
		meteor.debug("moved new incoming to incoming.");
		this.new_incoming = 0;
		this.incoming = xhr;
		this.pos = 0;
		this.incoming_state_change(xhr);

		// This code polls the xhr for new data in case opera is used. its necessary
		// because opera does not trigger an event if new data is available in state 3.
		if (window.opera) {
			this.operatimer = setInterval(UTIL.make_callback(this, function() { this.incoming_state_change(xhr) }), 100);
			meteor.debug("timer: "+this.operatimer);
		}
	},
	init_state_change : function(xhr) { // fetch the client_id and go
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				this.vars["id"] = xhr.responseText;
				meteor.debug("got client ID " + this.vars["id"]);

				meteor.dismantle(xhr);

				this.connect_new_incoming();
			} else if (xhr.status == 404) {
				this.error(xhr.responseText);
			} else {
				this.error(xhr.statusText);
			}
		}
	},
	/**
	 * Initialize the connection. This needs to be called before any data can be sent or received.
	 */
	init : function() { // fetch the client_id and go
		var xhr = new XMLHttpRequest();
		this.reconnect = 1;

		xhr.onreadystatechange = UTIL.make_callback(this, this.init_state_change);
		xhr.open("GET", UTIL.make_url(this.url, this.vars), true);
		xhr.send("");
	},
	/**
	 * Close incoming connection and clean up cyclic references.
	 */
	close : function() {
		var list = [this.new_incoming, this.incoming, this.outgoing];
		for (var i = 0; i < list.length; i++) {
			var t = list[i];
			try {
				if (t) {
					meteor.dismantle(t);
				}
			} catch(e) { }
		}
		delete this.outgoing;
		delete this.incoming;
		delete this.new_incoming;
		delete this.callback;
		delete this.error;
	},
	/**
	 * Send some data.
	 * @param {String} data String to be sent.
	 */
	send : function(data) {
		meteor.debug("sending "+data.length+" bytes");
		// check for status
		this.buffer += data;

		if (this.vars["id"]) {
		    if (!this.async) {
			this.write();
		    } else if (!this.will_write) {
			this.will_write = true;
			// we give a small window for more data coming in in the same loop
			window.setTimeout(UTIL.make_method(this, this.write), 20);
		    }
		}
	},
	outgoing_onerror : function(xhr) {
		this.will_write = false;
		this.buffer = this.old_buffer + this.buffer;
		this.write();
	},
	outgoing_state_change : function(xhr) {
		meteor.debug("outgoing state is "+xhr.readyState);

		if (xhr.readyState == 4) {
		    	window.clearTimeout(this.outgoing_timeout);
			xhr.onreadystatechange = null;
			if (xhr.status == 200) {
			    	// we do this do avoid opening too many connections. this should be enough
				this.will_write = false;
				if (this.buffer.length) window.setTimeout(UTIL.make_method(this, this.write), 20);
			} else  { // this basically means, that the server does not know the id
			    	this.error("It seems like the id timed out or something went wrong: "+xhr.statusText);
			}
			delete this.outdoing;
			meteor.dismantle(xhr);
		}
	},
	write : function() {
		if (this.buffer.length == 0) return;

		var xhr = new XMLHttpRequest();
		this.outgoing = xhr; // we keep it to be able to clean up

		/*
		if (this.outgoing) {
			// we could reuse the xhr object, however this
			// is not completely safe on safari/chrome
			// TODO: do it for firefox, opera, ie
			meteor.dismantle(this.outgoing);
		}
		*/

		xhr.open("POST", UTIL.make_url(this.url, this.vars), this.async);
		// we do this charset hackery because we have internal utf8 and plain ascii
		// for the rest of atom. this is supposed to be a binary transport
		if (this.async) {
		    meteor.debug("doing async request. setting callbacks");
		    xhr.onreadystatechange = UTIL.make_callback(this, this.outgoing_state_change);
		    xhr.onerror = UTIL.make_callback(this, this.outgoing_onerror);
		    var cb = UTIL.make_method(this, function() {
			meteor.dismantle(xhr);
			delete this.outgoing;
			this.will_write = false;
			this.buffer = this.old_buffer + this.buffer;
			this.write();
		    });
		    this.outgoing_timeout = window.setTimeout(cb, 3000);
		} else meteor.debug("doing sync request.");

		//meteor.debug("outgoing state change is %o", xhr.onreadystatechange);
		if (xhr.sendAsBinary) {
			xhr.setRequestHeader("Content-Type", "application/octet-stream");
			xhr.setRequestHeader("Content-Length", this.buffer.length);
			xhr.sendAsBinary(this.buffer);
		} else {
			xhr.send(this.buffer);
		}
		meteor.debug("writing "+this.buffer.length+" bytes\n");
		this.old_buffer = this.buffer;
		this.buffer = "";
	}
};
// the params handed by the user could be prototyped with a
// msg and something more
meteor.CallbackWrapper = function(params, mapping) {
	this.mapping = mapping;
	this.params = params;
};
meteor.CallbackWrapper.prototype = {
	msg : function(p, message) {
		var ok = true;
		if ((this.params.source && this.params.source != p.source())
		||  (this.params.context && this.params.context != p.v("_context"))
		||  (this.params.target && this.params.target != p.target())
		) {
			ok = false;
			meteor.debug(p.toString()+" is not the one.\n");
		}

		if (ok) {
			if (this.params.object) {
				if (this.params.cb) {
					return this.params.cb.call(this.params.object, p, message, this);
				}

				return this.params.object.msg(p, message, this);
			} else {
				return this.params.cb(p, message, this);
			}
		}
	},
	active : function() {
		return this.mapping == 0 ? 0 : 1;
	},
	unregister : function() {
		if (this.mapping == 0) return;

		var list = this.mapping.get(this.params.method);

		for (var i = 0; i < list.length; i++) {
			if (list[i] == this) {
				list.splice(i, 1);
			}
		}

		this.mapping = 0;
	}
};
<commit_msg>fix for IE<commit_after>/*
Copyright (C) 2008-2009  Arne Goedeke

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation.

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 General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
  try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
  try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
  try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
  throw new Error( "This browser does not support XMLHttpRequest." )
};
/**
 * @namespace Meteor js connection namespace.
 */
meteor = new Object();
/**
 * Limit for the incoming buffer. When the incoming XMLHttpRequest object buffer grows larger than this, the connection is reinitiated.
 */
meteor.BUFFER_MAX = 1 << 16; // limit for incoming buffer, exceeding this buffer triggers a reconnect
meteor.dismantle = function(xhr) {
	if (xhr.hasOwnProperty("onerror")) delete xhr.onreadystatechange;
	if (xhr.hasOwnProperty("onerror")) delete xhr.onerror;
	if (xhr.readyState < 4) {
	    try { xhr.abort(); } catch (e) {};
	}
};
meteor.debug = function() {
	if (window.console && window.console.log) {
		if (window.console.firebug) {
			window.console.log.apply(window, arguments);
		} else { //this is IE
			window.console.log(arguments[0]);
		}
	}
};
/**
 * Meteor connection class. This is usually used with Atom serialization on top. Use psyc.Client if unsure.
 * @param {String} url URL of the Meteor connection endpoint.
 * @param {Function} callback Function to be called when data has been received.
 * @param {Function} error Function to be called when a fatal error occures.
 * @constructor
 * @example
 * var connection;
 * var incoming = function(data) {
 * 	document.write("Received data: " + data);
 * 	connection.send("Hello World.\n");
 * }
 * connection = new meteor.Connection("http://example.org/meteor/", incoming, alert);
 * connection.init();
 */
meteor.Connection = function(url, vars, callback, error) {
    this.url = url;
    this.vars = vars;
    this.buffer = "";
    this.callback = callback;
    this.error = error;
    this.async = true;
    this.pos = 0;
    this.reconnect = 1; // do a reconnect on close
};
meteor.Connection.prototype = {
	reconnect_incoming : function() {
		meteor.debug("reconnecting due to timeout.\n");
		if (this.new_incoming) {
			meteor.dismantle(this.new_incoming);
			delete this.new_incoming;
		}
		if (this.incoming) {
			meteor.dismantle(this.incoming);
			delete this.incoming;
		}
		this.connect_new_incoming();
	},
	new_incoming_state_change : function(xhr) {
		meteor.debug("new_incoming state is " + xhr.readyState);
		// we should check here for buffer length. maybe set a max
		// amount to shut down the main one ungracefully
		if (xhr.readyState >= 3) {
			this.connect_incoming();
		}
	},
	connect_new_incoming : function() {
		if (this.new_incoming) {
			// we already have one new incoming and are waiting for the
			// main one to shut down

			if (this.new_incoming.readyState == 4) {
			// someone is too fast for us.
			// TODO: we have to check for data in new_incoming,
			// not sure what to do with it. we can probably savely
			// parse it in case of atoms.
				meteor.debug("New connection already finished.\n");
			} else return this.connect_incoming();
		}

		meteor.debug("Connecting new incoming.\n");

		var xhr = new XMLHttpRequest();
		this.new_incoming = xhr;

		xhr.open("POST", UTIL.make_url(this.url, this.vars), true);
		// both opera and IE dont handle binary data correctly.
		if (!window.opera && navigator.appName != 'Microsoft Internet Explorer') {
			xhr.setRequestHeader("Content-Type", "application/octet-stream");
		}
		//xhr.overrideMimeType("text/plain; charset=ISO-8859-1");
		if (xhr.overrideMimeType) xhr.overrideMimeType('text/plain; charset=x-user-defined');
		xhr.onreadystatechange = UTIL.make_callback(this, this.new_incoming_state_change);
		xhr.send("");
	},
	set_nonblocking : function() {
		this.async = true;
	},
	set_blocking : function() {
		this.async = false;
	},
	incoming_state_change : function(xhr) {
		var s;

		//meteor.debug("incoming state is "+xhr.readyState);

		if (xhr.readyState >= 3) {
			// workaround for IE
			try {
				s = xhr.status;
			} catch(e) {
				// this is ie country
				// this is ie
				meteor.debug("fucking ie");
			}

			if (s == 200) {
				var length = xhr.responseBody ? xhr.responseBody.length : xhr.responseText.length;

				if (length > this.pos) {
					meteor.debug((length-this.pos)+" bytes received in readyState "+xhr.readyState);
					var str;

					try {
						if (window.opera) {
							str = xhr.responseText.slice(this.pos);
						} else if (xhr.responseBody) {
							str = xhr.responseBody.join("");
						} else {
							str = xhr.responseText.slice(this.pos);
							var t = str.split("");
							for (var i = 0; i < str.length; i++) {
								t[i] = t[i].charCodeAt(0) & 0xff;
							}
							str = String.fromCharCode.apply(window, t);
						}

						meteor.debug("calling callback: %o with %db of data", this.callback, str.length);
						this.callback(str);
					} catch (error) {
						meteor.debug("ERROR: "+error);
					}

					this.pos = length;
				}

				//meteor.debug("position %d (max %d)", this.pos, meteor.BUFFER_MAX);

				if (xhr.readyState == 4 || this.pos >= meteor.BUFFER_MAX) {
					if (this.operatimer) {
						clearTimeout(this.operatimer);
						delete this.operatimer;
					}
					if (this.reconnect) this.connect_new_incoming();
				}
			} else {
			// this throws an exception in firefox. brain
			//	con.error(this.statusText);
			}
		}
	},
	incoming_on_error : function() {
		meteor.debug("INCOMING ERROR!");
		window.setTimeout(UTIL.make_callback(this, this.connect_new_incoming), 500);
	},
	connect_incoming : function(xhr) {
		if (!xhr) {
			if (this.new_incoming) {
				xhr = this.new_incoming;
			} else throw("you need to call new_incoming() first. no this.new_incoming.");
		}

		if (this.incoming) {
		    	if (this.incoming.readyState != 4) {
			    // we lost some data here. we will still connect the new one because we dont expect it
			    // to be closed properly. we need to implement _id in order to fix this properly.
			    meteor.debug("Lost data on incoming connection (probably).");
			}
			meteor.dismantle(this.incoming);
		}

		if (this.operatimer) {
			clearTimeout(this.operatimer);
			delete this.operatimer;
		}

		xhr.onreadystatechange = UTIL.make_callback(this, this.incoming_state_change);
		xhr.onerror = UTIL.make_callback(this, this.incoming_on_error);
		meteor.debug("moved new incoming to incoming.");
		this.new_incoming = 0;
		this.incoming = xhr;
		this.pos = 0;
		this.incoming_state_change(xhr);

		// This code polls the xhr for new data in case opera is used. its necessary
		// because opera does not trigger an event if new data is available in state 3.
		if (window.opera) {
			this.operatimer = setInterval(UTIL.make_callback(this, function() { this.incoming_state_change(xhr) }), 100);
			meteor.debug("timer: "+this.operatimer);
		}
	},
	init_state_change : function(xhr) { // fetch the client_id and go
		if (xhr.readyState == 4) {
			if (xhr.status == 200) {
				this.vars["id"] = xhr.responseText;
				meteor.debug("got client ID " + this.vars["id"]);

				meteor.dismantle(xhr);

				this.connect_new_incoming();
			} else if (xhr.status == 404) {
				this.error(xhr.responseText);
			} else {
				this.error(xhr.statusText);
			}
		}
	},
	/**
	 * Initialize the connection. This needs to be called before any data can be sent or received.
	 */
	init : function() { // fetch the client_id and go
		var xhr = new XMLHttpRequest();
		this.reconnect = 1;

		xhr.onreadystatechange = UTIL.make_callback(this, this.init_state_change);
		xhr.open("GET", UTIL.make_url(this.url, this.vars), true);
		xhr.send("");
	},
	/**
	 * Close incoming connection and clean up cyclic references.
	 */
	close : function() {
		var list = [this.new_incoming, this.incoming, this.outgoing];
		for (var i = 0; i < list.length; i++) {
			var t = list[i];
			try {
				if (t) {
					meteor.dismantle(t);
				}
			} catch(e) { }
		}
		delete this.outgoing;
		delete this.incoming;
		delete this.new_incoming;
		delete this.callback;
		delete this.error;
	},
	/**
	 * Send some data.
	 * @param {String} data String to be sent.
	 */
	send : function(data) {
		meteor.debug("sending "+data.length+" bytes");
		// check for status
		this.buffer += data;

		if (this.vars["id"]) {
		    if (!this.async) {
			this.write();
		    } else if (!this.will_write) {
			this.will_write = true;
			// we give a small window for more data coming in in the same loop
			window.setTimeout(UTIL.make_method(this, this.write), 20);
		    }
		}
	},
	outgoing_onerror : function(xhr) {
		this.will_write = false;
		this.buffer = this.old_buffer + this.buffer;
		this.write();
	},
	outgoing_state_change : function(xhr) {
		meteor.debug("outgoing state is "+xhr.readyState);

		if (xhr.readyState == 4) {
		    	window.clearTimeout(this.outgoing_timeout);
			xhr.onreadystatechange = null;
			if (xhr.status == 200) {
			    	// we do this do avoid opening too many connections. this should be enough
				this.will_write = false;
				if (this.buffer.length) window.setTimeout(UTIL.make_method(this, this.write), 20);
			} else  { // this basically means, that the server does not know the id
			    	this.error("It seems like the id timed out or something went wrong: "+xhr.statusText);
			}
			delete this.outdoing;
			meteor.dismantle(xhr);
		}
	},
	write : function() {
		if (this.buffer.length == 0) return;

		var xhr = new XMLHttpRequest();
		this.outgoing = xhr; // we keep it to be able to clean up

		/*
		if (this.outgoing) {
			// we could reuse the xhr object, however this
			// is not completely safe on safari/chrome
			// TODO: do it for firefox, opera, ie
			meteor.dismantle(this.outgoing);
		}
		*/

		xhr.open("POST", UTIL.make_url(this.url, this.vars), this.async);
		// we do this charset hackery because we have internal utf8 and plain ascii
		// for the rest of atom. this is supposed to be a binary transport
		if (this.async) {
		    meteor.debug("doing async request. setting callbacks");
		    xhr.onreadystatechange = UTIL.make_callback(this, this.outgoing_state_change);
		    xhr.onerror = UTIL.make_callback(this, this.outgoing_onerror);
		    var cb = UTIL.make_method(this, function() {
			meteor.dismantle(xhr);
			delete this.outgoing;
			this.will_write = false;
			this.buffer = this.old_buffer + this.buffer;
			this.write();
		    });
		    this.outgoing_timeout = window.setTimeout(cb, 3000);
		} else meteor.debug("doing sync request.");

		//meteor.debug("outgoing state change is %o", xhr.onreadystatechange);
		if (xhr.sendAsBinary) {
			xhr.setRequestHeader("Content-Type", "application/octet-stream");
			xhr.setRequestHeader("Content-Length", this.buffer.length);
			xhr.sendAsBinary(this.buffer);
		} else {
			xhr.send(this.buffer);
		}
		meteor.debug("writing "+this.buffer.length+" bytes\n");
		this.old_buffer = this.buffer;
		this.buffer = "";
	}
};
// the params handed by the user could be prototyped with a
// msg and something more
meteor.CallbackWrapper = function(params, mapping) {
	this.mapping = mapping;
	this.params = params;
};
meteor.CallbackWrapper.prototype = {
	msg : function(p, message) {
		var ok = true;
		if ((this.params.source && this.params.source != p.source())
		||  (this.params.context && this.params.context != p.v("_context"))
		||  (this.params.target && this.params.target != p.target())
		) {
			ok = false;
			meteor.debug(p.toString()+" is not the one.\n");
		}

		if (ok) {
			if (this.params.object) {
				if (this.params.cb) {
					return this.params.cb.call(this.params.object, p, message, this);
				}

				return this.params.object.msg(p, message, this);
			} else {
				return this.params.cb(p, message, this);
			}
		}
	},
	active : function() {
		return this.mapping == 0 ? 0 : 1;
	},
	unregister : function() {
		if (this.mapping == 0) return;

		var list = this.mapping.get(this.params.method);

		for (var i = 0; i < list.length; i++) {
			if (list[i] == this) {
				list.splice(i, 1);
			}
		}

		this.mapping = 0;
	}
};
<|endoftext|>


<commit_before>/*
 * Init login overlay
 */
$('document').ready(function(){
    $('#modaloverlay').click(function(){
        hideModal();
    });

    $('.modal_box').click(function(e){
        e.stopPropagation();
    });

    $('#usermanagement').click(function(){
        showLogin();
    });

    $('#loginform').submit(function(e){
        // Hide the error message
        $('#login_error').hide();

        // Post the form
        $.ajax({
            type: "POST",
            url: "/login/" + encodeURIComponent($('#loginform').find('input[name="email"]').val()),
            data: $('#loginform').serialize(),
            success: function() {
                // Reload page when logged in
                location.reload();
            },
            error: function() {
                // Display error message
                $('#login_error').html(i18n.__("ServiceNotReachableError"));
                $('#login_error').show();
            }
        });

        // Stop form submit via normal post
        e.preventDefault();
    });
});

/*
 * Log out a user from the system
 */
function logoutUser() {
    $.ajax({
        url: 'logout',
        success: function() {
            location.reload();
        }
    });
}

/*
 * Show the login modal
 */
function showLogin() {
    // Clear the form
    $('#login_error').hide();
    $('#loginform')[0].reset();

    // Show the login window
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#login_modal').show();
    $('#modaloverlay').show();
}

/*
 * Show the Yes and No modal with callback
 */
function showYesNoModal(body, callback) {
    // Hide the login window
    $('#login_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#yes_no_modal').show();

    // Fill up the body
    $('#modal_title_body').html = body;

    // Show the modal
    $('#modaloverlay').show();

    $('#ynmodel-y-btn').click(function(){
        callback(true);
        hideModal();
    });

    $('#ynmodal-n-btn').click(function(){
        callback(false);
        hideModal();
    });
}

function showUploadModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').show();

    $('#modaloverlay').show();
}

function showGeneralModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#upload_modal').hide();
    $('#general_modal').show();

    // Show the modal
    $('#modaloverlay').show();
}

function setGeneralModalTitle(title)
{
    $('#general_modal_title').html(title);
}

function setGeneralModalBody(body)
{
    $('#general_modal_body').html(body);
}

function addGeneralModalButton(text, action)
{
    var button = document.createElement('button');
    $(button).addClass('btn btn-primary inline btn-extra-margin');
    $(button).click(function(){action();});
    $(button).html(text);
    $('#general_modal_buttons').append(button);
}

function resetGeneralModal()
{
    $('#general_modal_title').empty();
    $('#general_modal_body').empty();
    $('#general_modal_buttons').empty();
}

function hideModal() {
    $('#modaloverlay').hide();
}

$(document).ready(function () {
        $('#uploadformbtn').click(function(){
            // Get the form data. This serializes the entire form. pritty easy huh!
            var form = new FormData($('#uploadform')[0]);

            // Make the ajax call
            $.ajax({
                url: '/api/upload',
                type: 'POST',
                xhr: function() {
                    var myXhr = $.ajaxSettings.xhr();
                    if(myXhr.upload){
                        myXhr.upload.addEventListener('progress',progress, false);
                    }
                    return myXhr;
                },
                //add beforesend handler to validate or something
                beforeSend: function(){
					$('progress').attr({value:0,max:100});
                                        setGeneralModalTitle('Uploading images...');
                                        setGeneralModalBody('<progress value="0" max="100" id="progressbar"></progress>');
                                        showGeneralModal();

					var imgdiv = document.getElementById('uploadedimages');
					imgdiv.innerHTML = "";
					document.getElementById('upimagestext').style.display = 'none';
				},
                success: function(res){
                                    setGeneralModalTitle('Upload succes');
                                        setGeneralModalBody('All images are succesfully uploaded');
                                        showGeneralModal();

					var imgdiv = document.getElementById('uploadedimages');
					document.getElementById('upimagestext').style.display = 'block';

					$.each(res, function(index, elem){
						var div = document.createElement('div');
						div.className += 'upimage';
						imgdiv.appendChild(div);

						div.innerHTML += '
';
        				div.innerHTML += 'id: '+elem['id']+'
';
       					div.innerHTML += 'type: '+elem['type']+'
';
        				div.innerHTML += 'name: '+elem['name']+'
';
        				div.innerHTML += 'size: '+elem['size']+'';
					});
				},
                //add error handler for when a error occurs if you want!
                error: function(xhr, status, error){
                                        setGeneralModalTitle('Upload error');
                                        setGeneralModalBody(xhr.responseText);
                                        showGeneralModal();

				},
                data: form,
                // this is the important stuf you need to overide the usual post behavior
                cache: false,
                contentType: false,
                processData: false
            });
        });
    });

    // Yes outside of the .ready space becouse this is a function not an event listner!
    function progress(e){
        if(e.lengthComputable){
            //this makes a nice fancy progress bar
            $('progress').attr({value:e.loaded,max:e.total});
        }
    }<commit_msg>updated upload to fit in dptcms<commit_after>/*
 * Init login overlay
 */
$('document').ready(function () {
    $('#modaloverlay').click(function () {
        hideModal();
    });

    $('.modal_box').click(function (e) {
        e.stopPropagation();
    });

    $('#usermanagement').click(function () {
        showLogin();
    });

    $('#loginform').submit(function (e) {
        // Hide the error message
        $('#login_error').hide();

        // Post the form
        $.ajax({
            type: "POST",
            url: "/login/" + encodeURIComponent($('#loginform').find('input[name="email"]').val()),
            data: $('#loginform').serialize(),
            success: function () {
                // Reload page when logged in
                location.reload();
            },
            error: function () {
                // Display error message
                $('#login_error').html(i18n.__("ServiceNotReachableError"));
                $('#login_error').show();
            }
        });

        // Stop form submit via normal post
        e.preventDefault();
    });
});

/*
 * Log out a user from the system
 */
function logoutUser() {
    $.ajax({
        url: 'logout',
        success: function () {
            location.reload();
        }
    });
}

/*
 * Show the login modal
 */
function showLogin() {
    // Clear the form
    $('#login_error').hide();
    $('#loginform')[0].reset();

    // Show the login window
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#login_modal').show();
    $('#modaloverlay').show();
}

/*
 * Show the Yes and No modal with callback
 */
function showYesNoModal(body, callback) {
    // Hide the login window
    $('#login_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').hide();
    $('#yes_no_modal').show();

    // Fill up the body
    $('#modal_title_body').html = body;

    // Show the modal
    $('#modaloverlay').show();

    $('#ynmodel-y-btn').click(function () {
        callback(true);
        hideModal();
    });

    $('#ynmodal-n-btn').click(function () {
        callback(false);
        hideModal();
    });
}

function showUploadModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#general_modal').hide();
    $('#upload_modal').show();

    $('#modaloverlay').show();
}

function showGeneralModal()
{
    $('#login_modal').hide();
    $('#yes_no_modal').hide();
    $('#upload_modal').hide();
    $('#general_modal').show();

    // Show the modal
    $('#modaloverlay').show();
}

function setGeneralModalTitle(title)
{
    $('#general_modal_title').html(title);
}

function setGeneralModalBody(body)
{
    $('#general_modal_body').html(body);
}

function getGeneralModalBody()
{
    return $('#general_modal_body').html();
}

function addGeneralModalButton(text, action)
{
    var button = document.createElement('button');
    $(button).addClass('btn btn-primary inline btn-extra-margin');
    $(button).click(function () {
        action();
    });
    $(button).html(text);
    $('#general_modal_buttons').append(button);
}

function resetGeneralModal()
{
    $('#general_modal_title').empty();
    $('#general_modal_body').empty();
    $('#general_modal_buttons').empty();
}

function hideModal() {
    $('#modaloverlay').hide();
}

$(document).ready(function () {
    $('#uploadformbtn').click(function () {
        // Get the form data. This serializes the entire form. pritty easy huh!
        var form = new FormData($('#uploadform')[0]);

        var body;

        // Make the ajax call
        $.ajax({
            url: '/api/upload',
            type: 'POST',
            xhr: function () {
                var myXhr = $.ajaxSettings.xhr();
                if (myXhr.upload) {
                    myXhr.upload.addEventListener('progress', progress, false);
                }
                return myXhr;
            },
            //add beforesend handler to validate or something
            beforeSend: function () {
                body = getGeneralModalBody();
                $('progress').attr({value: 0, max: 100});
                setGeneralModalTitle('Uploading images...');
                setGeneralModalBody('<progress value="0" max="100" id="progressbar"></progress>');
                showGeneralModal();

                var imgdiv = document.getElementById('uploadedimages');
                imgdiv.innerHTML = "";
                document.getElementById('upimagestext').style.display = 'none';
            },
            success: function (res) {
                setGeneralModalTitle('Upload succes');
                setGeneralModalBody(body);
                showGeneralModal();

                var imgdiv = document.getElementById('uploadedimages');
                document.getElementById('upimagestext').style.display = 'block';

                $.each(res, function (index, elem) {
                    var div = document.createElement('div');
                    div.className += 'upimage';
                    imgdiv.appendChild(div);

                    div.innerHTML += '
';
                    div.innerHTML += 'id: ' + elem['id'] + '
';
                    div.innerHTML += 'type: ' + elem['type'] + '
';
                    div.innerHTML += 'name: ' + elem['name'] + '
';
                    div.innerHTML += 'size: ' + elem['size'] + '';
                });
            },
            //add error handler for when a error occurs if you want!
            error: function (xhr, status, error) {
                setGeneralModalTitle('Upload error');
                setGeneralModalBody(xhr.responseText);
                showGeneralModal();

            },
            data: form,
            // this is the important stuf you need to overide the usual post behavior
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

// Yes outside of the .ready space becouse this is a function not an event listner!
function progress(e) {
    if (e.lengthComputable) {
        //this makes a nice fancy progress bar
        $('progress').attr({value: e.loaded, max: e.total});
    }
}<|endoftext|>


<commit_before>var Models = {};
Models.ItemListing = Backbone.Model.extend({
	defaults: {
		id: '',
		name: '',
		price: '',
		location: '',
		buyers: [],
		owner: ''
	}
	initialize: function() {

	}
});<commit_msg>Add imageUrl to ItemListing model.<commit_after>var Models = {};
Models.ItemListing = Backbone.Model.extend({
	defaults: {
		id: '',
		name: '',
		price: '',
		location: '',
		buyers: [],
		owner: '',
		imageUrl: ''
	}
	initialize: function() {

	}
});<|endoftext|>


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

    var pageList = ["http://sureshnswamy.github.io/index.html",
                "http://sureshnswamy.github.io/blog/c1-reflection-blog.html",
                'http://sureshnswamy.github.io/blog/c1-time-and-habits-blog.html',
                'http://sureshnswamy.github.io/blog/c2-emotional-intelligence.html',
                "http://sureshnswamy.github.io/blog/t2-html-css-dom-p1-blog",
                "http://sureshnswamy.github.io/blog/t2-html-css-dom-p2-blog.html",
                "http://sureshnswamy.github.io/blog/t3-design-to-web-blog.html",
                "http://sureshnswamy.github.io/blog/c3-meditation-process.html",
                "http://sureshnswamy.github.io/blog/c4-daily-mindfulness.html",
                "http://sureshnswamy.github.io/blog/t4-javascript-basics.html",
                'http://sureshnswamy.github.io/blog/c5-self-confidence.html'
                ];
// page file name stripper from url    ///

    function getFileName(url) {
    //this gets the full url
    document.location=url;

    //this removes the anchor at the end, if there is one
    url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));

    //this removes the query after the file name, if there is one
    url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));

    //this removes everything before the last slash in the path
    url = url.substring(url.lastIndexOf("/") + 1, url.length);

    return url;
};

document.getElementById('next-btn').onclick = function next(){

    var hr = window.location.href;
    //var page = getFileName(hr);
    var nxtIndex =  pageList.indexOf(hr) + 1 ;

      if(nxtIndex >pageList.length-1) nxtIndex = 0;
        var redirect = pageList[nxtIndex];
        window.location.href=redirect;

    };

document.getElementById('prv-btn').onclick = function prev(){
    var hr = window.location.href;
    var nxtIndex =  pageList.indexOf(hr) - 1 ;
    console.log(hr,nxtIndex);
    if(nxtIndex < 0) nxtIndex = pageList.length-1;
    var redirect = pageList[nxtIndex];
    window.location.href=redirect;
}

});<commit_msg>sprint-5 tech blog added<commit_after>
$(document).ready (function () {

    var pageList = ["http://sureshnswamy.github.io/index.html",
                "http://sureshnswamy.github.io/blog/c1-reflection-blog.html",
                'http://sureshnswamy.github.io/blog/c1-time-and-habits-blog.html',
                'http://sureshnswamy.github.io/blog/c2-emotional-intelligence.html',
                "http://sureshnswamy.github.io/blog/t2-html-css-dom-p1-blog",
                "http://sureshnswamy.github.io/blog/t2-html-css-dom-p2-blog.html",
                "http://sureshnswamy.github.io/blog/t3-design-to-web-blog.html",
                "http://sureshnswamy.github.io/blog/c3-meditation-process.html",
                "http://sureshnswamy.github.io/blog/c4-daily-mindfulness.html",
                "http://sureshnswamy.github.io/blog/t4-javascript-basics.html",
                'http://sureshnswamy.github.io/blog/c5-self-confidence.html',
                'http://sureshnswamy.github.io/blog/t5-problem-solving.html'
                ];
// page file name stripper from url    ///

    function getFileName(url) {
    //this gets the full url
    document.location=url;

    //this removes the anchor at the end, if there is one
    url = url.substring(0, (url.indexOf("#") == -1) ? url.length : url.indexOf("#"));

    //this removes the query after the file name, if there is one
    url = url.substring(0, (url.indexOf("?") == -1) ? url.length : url.indexOf("?"));

    //this removes everything before the last slash in the path
    url = url.substring(url.lastIndexOf("/") + 1, url.length);

    return url;
};

document.getElementById('next-btn').onclick = function next(){

    var hr = window.location.href;
    //var page = getFileName(hr);
    var nxtIndex =  pageList.indexOf(hr) + 1 ;

      if(nxtIndex >pageList.length-1) nxtIndex = 0;
        var redirect = pageList[nxtIndex];
        window.location.href=redirect;

    };

document.getElementById('prv-btn').onclick = function prev(){
    var hr = window.location.href;
    var nxtIndex =  pageList.indexOf(hr) - 1 ;
    console.log(hr,nxtIndex);
    if(nxtIndex < 0) nxtIndex = pageList.length-1;
    var redirect = pageList[nxtIndex];
    window.location.href=redirect;
}

});<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
/*globals gGrid, gPage, gCustomize, gStrings, gUpdater, gUserDatabase, gPinnedLinks, async*/

"use strict";

(function(exports) {
  const gNewTab = {
    _prefsObjectStoreKeys: ["pinnedLinks"],

    listeners: {},

    init() {
      // Add a listener for messages sent from the browser.
      // The listener calls our associated callback functions.
      window.addEventListener("message", message => {
        for (let callback of this.listeners[message.data.name]) {
          callback(message.data.data);
        }
      });
    },

    observe(topic, data) {
      switch (topic) {
      case "page-thumbnail:create":
        if (!gGrid.ready) {
          return;
        }
        for (let site of gGrid.sites) {
          if (site && site.url === data) {
            site.refreshThumbnail();
          }
        }
        break;
      case "browser.newtabpage.enabled":
        this.enabled = data;
        gPage.handleEnabled(data);
        break;
      case "browser.newtabpage.enhanced":
        this.enhanced = data;
        break;
      case "browser.newtabpage.rows":
        this.rows = data;
        break;
      case "browser.newtabpage.columns":
        this.columns = data;
        break;
      }
      let isEnhanced =  "browser.newtabpage.enhanced" === topic;
      let isEnabled = "browser.newtabpage.enabled" === topic;
      if (isEnabled || isEnhanced) {
        gCustomize.updateSelected();
      }
    },

    setInitialState(message) {
      this.privateBrowsingMode = message.privateBrowsingMode;
      this.rows = message.rows;
      this.columns = message.columns;
      this.introShown = message.introShown;
      this.windowID = message.windowID;
      this.observe("browser.newtabpage.enabled", message.enabled);
      this.observe("browser.newtabpage.enhanced", message.enhanced);
      gUpdater.init();
      gPage.init();
    },

    newTabString(name, args) {
      let stringName = "newtab." + name;
      if (!args) {
        return gStrings[stringName];
      }
      let len = args.length;
      return this._formatStringFromName(gStrings[stringName], args, len);
    },

    _formatStringFromName(str, substrArr) {
      // Match regex that looks like "%<int>$S" representing variables in our strings
      let regExp = /%[0-9]\$S/g;
      let matches;
      while (matches = regExp.exec(str)) { // jshint ignore:line
        let match = matches[0];
        let index = match.charAt(1); // Get the digit in the regExp.
        str = str.replace(match, substrArr[index - 1]);
      }
      return str;
    },

    stringifySites() {
      let stringifiedSites = [];
      for (let site of gGrid.sites) {
        stringifiedSites.push(site ? JSON.stringify(site.link) : site);
      }
      return stringifiedSites;
    },

    sendToBrowser(type, data) {
      let event = new CustomEvent("NewTabCommand", {
        detail: {
          command: type,
          data: data
        }
      });
      document.dispatchEvent(event);
    },

    registerListener(type, callback) {
      if (!this.listeners[type]) {
        this.listeners[type] = [];
      }
      this.listeners[type].push(callback);
      this.sendToBrowser("NewTab:Register", {
        type
      });
    }
  };

  // Document is loaded. Initialize the New Tab Page.
  gNewTab.init();
  document.addEventListener("NewTabCommandReady", async(function* () {
    yield gUserDatabase.init(this._prefsObjectStoreKeys);
    yield gPinnedLinks.initPinnedLinks();
    gNewTab.registerListener("NewTab:Observe", message => {
      gNewTab.observe(message.topic, message.data);
    });
    gNewTab.registerListener("NewTab:State", gNewTab.setInitialState.bind(gNewTab));
    gNewTab.sendToBrowser("NewTab:GetInitialState");
  }, gNewTab));
  exports.gNewTab = gNewTab;
}(window));
<commit_msg>Ensure sendToBrowser() only send strings. (closes #79)<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */
/*globals gGrid, gPage, gCustomize, gStrings, gUpdater, gUserDatabase, gPinnedLinks, async*/

"use strict";

(function(exports) {
  const gNewTab = {
    _prefsObjectStoreKeys: ["pinnedLinks"],

    listeners: {},

    init() {
      // Add a listener for messages sent from the browser.
      // The listener calls our associated callback functions.
      window.addEventListener("message", message => {
        for (let callback of this.listeners[message.data.name]) {
          callback(message.data.data);
        }
      });
    },

    observe(topic, data) {
      switch (topic) {
      case "page-thumbnail:create":
        if (!gGrid.ready) {
          return;
        }
        for (let site of gGrid.sites) {
          if (site && site.url === data) {
            site.refreshThumbnail();
          }
        }
        break;
      case "browser.newtabpage.enabled":
        this.enabled = data;
        gPage.handleEnabled(data);
        break;
      case "browser.newtabpage.enhanced":
        this.enhanced = data;
        break;
      case "browser.newtabpage.rows":
        this.rows = data;
        break;
      case "browser.newtabpage.columns":
        this.columns = data;
        break;
      }
      let isEnhanced =  "browser.newtabpage.enhanced" === topic;
      let isEnabled = "browser.newtabpage.enabled" === topic;
      if (isEnabled || isEnhanced) {
        gCustomize.updateSelected();
      }
    },

    setInitialState(message) {
      this.privateBrowsingMode = message.privateBrowsingMode;
      this.rows = message.rows;
      this.columns = message.columns;
      this.introShown = message.introShown;
      this.windowID = message.windowID;
      this.observe("browser.newtabpage.enabled", message.enabled);
      this.observe("browser.newtabpage.enhanced", message.enhanced);
      gUpdater.init();
      gPage.init();
    },

    newTabString(name, args) {
      let stringName = "newtab." + name;
      if (!args) {
        return gStrings[stringName];
      }
      let len = args.length;
      return this._formatStringFromName(gStrings[stringName], args, len);
    },

    _formatStringFromName(str, substrArr) {
      // Match regex that looks like "%<int>$S" representing variables in our strings
      let regExp = /%[0-9]\$S/g;
      let matches;
      while (matches = regExp.exec(str)) { // jshint ignore:line
        let match = matches[0];
        let index = match.charAt(1); // Get the digit in the regExp.
        str = str.replace(match, substrArr[index - 1]);
      }
      return str;
    },

    stringifySites() {
      let stringifiedSites = [];
      for (let site of gGrid.sites) {
        stringifiedSites.push(site ? JSON.stringify(site.link) : site);
      }
      return stringifiedSites;
    },

    sendToBrowser(command, msgData = "") {
      var data = JSON.stringify(msgData);
      let event = new CustomEvent("NewTabCommand", {
        detail: {
          command,
          data,
        }
      });
      document.dispatchEvent(event);
    },

    registerListener(type, callback) {
      if (!this.listeners[type]) {
        this.listeners[type] = [];
      }
      this.listeners[type].push(callback);
      this.sendToBrowser("NewTab:Register", {
        type
      });
    }
  };

  // Document is loaded. Initialize the New Tab Page.
  gNewTab.init();
  document.addEventListener("NewTabCommandReady", async(function* () {
    yield gUserDatabase.init(this._prefsObjectStoreKeys);
    yield gPinnedLinks.initPinnedLinks();
    gNewTab.registerListener("NewTab:Observe", message => {
      gNewTab.observe(message.topic, message.data);
    });
    gNewTab.registerListener("NewTab:State", gNewTab.setInitialState.bind(gNewTab));
    gNewTab.sendToBrowser("NewTab:GetInitialState");
  }, gNewTab));
  exports.gNewTab = gNewTab;
}(window));
<|endoftext|>


<commit_before>class Player {
  constructor() {
    const player = DontPanic.game.add.sprite(DontPanic.game.world.width/2 - 16, DontPanic.game.world.height - 100, `rocket_${config.playerColour}`);
    player.scale.x = 0.5;
    player.scale.y = 0.5;
    player.anchor.set(0, 0);
    DontPanic.game.physics.arcade.enable(player);
    player.body.bounce.y = 0.2;
    player.body.setSize(65, 150, 0, 28, 0);
    player.body.immovable = true;
    player.body.gravity.y = 0;
    player.body.collideWorldBounds = true;
    player.frame = 1;
    player.lifeLostAnimate = player.animations.add('lifeLost', [-1,1,-1,1,-1]);
    // DontPanic.game.physics.p2.enable(player, true);
    //	Convex polys
    // player.body.clearShapes();
    // player.body.loadPolygon('physicsData', `rocket_${config.playerColour}`);
    this.playerSprite = player;
  }

  handleInput() {
    DontPanic.game.debug.spriteInfo(this.playerSprite, 32, 32);
    // DontPanic.game.debug.spriteBounds(player);
    DontPanic.game.debug.body(this.playerSprite);
    this.playerSprite.body.velocity.x = 0;
    if ((cursors.left.isDown && !cursors.right.isDown) || (DontPanic.game.input.pointer1.isDown && DontPanic.game.input.pointer1.x < DontPanic.game.world.centerX)) {
      this.moveLeft();
    }
    else if ((cursors.right.isDown && !cursors.left.isDown) || (DontPanic.game.input.pointer1.isDown && DontPanic.game.input.pointer1.x > DontPanic.game.world.centerX)) {
      this.moveRight();
    }
    else {
      this.moveUp();
    }
  }

  moveLeft() {
    this.playerSprite.body.velocity.x = -50;
    if (this.playerSprite.angle > -45) {
      this.playerSprite.angle -= 1;
    }
    this.playerSprite.frame = 2;
  }

  moveRight() {
    this.playerSprite.body.velocity.x = 50;
    if (this.playerSprite.angle < 45) {
      this.playerSprite.angle += 1;
    }
    this.playerSprite.frame = 0;
  }

  moveUp() {
    this.playerSprite.body.velocity.x = 0;
    if (this.playerSprite.angle > 0 ) {
      this.playerSprite.angle -= 1;
    }
    else if (this.playerSprite.angle < 0) {
      this.playerSprite.angle += 1;
    }
    this.playerSprite.frame = 1;
  }

  loseLifeFlash() {
    player.tint = 0xff0000;
  }
}
<commit_msg>update hit area when player moves<commit_after>class Player {
  constructor() {
    const player = DontPanic.game.add.sprite(DontPanic.game.world.width/2 - 16, DontPanic.game.world.height - 100, `rocket_${config.playerColour}`);
    player.scale.x = 0.5;
    player.scale.y = 0.5;
    player.anchor.set(0.5, 0.5);
    DontPanic.game.physics.arcade.enable(player);
    player.body.bounce.y = 0.2;
    player.body.setSize(65, 150, 28, 0);
    player.body.immovable = true;
    player.body.gravity.y = 0;
    player.body.collideWorldBounds = true;
    player.frame = 1;
    player.lifeLostAnimate = player.animations.add('lifeLost', [-1,1,-1,1,-1]);
    // DontPanic.game.physics.p2.enable(player, true);
    //	Convex polys
    // player.body.clearShapes();
    // player.body.loadPolygon('physicsData', `rocket_${config.playerColour}`);
    this.playerSprite = player;
  }

  handleInput() {
    DontPanic.game.debug.spriteInfo(this.playerSprite, 32, 32);
    // DontPanic.game.debug.spriteBounds(player);
    DontPanic.game.debug.body(this.playerSprite);
    this.playerSprite.body.velocity.x = 0;
    if ((cursors.left.isDown && !cursors.right.isDown) || (DontPanic.game.input.pointer1.isDown && DontPanic.game.input.pointer1.x < DontPanic.game.world.centerX)) {
      this.moveLeft();
    }
    else if ((cursors.right.isDown && !cursors.left.isDown) || (DontPanic.game.input.pointer1.isDown && DontPanic.game.input.pointer1.x > DontPanic.game.world.centerX)) {
      this.moveRight();
    }
    else {
      this.moveUp();
    }
  }

  moveLeft() {
    this.playerSprite.body.velocity.x = -50;
    if (this.playerSprite.angle > -45) {
      this.playerSprite.angle -= 1;
    }
    this.playerSprite.body.setSize(85, 150, 0, 20);
    this.playerSprite.frame = 2;
  }

  moveRight() {
    this.playerSprite.body.velocity.x = 50;
    if (this.playerSprite.angle < 45) {
      this.playerSprite.angle += 1;
    }
    this.playerSprite.body.setSize(85, 150, 40, 20);
    this.playerSprite.frame = 0;
  }

  moveUp() {
    this.playerSprite.body.velocity.x = 0;
    this.playerSprite.body.setSize(65, 150, 28, 0);
    if (this.playerSprite.angle > 0 ) {
      this.playerSprite.angle -= 1;
    }
    else if (this.playerSprite.angle < 0) {
      this.playerSprite.angle += 1;
    }
    this.playerSprite.frame = 1;
  }

  loseLifeFlash() {
    player.tint = 0xff0000;
  }
}
<|endoftext|>


<commit_before>function Pusher(options) {
  var that = this;
  // socket url
  that.url = options.url;
  // heartbeat interval
  that.heartbeat = null;
  // session id
  that.id = null;
  // min backoff
  that.minBackoff = 500;
  // max backoff
  that.maxBackoff = 30000;
  // exponential backoff
  that.backoff = that.minBackoff;
  // interval that sends heartbeats
  that.heartbeater = null;
  // socket
  that.socket = null;
  // reconnect timeout
  that.reconnector = null;
  // buffer while closed
  that.buffer = [];
  // callbacks
  that.callbacks = {};
  // error handler
  that.onerror = options.onerror || (function(err) { console.log('pusher error:', err); });
  // on connect handler
  that.onconnect = options.onconnect || (function(msg) { console.log('pusher connected:', msg); });
  /*
   * set up the socket
   */
  that.connect = function() {
    var url = that.url;
    if (that.id != null) {
      url += '?session_id=' + that.id;
    }
    that.socket = new WebSocket(url);
    that.socket.onopen = function() {
      that.lastHeartbeatReceived = new Date();
      that.backoff = that.minBackoff;
      while (that.buffer.length > 0) {
        that.send(that.buffer.shift());
      }
    };
    that.socket.onerror = function(err) {
      that.onerror(err);
    };
    that.socket.onmessage = function(message) {
      var msg = JSON.parse(message.data);
      that.handleMessage(msg);
    };
    that.socket.onclose = function() {
      that.close();
    };
  }
  /*
   * handle incoming messages
   */
  that.handleMessage = function(msg) {
    if (msg.Type == "Welcome") {
      that.heartbeat = msg.Welcome.Heartbeat;
      if (msg.Welcome.Id != that.id) {
        for (var uri in that.callbacks) {
          that.send({
            Type: 'Subscribe',
            URI: uri
          });
        }
      }
      that.id = msg.Welcome.Id;
      if (that.heartbeater != null) {
        clearInterval(that.heartbeater);
      }
      that.heartbeater = setInterval(function() {
        if (new Date().getTime() - that.lastHeartbeatReceived.getTime() > that.heartbeat) {
          that.close()
        } else {
          that.send({
            Type: "Heartbeat"
          });
        }
      }, that.heartbeat / 2);
      that.onconnect(msg);
    } else if (msg.Type == "Heartbeat") {
      that.lastHeartbeatReceived = new Date();
    } else if (msg.Type == "Message") {
      var callbacks = that.callbacks[msg.URI];
      if (callbacks != null) {
        for (var callback in callbacks) {
          callbacks[callback].apply(msg, msg.Data);
        }
      }
    } else if (msg.Type == "Error") {
      if (msg.Data.Type == "Subscribe") {
        delete(that.callbacks[msg.Data.URI]);
      }
      that.onerror(msg);
    } else {
      that.onerror({
        Type: "Error",
        Error: "Unknown message type " + msg.Type,
        Data: msg
      });
    }
  };
  that.authorize = function(uri, token, write) {
    that.send({
      Type: 'Authorize',
      URI: uri,
      Token: token,
      Write: write
    });
  };
  that.emit = function(uri, data) {
    // Copy arguments, becouse slice changes it.
    var args = Array.prototype.slice.call(arguments, 0);
    that.send({
      Type: 'Message',
      URI: uri,
      Data: args.slice(1)
    });
  };
  that.on = function(uri, callback) {
    if (that.callbacks[uri] == null) {
      that.callbacks[uri] = {};
      that.send({
        Type: 'Subscribe',
        URI: uri
      });
    }
    that.callbacks[uri][callback] = callback;
  };
  that.off = function(uri, callback) {
    delete(that.callbacks[uri][callback]);
    var left = 0;
    for (var callback in that.callbacks[uri]) {
      left++;
    }
    if (left == 0) {
      that.send({
        Type: 'Unsubscribe',
        URI: uri
      });
      delete(that.callbacks[uri]);
    }
  };
  /*
   * close
   */
  that.close = function() {
    clearInterval(that.heartbeater);
    that.heartbeater = null;
    that.socket.close();
    if (that.backoff < that.maxBackoff) {
      that.backoff *= 2;
    }
    if (that.reconnector != null) {
      clearTimeout(that.reconnector);
    }
    that.reconnector = setTimeout(that.connect, that.backoff);
  };
  /*
   * send a JSON encoded obj
   */
  that.send = function(obj) {
    if (that.socket.readyState == 1) {
      that.socket.send(JSON.stringify(obj));
    } else {
      that.buffer.push(obj);
    }
  };
  that.connect();
  return that;
}
<commit_msg>created an id sequence for the client. renamed callbacks to subscriptions. added callbacks and errbacks to provide proper async response handling in the client. moved buffer flushing from onconnect to incoming Welcome messages. made pusher.send provide ids for all objects with id==true, and register callback/errback for all objects with callback or errback.<commit_after>function Pusher(options) {
  var that = this;
  // next message id
  that.nextId = 0;
  // socket url
  that.url = options.url;
  // heartbeat interval
  that.heartbeat = null;
  // session id
  that.id = null;
  // min backoff
  that.minBackoff = 500;
  // max backoff
  that.maxBackoff = 30000;
  // exponential backoff
  that.backoff = that.minBackoff;
  // interval that sends heartbeats
  that.heartbeater = null;
  // socket
  that.socket = null;
  // reconnect timeout
  that.reconnector = null;
  // buffer while closed
  that.buffer = [];
  // subscriptions
  that.subscriptions = {};
  // callbacks
  that.callbacks = {};
  // errbacks
  that.errbacks = {};
  // error handler
  that.onerror = options.onerror || function(err) {
    console.log('pusher error:', err);
  };
  // on connect handler
  that.onconnect = options.onconnect || function(msg) {
    console.log('pusher connected:', msg);
  };
  // authorizer is a function that generate authorization tokens for your rights.
  that.authorizer = options.authorizer || function(uri, write) {
    console.log('authorizer returned empty token for ', uri, write);
    return "";
  };
  /*
   * set up the socket
   */
  that.connect = function() {
    var url = that.url;
    if (that.id != null) {
      url += '?session_id=' + that.id;
    }
    that.socket = new WebSocket(url);
    that.socket.onopen = function() {
      that.lastHeartbeatReceived = new Date();
      that.backoff = that.minBackoff;
    };
    that.socket.onerror = function(err) {
      that.onerror(err);
    };
    that.socket.onmessage = function(message) {
      var msg = JSON.parse(message.data);
      that.handleMessage(msg);
    };
    that.socket.onclose = function() {
      that.close();
    };
  }
  /*
   * handle incoming messages
   */
  that.handleMessage = function(msg) {
    if (msg.Type == "Welcome") {
      that.heartbeat = msg.Welcome.Heartbeat;
      if (that.id != null && msg.Welcome.Id != that.id) {
        for (var uri in that.subscriptions) {
          that.send({
            Type: 'Subscribe',
            URI: uri,
            Id: true
          });
        }
      }
      that.id = msg.Welcome.Id;
      if (that.heartbeater != null) {
        clearInterval(that.heartbeater);
      }
      that.heartbeater = setInterval(function() {
        if (new Date().getTime() - that.lastHeartbeatReceived.getTime() > that.heartbeat) {
          that.close()
        } else {
          if (that.socket.readyState == 1) {
            that.send({
              Type: "Heartbeat"
            });
          }
        }
      }, that.heartbeat / 2);
      while (that.buffer.length > 0) {
        that.send(that.buffer.shift());
      }
      that.onconnect(msg);
    } else if (msg.Type == "Heartbeat") {
      that.lastHeartbeatReceived = new Date();
    } else if (msg.Type == "Message") {
      var subscriptions = that.subscriptions[msg.URI];
      if (subscriptions != null) {
        for (var subscription in subscriptions) {
          subscriptions[subscription].apply(msg, msg.Data);
        }
      }
    } else if (msg.Type == "Error") {
      if (msg.Data.Type == "Subscribe") {
        delete(that.subscriptions[msg.Data.URI]);
      }
      var obj = that.errbacks[msg.Id];
      if (obj != null) {
        obj.errback.call(obj, msg);
      } else {
        that.onerror(msg);
      }
      delete(that.errbacks[msg.Id]);
      delete(that.callbacks[msg.Id]);
    } else if (msg.Type == "Ack") {
      var obj = that.callbacks[msg.Id];
      if (obj != null) {
        obj.callback.call(obj, msg);
      }
      delete(that.callbacks[msg.Id]);
      delete(that.errbacks[msg.Id]);
    } else {
      that.onerror({
        Type: "Error",
        Error: "Unknown message type " + msg.Type,
        Data: msg
      });
    }
  };
  that.emit = function(uri, data) {
    // Copy arguments, becouse slice changes it.
    var args = Array.prototype.slice.call(arguments, 0);
    that.send({
      Type: 'Message',
      URI: uri,
      Data: args.slice(1),
      Id: true
    });
  };
  that.on = function(uri, subscription) {
    if (that.subscriptions[uri] == null) {
      that.subscriptions[uri] = {};
      that.send({
        Type: 'Subscribe',
        URI: uri,
        Id: true
      });
    }
    that.subscriptions[uri][subscription] = subscription;
  };
  that.off = function(uri, subscription) {
    delete(that.subscriptions[uri][subscription]);
    var left = 0;
    for (var subscription in that.subscriptions[uri]) {
      left++;
    }
    if (left == 0) {
      that.send({
        Type: 'Unsubscribe',
        URI: uri,
        Id: true
      });
      delete(that.subscriptions[uri]);
    }
  };
  /*
   * close
   */
  that.close = function() {
    clearInterval(that.heartbeater);
    that.heartbeater = null;
    that.socket.close();
    if (that.backoff < that.maxBackoff) {
      that.backoff *= 2;
    }
    if (that.reconnector != null) {
      clearTimeout(that.reconnector);
    }
    that.reconnector = setTimeout(that.connect, that.backoff);
  };
  /*
   * send a JSON encoded obj
   */
  that.send = function(obj) {
    if (that.socket.readyState == 1) {
      if (obj.Id) {
        obj.Id = that.id + ":" + that.nextId++;
        if (obj.callback != null) {
          that.callbacks[obj.Id] = obj;
        }
        if (obj.errback != null) {
          that.errbacks[obj.Id] = obj;
        }
      }
      that.socket.send(JSON.stringify(obj));
    } else {
      that.buffer.push(obj);
    }
  };
  that.connect();
  return that;
}
<|endoftext|>


<commit_before>'use strict';

var LS = require('../js/plugins/LocalStorage');
var ls = new LS();

var unsupported = false;

if (!ls || ls.length < 1)
  unsupported = true;

if (window && window.navigator) {
  var rxaosp = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);
  var isaosp = (rxaosp && rxaosp[1] < 537);
  if (isaosp)
    unsupported = true;
}

//Setting up route
angular
  .module('copayApp')
  .config(function($routeProvider) {

    $routeProvider
      .when('/', {
        templateUrl: 'views/home.html',
      })
      .when('/createProfile', {
        templateUrl: 'views/createProfile.html',
      })
      .when('/unsupported', {
        templateUrl: 'views/unsupported.html'
      })
      .when('/confirmed', {
        template: " ", // just fire controller
        controller: 'EmailConfirmationController',
      })
    // Payment intents come here.
    .when('/uri-payment/:data', {
      template: " ", // just fire controller
      controller: 'paymentUriController',
    })
      .when('/selectWalletForPayment', {
        template: " ", // just fire controller
        controller: 'walletForPaymentController',
        logged: true
      })
      .when('/join', {
        templateUrl: 'views/join.html',
        logged: true
      })
      .when('/import', {
        templateUrl: 'views/import.html',
        logged: true
      })
      .when('/importProfile', {
        templateUrl: 'views/importProfile.html',
      })
      .when('/create', {
        templateUrl: 'views/create.html',
        logged: true
      })
      .when('/copayers', {
        templateUrl: 'views/copayers.html',
        logged: true
      })
      .when('/homeWallet', {
        templateUrl: 'views/homeWallet.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/receive', {
        templateUrl: 'views/receive.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/history', {
        templateUrl: 'views/history.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/send', {
        templateUrl: 'views/send.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/more', {
        templateUrl: 'views/more.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/settings', {
        templateUrl: 'views/settings.html',
        walletShouldBeComplete: true,
        logged: false
      })
      .when('/warning', {
        templateUrl: 'views/warning.html',
        logged: true
      })
      .when('/profile', {
        templateUrl: 'views/profile.html',
        logged: true
      })
      .when('/add', {
        templateUrl: 'views/add.html',
        logged: true
      });

    if (config.developmentFeatures) {
      $routeProvider.when('/devLogin/:mail/:password', {
        templateUrl: 'views/devLogin.html',
        logged: false
      });
    }

    $routeProvider.otherwise({
      templateUrl: 'views/errors/404.html',
      title: 'Error'
    });
  });

//Setting HTML5 Location Mode
angular
  .module('copayApp')
  .config(function($locationProvider, $idleProvider, $keepaliveProvider) {
    $locationProvider
      .html5Mode(false)
      .hashPrefix('!');
    // IDLE timeout
    var timeout = config.wallet.idleDurationMin * 60 || 300;
    $idleProvider.idleDuration(timeout); // in seconds
    $idleProvider.warningDuration(40); // in seconds
    $keepaliveProvider.interval(30); // in seconds
  })
  .run(function($rootScope, $location, $idle, gettextCatalog, uriHandler, isCordova) {

    gettextCatalog.currentLanguage = config.defaultLanguage;

    // Register URI handler, not for mobileApp
    if (!isCordova) {
      $idle.watch();
      uriHandler.register();
    }

    $rootScope.$on('$routeChangeStart', function(event, next, current) {
      if (unsupported && !isCordova) {
        $location.path('unsupported');
        return;
      }

      if (!$rootScope.iden && next.logged) {
        $idle.unwatch();
        $location.path('/');
      }
      if ($rootScope.wallet && !$rootScope.wallet.isComplete() && next.walletShouldBeComplete) {
        $location.path('/copayers');
      }
    });
  })
  .config(function($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel|chrome-extension|resource):/);
  });
<commit_msg>Fixing condition for supported browsers<commit_after>'use strict';

var LS = require('../js/plugins/LocalStorage');
var ls = new LS();

var unsupported = false;

if (!ls || ls.length < 1)
  unsupported = true;

if (window && window.navigator) {
  var rxaosp = window.navigator.userAgent.match(/Android.*AppleWebKit\/([\d.]+)/);
  var isaosp = (rxaosp && rxaosp[1] < 534);
  if (isaosp)
    unsupported = true;
}

//Setting up route
angular
  .module('copayApp')
  .config(function($routeProvider) {

    $routeProvider
      .when('/', {
        templateUrl: 'views/home.html',
      })
      .when('/createProfile', {
        templateUrl: 'views/createProfile.html',
      })
      .when('/unsupported', {
        templateUrl: 'views/unsupported.html'
      })
      .when('/confirmed', {
        template: " ", // just fire controller
        controller: 'EmailConfirmationController',
      })
    // Payment intents come here.
    .when('/uri-payment/:data', {
      template: " ", // just fire controller
      controller: 'paymentUriController',
    })
      .when('/selectWalletForPayment', {
        template: " ", // just fire controller
        controller: 'walletForPaymentController',
        logged: true
      })
      .when('/join', {
        templateUrl: 'views/join.html',
        logged: true
      })
      .when('/import', {
        templateUrl: 'views/import.html',
        logged: true
      })
      .when('/importProfile', {
        templateUrl: 'views/importProfile.html',
      })
      .when('/create', {
        templateUrl: 'views/create.html',
        logged: true
      })
      .when('/copayers', {
        templateUrl: 'views/copayers.html',
        logged: true
      })
      .when('/homeWallet', {
        templateUrl: 'views/homeWallet.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/receive', {
        templateUrl: 'views/receive.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/history', {
        templateUrl: 'views/history.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/send', {
        templateUrl: 'views/send.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/more', {
        templateUrl: 'views/more.html',
        walletShouldBeComplete: true,
        logged: true
      })
      .when('/settings', {
        templateUrl: 'views/settings.html',
        walletShouldBeComplete: true,
        logged: false
      })
      .when('/warning', {
        templateUrl: 'views/warning.html',
        logged: true
      })
      .when('/profile', {
        templateUrl: 'views/profile.html',
        logged: true
      })
      .when('/add', {
        templateUrl: 'views/add.html',
        logged: true
      });

    if (config.developmentFeatures) {
      $routeProvider.when('/devLogin/:mail/:password', {
        templateUrl: 'views/devLogin.html',
        logged: false
      });
    }

    $routeProvider.otherwise({
      templateUrl: 'views/errors/404.html',
      title: 'Error'
    });
  });

//Setting HTML5 Location Mode
angular
  .module('copayApp')
  .config(function($locationProvider, $idleProvider, $keepaliveProvider) {
    $locationProvider
      .html5Mode(false)
      .hashPrefix('!');
    // IDLE timeout
    var timeout = config.wallet.idleDurationMin * 60 || 300;
    $idleProvider.idleDuration(timeout); // in seconds
    $idleProvider.warningDuration(40); // in seconds
    $keepaliveProvider.interval(30); // in seconds
  })
  .run(function($rootScope, $location, $idle, gettextCatalog, uriHandler, isCordova) {

    gettextCatalog.currentLanguage = config.defaultLanguage;

    // Register URI handler, not for mobileApp
    if (!isCordova) {
      $idle.watch();
      uriHandler.register();
    }

    $rootScope.$on('$routeChangeStart', function(event, next, current) {
      if (unsupported) {
        $location.path('unsupported');
        return;
      }

      if (!$rootScope.iden && next.logged) {
        $idle.unwatch();
        $location.path('/');
      }
      if ($rootScope.wallet && !$rootScope.wallet.isComplete() && next.walletShouldBeComplete) {
        $location.path('/copayers');
      }
    });
  })
  .config(function($compileProvider) {
    $compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|file|tel|chrome-extension|resource):/);
  });
<|endoftext|>


<commit_before>var userMetaManager = (function () {
    var metaInformation = [];
    var userId;
    $('#usersMeta').dataTable({
        "dom": '<"top">rt<"bottom" pl>',
        "order": [[0, "asc"]],
        'scrollX': true,
        "autoWidth": false
    });

    $('#submitMeta').click(function (e) {
        e.preventDefault();
        if ($('#txtMetaKey').val() !== '') {
            getMetaMatchLIst();
        } else {
            $('#txtMetaKey').addClass('error');
        }
    });

    $('body').on('click', '.user-mail', function (e) {
        e.preventDefault();
        jQuery('.user-meta-results').html('');
        userId = +($($(this).parents('tr').find('#userId')).html());
        getUserMetaInformation();
    });

    $('body').on('click', '#imgClose', function () {
        jQuery('.user-meta-information').hide();
    });

    $('body').on('click', '#updateUserMetaInformation', function () {
        var updateMetaInformation = [];
        var updatedMetaData = {};
        for (var i = 1; i < jQuery('#userMetaInformation tr').length; i++) {
            var key = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input[type="text"]')[0]).val();
            var value = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input[type="text"]')[1]).val();
            updateMetaInformation[key] = value;
        }
        for (var key in updateMetaInformation) {
            if (metaInformation[key] !== updateMetaInformation[key]) {
                updatedMetaData[key] = updateMetaInformation[key];
            }
        }
        var data = {
            'action': 'update_user_meta_data',
            'security': myAjax.ajax_nonce,
            'userId': userId,
            'userMetaData': updatedMetaData
        };
        ajaxCall(data, showMessage);

    });

    $('body').on('click', '#addUserMetaInformation', function () {
        addMetaKeyValue();
    });

    $('body').on('click', '#deleteUserMetaInformation', function () {
        deleteUserMetaInformation();
    });

    // Function to show the
    function showMessage(data) {
        var json = JSON.parse(data);
        jQuery('#myModal').modal('hide');
        console.log(json.error);
        if (json['error']) {
            var container = jQuery('#modalnfo').find('.modal-body');
            jQuery(container).html(json['error']);
            jQuery('#modalnfo').modal('show');
        }
        else {
            var container = jQuery('#modalSuccess').find('.modal-body');
            jQuery(container).html(json['success']);
            jQuery('#modalSuccess').modal('show');
        }
    }
    // Function to get the user meta information.
    function  getUserMetaInformation() {
        var data = {
            action: "get_user_meta_details",
            'security': myAjax.ajax_nonce,
            "userId": userId
        };
        ajaxCall(data, showMetaDetails);
    }

    // Function to delete the User meta information from the meta list available..
    function deleteUserMetaInformation() {
        var deleteMetaInformation = {};
        for (var i = 1; i < jQuery('#userMetaInformation tr').length; i++) {
            var check = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input:checked'));
            if (check.length) {
                var key = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input')[1]).val();
                var value = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input')[2]).val();
                deleteMetaInformation[key] = value;
            }
        }
        var data = {
            'action': 'delete_user_meta',
            'security': myAjax.ajax_nonce,
            'userId': userId,
            'userMetaData': deleteMetaInformation
        };
        ajaxCall(data, showMessage);

    }

// Function to shoe the user meta details.
    function showMetaDetails(result) {
        metaInformation = [];
        jQuery('#userMetaInformation').DataTable().destroy();
        jQuery('#userMetaDetails').html(result);
        jQuery('#myModal').modal('show');
        jQuery('.user-meta-information').show();
        jQuery('#userMetaInformation').dataTable({
            "dom": '<"top">rt<"bottom">',
            "columnDefs": [
                {"width": "180px", "targets": 1}
            ],
            "autoWidth": false,
            "paging": false,
            "scrollY": "400px",
            "scrollCollapse": false,
            sortable: false,
            "bSort": false
        });

        for (var i = 1; i < jQuery('#userMetaInformation tr').length; i++) {
            var key = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input[type="text"]')[0]).val();
            var value = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input[type="text"]')[1]).val();
            metaInformation[key] = value;
        }
    }

    // Function to show the meta information of the user.
    function showmetaLIst(result) {
        jQuery('#usersMeta').DataTable().destroy();
        jQuery('#userMeta').DataTable().clear().draw();
        jQuery('.user-meta-information').remove();
        jQuery('.meta-results').html('');
        jQuery('.meta-table-results').html(result);
        jQuery('.user-meta-information').show();
        $('#usersMeta').dataTable({
            "dom": '<"top">rt<"bottom" pl>',
            "language": {
                "emptyTable": "There are no users with the specificied meta combination."
            },
            'scrollX': true,
            "autoWidth": false
        });
    }

    // Function to get the list of users who has meta key and value matched.
    function getMetaMatchLIst() {
        jQuery('#txtMetaKey').removeClass('error');
        var metakey = jQuery('#txtMetaKey').val();
        var metaValue = jQuery('#txtMetaValue').val();
        var data = {
            action: "meta_search",
            security: myAjax.ajax_nonce,
            "metaKey": metakey,
            "metaValue": metaValue
        };
        ajaxCall(data, showmetaLIst);
    }

// Function to make a ajax call
    function ajaxCall(data, cbFunction, chidCbFunc) {
        jQuery.ajax({
            url: myAjax.ajaxurl,
            type: "post",
            data: data,
            success: function (result) {
                if (chidCbFunc) {
                    chidCbFunc();
                }
                cbFunction(result);
            },
            error: function (xhr) {
                console.log(xhr);
                jQuery.notify('Unable to process your request', "error");
            }
        });
    }

// Function to append the new meta key and value to the existing meta information.
    function addMetaKeyValue() {
        var appendContent = '
<input  type="checkbox" name="meta[]">	';
        appendContent += '<input type="text" placeholder="  Meta key.....">	';
        appendContent += '<input type="text" placeholder=" Meta value...."
';
        jQuery('#userMetaInformation').append(appendContent);
        jQuery('html, .dataTables_scrollBody').animate({scrollTop: jQuery('#userMetaInformation tr:last').offset().top}, 500);
        jQuery('#updateUserMetaInformation').html('Save');

    }
});
jQuery(userMetaManager);
<commit_msg>Added the functionality of reloading the page when the response from the server is -1.<commit_after>var userMetaManager = (function () {
    var metaInformation = [];
    var userId;
    $('#usersMeta').dataTable({
        "dom": '<"top">rt<"bottom" pl>',
        "order": [[0, "asc"]],
        'scrollX': true,
        "autoWidth": false
    });

    $('#submitMeta').click(function (e) {
        e.preventDefault();
        if ($('#txtMetaKey').val() !== '') {
            getMetaMatchLIst();
        } else {
            $('#txtMetaKey').addClass('error');
        }
    });

    $('body').on('click', '.user-mail', function (e) {
        e.preventDefault();
        jQuery('.user-meta-results').html('');
        userId = +($($(this).parents('tr').find('#userId')).html());
        getUserMetaInformation();
    });

    $('body').on('click', '#imgClose', function () {
        jQuery('.user-meta-information').hide();
    });

    $('body').on('click', '#updateUserMetaInformation', function () {
        var updateMetaInformation = [];
        var updatedMetaData = {};
        for (var i = 1; i < jQuery('#userMetaInformation tr').length; i++) {
            var key = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input[type="text"]')[0]).val();
            var value = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input[type="text"]')[1]).val();
            updateMetaInformation[key] = value;
        }
        for (var key in updateMetaInformation) {
            if (metaInformation[key] !== updateMetaInformation[key]) {
                updatedMetaData[key] = updateMetaInformation[key];
            }
        }
        var data = {
            'action': 'update_user_meta_data',
            'security': myAjax.ajax_nonce,
            'userId': userId,
            'userMetaData': updatedMetaData
        };
        ajaxCall(data, showMessage);

    });

    $('body').on('click', '#addUserMetaInformation', function () {
        addMetaKeyValue();
    });

    $('body').on('click', '#deleteUserMetaInformation', function () {
        deleteUserMetaInformation();
    });

    // Function to show the
    function showMessage(data) {
        var json = JSON.parse(data);
        jQuery('#myModal').modal('hide');
        console.log(json.error);
        if (json['error']) {
            var container = jQuery('#modalnfo').find('.modal-body');
            jQuery(container).html(json['error']);
            jQuery('#modalnfo').modal('show');
        }
        else {
            var container = jQuery('#modalSuccess').find('.modal-body');
            jQuery(container).html(json['success']);
            jQuery('#modalSuccess').modal('show');
        }
    }
    // Function to get the user meta information.
    function  getUserMetaInformation() {
        var data = {
            action: "get_user_meta_details",
            'security': myAjax.ajax_nonce,
            "userId": userId
        };
        ajaxCall(data, showMetaDetails);
    }

    // Function to delete the User meta information from the meta list available..
    function deleteUserMetaInformation() {
        var deleteMetaInformation = {};
        for (var i = 1; i < jQuery('#userMetaInformation tr').length; i++) {
            var check = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input:checked'));
            if (check.length) {
                var key = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input')[1]).val();
                var value = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input')[2]).val();
                deleteMetaInformation[key] = value;
            }
        }
        var data = {
            'action': 'delete_user_meta',
            'security': myAjax.ajax_nonce,
            'userId': userId,
            'userMetaData': deleteMetaInformation
        };
        ajaxCall(data, showMessage);

    }

// Function to shoe the user meta details.
    function showMetaDetails(result) {
        metaInformation = [];
        jQuery('#userMetaInformation').DataTable().destroy();
        jQuery('#userMetaDetails').html(result);
        jQuery('#myModal').modal('show');
        jQuery('.user-meta-information').show();
        jQuery('#userMetaInformation').dataTable({
            "dom": '<"top">rt<"bottom">',
            "columnDefs": [
                {"width": "180px", "targets": 1}
            ],
            "autoWidth": false,
            "paging": false,
            "scrollY": "400px",
            "scrollCollapse": false,
            sortable: false,
            "bSort": false
        });

        for (var i = 1; i < jQuery('#userMetaInformation tr').length; i++) {
            var key = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input[type="text"]')[0]).val();
            var value = jQuery(jQuery(jQuery('#userMetaInformation tr')[i]).find('input[type="text"]')[1]).val();
            metaInformation[key] = value;
        }
    }

    // Function to show the meta information of the user.
    function showmetaLIst(result) {
        jQuery('#usersMeta').DataTable().destroy();
        jQuery('#userMeta').DataTable().clear().draw();
        jQuery('.user-meta-information').remove();
        jQuery('.meta-results').html('');
        jQuery('.meta-table-results').html(result);
        jQuery('.user-meta-information').show();
        $('#usersMeta').dataTable({
            "dom": '<"top">rt<"bottom" pl>',
            "language": {
                "emptyTable": "There are no users with the specificied meta combination."
            },
            'scrollX': true,
            "autoWidth": false
        });
    }

    // Function to get the list of users who has meta key and value matched.
    function getMetaMatchLIst() {
        jQuery('#txtMetaKey').removeClass('error');
        var metakey = jQuery('#txtMetaKey').val();
        var metaValue = jQuery('#txtMetaValue').val();
        var data = {
            action: "meta_search",
            security: myAjax.ajax_nonce,
            "metaKey": metakey,
            "metaValue": metaValue
        };
        ajaxCall(data, showmetaLIst);
    }

// Function to make a ajax call
    function ajaxCall(data, cbFunction, chidCbFunc) {
        jQuery.ajax({
            url: myAjax.ajaxurl,
            type: "post",
            data: data,
            success: function (result) {
                if (result !== '-1') {
                    if (chidCbFunc) {
                        chidCbFunc();
                    }
                    cbFunction(result);
                }
                else {
                    location.reload();
                }
            },
            error: function (xhr) {
                console.log(xhr);
                jQuery.notify('Unable to process your request', "error");
            }
        });
    }

// Function to append the new meta key and value to the existing meta information.
    function addMetaKeyValue() {
        var appendContent = '
<input  type="checkbox" name="meta[]">	';
        appendContent += '<input type="text" placeholder="  Meta key.....">	';
        appendContent += '<input type="text" placeholder=" Meta value...."
';
        jQuery('#userMetaInformation').append(appendContent);
        jQuery('html, .dataTables_scrollBody').animate({scrollTop: jQuery('#userMetaInformation tr:last').offset().top}, 500);
        jQuery('#updateUserMetaInformation').html('Save');

    }
});
jQuery(userMetaManager);
<|endoftext|>