<commit_before>dojo.provide("dojox.rpc.JsonReferencing");
dojo.require("dojo.date.stamp");
dojo.require("dojo._base.Deferred");

// summary:
// Adds advanced JSON {de}serialization capabilities to the base json library.
// This enhances the capabilities of dojo.toJson and dojo.fromJson,
// adding referencing support, date handling, and other extra format handling.
// On parsing, references are resolved. When references are made to
// ids/objects that have been loaded yet, a Deferred object will be used as the
// value and as soon as a callback is added to the Deferred object, the target
// object will be loaded.

dojox.rpc._index={}; // the global map of id->object
dojox.rpc.onUpdate = function(/*Object*/ object,  /* attribute-name-string */ attribute,  /* any */ oldValue,  /* any */ newValue){
		//	summary:
		//		This function is called when an existing object in the system is updated. Existing objects are found by id.
};

dojox.rpc.resolveJson = function(/*Object*/ root,/*Object?*/ schema){
	// summary:
	// 		Indexes and resolves references in the JSON object.
	// A JSON Schema object that can be used to advise the handling of the JSON (defining ids, date properties, urls, etc)
	//
	// root:
	//		The root object of the object graph to be processed
	//
	// schema: A JSON Schema object that can be used to advise the parsing of the JSON (defining ids, date properties, urls, etc)	//
	// 		Currently this provides a means for context based id handling
	//
	// return:
	//		An object, the result of the processing
	var ref,reWalk=[];
	function makeIdInfo(schema){ // find out what attribute and what id prefix to use
		if (schema){
			var attr;
			if (!(attr = schema._idAttr)){
				for (var i in schema.properties){
					if (schema.properties[i].unique){
						schema._idAttr = attr = i;
					}
				}
			}
			if (attr || schema._idPrefix){
				return {attr:attr || 'id',prefix:schema._idPrefix};
			}
		}

		return false;
	}
	function walk(it,stop,schema,idInfo,defaultId){
		// this walks the new graph, resolving references and making other changes
	 	var val,i;
	 	var id = it[idInfo.attr];
	 	id = (id && (idInfo.prefix + id)) || defaultId; // if there is an id, prefix it, otherwise inherit
	 	var target = it;

		if (id){ // if there is an id available...
			it._id = id;
			if (dojox.rpc._index[id]){ // if the id already exists in the system, we should use the existing object, and just update it
				target = dojox.rpc._index[id];
				delete target.$ref; // remove this artifact
			}
			dojox.rpc._index[id] = target; // add the prefix, set _id, and index it
			if (schema && dojox.validate && dojox.validate.jsonSchema){ // if json schema is activated, we can load it in the registry of instance schemas map
				dojox.validate.jsonSchema._schemas[id] = schema;
			}

		}
		for (i in it){
			if (it.hasOwnProperty(i) && (typeof (val=it[i]) =='object') && val){
				ref=val.$ref;
				if (ref){ // a reference was found
					var stripped = ref.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');// trim it
					if(/[\w\[\]\.\$ \/\r\n\t]/.test(stripped) && !/=|((^|\W)new\W)/.test(stripped)){ // make sure it is a safe reference
						var path = ref.match(/(^\.*[^\.\[]+)([\.\[].*)?/); // divide along the path
						if ((ref=path[1]=='$' ? root:dojox.rpc._index[new dojo._Url(idInfo.prefix,path[1])]) &&  // a $ indicates to start with the root, otherwise start with an id
							(ref = path[2] ? eval('ref' + path[2]) : ref)){// starting point was found, use eval to resolve remaining property references
							// otherwise, no starting point was found (id not found), if stop is set, it does not exist, we have
							// unloaded reference, if stop is not set, it may be in a part of the graph not walked yet,
							// we will wait for the second loop
							val = ref;
						}
						else{
							if (!stop){
								if (!rewalking)
									reWalk.push(it); // we need to rewalk it to resolve references
								var rewalking = true; // we only want to add it once
							}
							else {
								ref = val.$ref;
								val = new dojo.Deferred();
								val._id = idInfo.prefix + ref;
								(function(val,ref){
									var connectId = dojo.connect(val,"addCallbacks",function(){
										dojo.disconnect(connectId);
										dojox.rpc.services[idInfo.prefix.substring(0,idInfo.prefix.length-1)](ref) // otherwise call by looking up the service
											.addCallback(dojo.hitch(val,val.callback));

									});
								})(val,ref);
							}
						}
					}
				}
				else {
					if (!stop){ // if we are in stop, that means we are in the second loop, and we only need to check this current one,
										// further walking may lead down circular loops
						var valSchema = val.schema || // a schema can be self-defined by the object,
										(schema && schema.properties && schema.properties[i]);  // or it can from the schema sub-object definition
						if (valSchema){
							idInfo = makeIdInfo(valSchema)||idInfo;
						}
						val = walk(val,reWalk==it,valSchema,idInfo,id && (id + ('[' + dojo._escapeString(i) + ']')));
					}
				}
			}
			if (dojo.isString(val) && schema && schema.properties && schema.properties[i] && schema.properties[i].format=='date-time'){// parse the date string
				val = dojo.date.stamp.fromISOString(val); // create a date object
			}
			it[i] = val;
			var old = target[i];
			if (val !== old){ // only update if it changed
				target[i] = val; // update the target
				propertyChange(i,old,val);
			}
		}
		function propertyChange(key,old,newValue){
			setTimeout(function(){
				dojox.rpc.onUpdate(target,i,old,newValue); // call the listener for each update
			});
		}
		if (target != it){ // this means we are updating, we need to remove deleted
			for (i in target){
				if (!it.hasOwnProperty(i) && i != '_id' && !(target instanceof Array && isNaN(i))){
					propertyChange(i,target[i],undefined);
					delete target[i];
				}
			}
		}
		return target;
	}
	var idInfo = makeIdInfo(schema)||{attr:'id',prefix:''};
	if (!root){ return root; }
	root = walk(root,false,schema,idInfo,dojox._newId && (new dojo._Url(idInfo.prefix,dojox._newId) +'')); // do the main walk through
	walk(reWalk,false,schema,idInfo); // re walk any parts that were not able to resolve references on the first round
	return root;
};
dojox.rpc.fromJson = function(/*String*/ str,/*Object?*/ schema){
	// summary:
	// 		evaluates the passed string-form of a JSON object.
	// A JSON Schema object that can be used to advise the parsing of the JSON (defining ids, date properties, urls, etc)
	// which may defined by setting dojox.currentSchema to the current schema you want to use for this evaluation
	//
	// json:
	//		a string literal of a JSON item, for instance:
	//			'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'
	// schema: A JSON Schema object that can be used to advise the parsing of the JSON (defining ids, date properties, urls, etc)	//
	// 		Currently this provides a means for context based id handling
	//
	// return:
	//		An object, the result of the evaluation
	root = eval('(' + str + ')'); // do the eval
	if (root){
		return this.resolveJson(root,schema);
	}
	return root;
}
dojox.rpc.toJson = function(/*Object*/ it, /*Boolean?*/ prettyPrint, /*Object?*/ schema){
	// summary:
	//		Create a JSON serialization of an object.
	//		This has support for referencing, including circular references, duplicate references, and out-of-message references
	// 		id and path-based referencing is supported as well and is based on http://www.json.com/2007/10/19/json-referencing-proposal-and-library/.
	//
	// it:
	//		an object to be serialized.
	//
	// prettyPrint:
	//		if true, we indent objects and arrays to make the output prettier.
	//		The variable dojo.toJsonIndentStr is used as the indent string
	//		-- to use something other than the default (tab),
	//		change that variable before calling dojo.toJson().
	//
	// schema: A JSON Schema object that can be used to advise the parsing of the JSON (defining ids, date properties, urls, etc)	//
	// 		Currently this provides a means for context based id handling
	//
	// return:
	//		a String representing the serialized version of the passed object.

	var idPrefix = (schema&& schema._idPrefix) || ''; // the id prefix for this context
	var paths={};
	function serialize(it,path,_indentStr){
		if (it && dojo.isObject(it)){
			var value;
			if (it instanceof Date){ // properly serialize dates
				return '"' + dojo.date.stamp.toISOString(it,{zulu:true}) + '"';
			}
			var id = it._id;
			if (id){ // we found an identifiable object, we will just serialize a reference to it... unless it is the root

				if (path != '$'){
					return serialize({$ref:id.charAt(0)=='$' ? id : // a pure path based reference, leave it alone
 									id.substring(0,idPrefix.length)==idPrefix ?  // see if the reference is in the current context
 										id.substring(idPrefix.length): // a reference with a prefix matching the current context, the prefix should be removed
	 										'../' + id});// a reference to a different context, assume relative url based referencing
				}
				path = id;
			}
			else {
				it._id = path; // we will create path ids for other objects in case they are circular
				paths[path] = it;// save it here so they can be deleted at the end
			}
			_indentStr = _indentStr || "";
			var nextIndent = prettyPrint ? _indentStr + dojo.toJsonIndentStr : "";
			var newLine = prettyPrint ? "\n" : "";
			var sep = prettyPrint ? " " : "";

			if (it instanceof Array){
				var res = dojo.map(it, function(obj,i){
					var val = serialize(obj, path + '[' + i + ']', nextIndent);
					if(!dojo.isString(val)){
						val = "undefined";
					}
					return newLine + nextIndent + val;
				});
				return "[" + res.join("," + sep) + newLine + _indentStr + "]";
			}

			var output = [];
			for(var i in it){
				var keyStr;
				if(typeof i == "number"){
					keyStr = '"' + i + '"';
				}else if(dojo.isString(i) && i != '_id'){
					keyStr = dojo._escapeString(i);
				}else{
					// skip non-string or number keys
					continue;
				}
				var val = serialize(it[i],path+(i.match(/^[a-zA-Z]\w*$/) ? // can we use simple .property syntax?
													('.' + i) : // yes, otherwise we have to escape it
													('[' + dojo._escapeString(i) + ']')),nextIndent);
				if(!dojo.isString(val)){
					// skip non-serializable values
					continue;
				}
				output.push(newLine + nextIndent + keyStr + ":" + sep + val);
			}
			return "{" + output.join("," + sep) + newLine + _indentStr + "}";
		}

		return dojo.toJson(it); // use the default serializer for primitives
	}
	var json = serialize(it,'$','');
	for (i in paths){  // cleanup the temporary path-generated ids
		delete paths[i]._id;
	}
	return json;
}
<commit_msg>refs #6653, fix an accidental global reference in dojox.rpc.JsonReferencing<commit_after>dojo.provide("dojox.rpc.JsonReferencing");
dojo.require("dojo.date.stamp");
dojo.require("dojo._base.Deferred");

// summary:
// Adds advanced JSON {de}serialization capabilities to the base json library.
// This enhances the capabilities of dojo.toJson and dojo.fromJson,
// adding referencing support, date handling, and other extra format handling.
// On parsing, references are resolved. When references are made to
// ids/objects that have been loaded yet, a Deferred object will be used as the
// value and as soon as a callback is added to the Deferred object, the target
// object will be loaded.

dojox.rpc._index={}; // the global map of id->object
dojox.rpc.onUpdate = function(/*Object*/ object,  /* attribute-name-string */ attribute,  /* any */ oldValue,  /* any */ newValue){
		//	summary:
		//		This function is called when an existing object in the system is updated. Existing objects are found by id.
};

dojox.rpc.resolveJson = function(/*Object*/ root,/*Object?*/ schema){
	// summary:
	// 		Indexes and resolves references in the JSON object.
	// A JSON Schema object that can be used to advise the handling of the JSON (defining ids, date properties, urls, etc)
	//
	// root:
	//		The root object of the object graph to be processed
	//
	// schema: A JSON Schema object that can be used to advise the parsing of the JSON (defining ids, date properties, urls, etc)	//
	// 		Currently this provides a means for context based id handling
	//
	// return:
	//		An object, the result of the processing
	var ref,reWalk=[];
	function makeIdInfo(schema){ // find out what attribute and what id prefix to use
		if (schema){
			var attr;
			if (!(attr = schema._idAttr)){
				for (var i in schema.properties){
					if (schema.properties[i].unique){
						schema._idAttr = attr = i;
					}
				}
			}
			if (attr || schema._idPrefix){
				return {attr:attr || 'id',prefix:schema._idPrefix};
			}
		}

		return false;
	}
	function walk(it,stop,schema,idInfo,defaultId){
		// this walks the new graph, resolving references and making other changes
	 	var val,i;
	 	var id = it[idInfo.attr];
	 	id = (id && (idInfo.prefix + id)) || defaultId; // if there is an id, prefix it, otherwise inherit
	 	var target = it;

		if (id){ // if there is an id available...
			it._id = id;
			if (dojox.rpc._index[id]){ // if the id already exists in the system, we should use the existing object, and just update it
				target = dojox.rpc._index[id];
				delete target.$ref; // remove this artifact
			}
			dojox.rpc._index[id] = target; // add the prefix, set _id, and index it
			if (schema && dojox.validate && dojox.validate.jsonSchema){ // if json schema is activated, we can load it in the registry of instance schemas map
				dojox.validate.jsonSchema._schemas[id] = schema;
			}

		}
		for (i in it){
			if (it.hasOwnProperty(i) && (typeof (val=it[i]) =='object') && val){
				ref=val.$ref;
				if (ref){ // a reference was found
					var stripped = ref.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, '');// trim it
					if(/[\w\[\]\.\$ \/\r\n\t]/.test(stripped) && !/=|((^|\W)new\W)/.test(stripped)){ // make sure it is a safe reference
						var path = ref.match(/(^\.*[^\.\[]+)([\.\[].*)?/); // divide along the path
						if ((ref=path[1]=='$' ? root:dojox.rpc._index[new dojo._Url(idInfo.prefix,path[1])]) &&  // a $ indicates to start with the root, otherwise start with an id
							(ref = path[2] ? eval('ref' + path[2]) : ref)){// starting point was found, use eval to resolve remaining property references
							// otherwise, no starting point was found (id not found), if stop is set, it does not exist, we have
							// unloaded reference, if stop is not set, it may be in a part of the graph not walked yet,
							// we will wait for the second loop
							val = ref;
						}
						else{
							if (!stop){
								if (!rewalking)
									reWalk.push(it); // we need to rewalk it to resolve references
								var rewalking = true; // we only want to add it once
							}
							else {
								ref = val.$ref;
								val = new dojo.Deferred();
								val._id = idInfo.prefix + ref;
								(function(val,ref){
									var connectId = dojo.connect(val,"addCallbacks",function(){
										dojo.disconnect(connectId);
										dojox.rpc.services[idInfo.prefix.substring(0,idInfo.prefix.length-1)](ref) // otherwise call by looking up the service
											.addCallback(dojo.hitch(val,val.callback));

									});
								})(val,ref);
							}
						}
					}
				}
				else {
					if (!stop){ // if we are in stop, that means we are in the second loop, and we only need to check this current one,
										// further walking may lead down circular loops
						var valSchema = val.schema || // a schema can be self-defined by the object,
										(schema && schema.properties && schema.properties[i]);  // or it can from the schema sub-object definition
						if (valSchema){
							idInfo = makeIdInfo(valSchema)||idInfo;
						}
						val = walk(val,reWalk==it,valSchema,idInfo,id && (id + ('[' + dojo._escapeString(i) + ']')));
					}
				}
			}
			if (dojo.isString(val) && schema && schema.properties && schema.properties[i] && schema.properties[i].format=='date-time'){// parse the date string
				val = dojo.date.stamp.fromISOString(val); // create a date object
			}
			it[i] = val;
			var old = target[i];
			if (val !== old){ // only update if it changed
				target[i] = val; // update the target
				propertyChange(i,old,val);
			}
		}
		function propertyChange(key,old,newValue){
			setTimeout(function(){
				dojox.rpc.onUpdate(target,i,old,newValue); // call the listener for each update
			});
		}
		if (target != it){ // this means we are updating, we need to remove deleted
			for (i in target){
				if (!it.hasOwnProperty(i) && i != '_id' && !(target instanceof Array && isNaN(i))){
					propertyChange(i,target[i],undefined);
					delete target[i];
				}
			}
		}
		return target;
	}
	var idInfo = makeIdInfo(schema)||{attr:'id',prefix:''};
	if (!root){ return root; }
	root = walk(root,false,schema,idInfo,dojox._newId && (new dojo._Url(idInfo.prefix,dojox._newId) +'')); // do the main walk through
	walk(reWalk,false,schema,idInfo); // re walk any parts that were not able to resolve references on the first round
	return root;
};
dojox.rpc.fromJson = function(/*String*/ str,/*Object?*/ schema){
	// summary:
	// 		evaluates the passed string-form of a JSON object.
	// A JSON Schema object that can be used to advise the parsing of the JSON (defining ids, date properties, urls, etc)
	// which may defined by setting dojox.currentSchema to the current schema you want to use for this evaluation
	//
	// json:
	//		a string literal of a JSON item, for instance:
	//			'{ "foo": [ "bar", 1, { "baz": "thud" } ] }'
	// schema: A JSON Schema object that can be used to advise the parsing of the JSON (defining ids, date properties, urls, etc)	//
	// 		Currently this provides a means for context based id handling
	//
	// return:
	//		An object, the result of the evaluation
	var root = eval('(' + str + ')'); // do the eval
	if (root){
		return this.resolveJson(root,schema);
	}
	return root;
}
dojox.rpc.toJson = function(/*Object*/ it, /*Boolean?*/ prettyPrint, /*Object?*/ schema){
	// summary:
	//		Create a JSON serialization of an object.
	//		This has support for referencing, including circular references, duplicate references, and out-of-message references
	// 		id and path-based referencing is supported as well and is based on http://www.json.com/2007/10/19/json-referencing-proposal-and-library/.
	//
	// it:
	//		an object to be serialized.
	//
	// prettyPrint:
	//		if true, we indent objects and arrays to make the output prettier.
	//		The variable dojo.toJsonIndentStr is used as the indent string
	//		-- to use something other than the default (tab),
	//		change that variable before calling dojo.toJson().
	//
	// schema: A JSON Schema object that can be used to advise the parsing of the JSON (defining ids, date properties, urls, etc)	//
	// 		Currently this provides a means for context based id handling
	//
	// return:
	//		a String representing the serialized version of the passed object.

	var idPrefix = (schema&& schema._idPrefix) || ''; // the id prefix for this context
	var paths={};
	function serialize(it,path,_indentStr){
		if (it && dojo.isObject(it)){
			var value;
			if (it instanceof Date){ // properly serialize dates
				return '"' + dojo.date.stamp.toISOString(it,{zulu:true}) + '"';
			}
			var id = it._id;
			if (id){ // we found an identifiable object, we will just serialize a reference to it... unless it is the root

				if (path != '$'){
					return serialize({$ref:id.charAt(0)=='$' ? id : // a pure path based reference, leave it alone
 									id.substring(0,idPrefix.length)==idPrefix ?  // see if the reference is in the current context
 										id.substring(idPrefix.length): // a reference with a prefix matching the current context, the prefix should be removed
	 										'../' + id});// a reference to a different context, assume relative url based referencing
				}
				path = id;
			}
			else {
				it._id = path; // we will create path ids for other objects in case they are circular
				paths[path] = it;// save it here so they can be deleted at the end
			}
			_indentStr = _indentStr || "";
			var nextIndent = prettyPrint ? _indentStr + dojo.toJsonIndentStr : "";
			var newLine = prettyPrint ? "\n" : "";
			var sep = prettyPrint ? " " : "";

			if (it instanceof Array){
				var res = dojo.map(it, function(obj,i){
					var val = serialize(obj, path + '[' + i + ']', nextIndent);
					if(!dojo.isString(val)){
						val = "undefined";
					}
					return newLine + nextIndent + val;
				});
				return "[" + res.join("," + sep) + newLine + _indentStr + "]";
			}

			var output = [];
			for(var i in it){
				var keyStr;
				if(typeof i == "number"){
					keyStr = '"' + i + '"';
				}else if(dojo.isString(i) && i != '_id'){
					keyStr = dojo._escapeString(i);
				}else{
					// skip non-string or number keys
					continue;
				}
				var val = serialize(it[i],path+(i.match(/^[a-zA-Z]\w*$/) ? // can we use simple .property syntax?
													('.' + i) : // yes, otherwise we have to escape it
													('[' + dojo._escapeString(i) + ']')),nextIndent);
				if(!dojo.isString(val)){
					// skip non-serializable values
					continue;
				}
				output.push(newLine + nextIndent + keyStr + ":" + sep + val);
			}
			return "{" + output.join("," + sep) + newLine + _indentStr + "}";
		}

		return dojo.toJson(it); // use the default serializer for primitives
	}
	var json = serialize(it,'$',''), i;
	for (i in paths){  // cleanup the temporary path-generated ids
		delete paths[i]._id;
	}
	return json;
}
<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

function Graph() {

	var that = this;
	this.canvas = document.getElementById('graph');
	this.ctx = this.canvas.getContext("2d");

	this.redraw = function() {
		var ctx = this.ctx;
		var w = this.canvas.width;
		var h = this.canvas.height;
		var start = this.start;
		var end = this.end;
		var step = this.step;
		ctx.fillStyle = "black";
		ctx.fillRect(0, 0, w, h);
		var top = 10;
		var bottom = h - 20;
		var left = 35;
		var right = w - 35;
		ctx.font = 'bold 12pt Courier';

		/**
		 * Draw columns
		 */
		var nrCol = 20;
		var diff = (right - left) / nrCol;
		ctx.strokeStyle = "yellow";
		var x = left;
		var i;
		for (i = 0; i <= nrCol; i++) {
			ctx.beginPath();
			ctx.moveTo(x, top);
			ctx.lineTo(x, bottom);
			ctx.stroke();
			x += diff;
		}

		/**
		 * Draw frequencies
		 */
		x = left - 25;
		var freq = start;
		nrCol = 10;
		var freqDiff = (end - start) / nrCol;
		diff = (right - left) / nrCol;
		for (i = 0; i <= nrCol; i++) {
			ctx.fillStyle = "white";
			ctx.fillText(freq.toFixed(0), x, h - 5);
			x += diff;
			freq += freqDiff;
		}

		/**
		 * Draw rows
		 */
		var nrRow = 20;
		diff = (bottom - top) / nrRow;
		var y = top;
		for (i = 0; i <= nrRow; i++) {
			ctx.beginPath();
			ctx.moveTo(left, y);
			ctx.lineTo(right, y);
			ctx.stroke();
			y += diff;
		}

		/**
		 * Draw SWR and R numbers
		 */
		y = bottom + 2;
		var swr = 1.0;
		var swrDiff = 5.0 / nrRow;
		var r = 0;
		var rDiff = 300 / nrRow;
		for (i = 0; i <= nrRow; i++) {
			ctx.fillStyle = "red";
			ctx.fillText(swr.toFixed(1), 2, y);
			ctx.fillStyle = "green";
			ctx.fillText(r.toFixed(0), right + 2, y);
			y -= diff;
			swr += swrDiff;
			r += rDiff;
		}

		/**
		 * Draw swr
		 */
		 var datapoints = this.data;
		 var p;
		 this.len = datapoints.length;
		 var nrSteps = (this.end - this.start) / this.step;
		 var xd = (right - left) / nrSteps;
		 ctx.beginPath();
		 x = left;
		 for (i = 0 ; i < len ; i++) {
			 dp = datapoints[i];
			 y = bottom - (bottom - top) * (dp.swr - 1) / 6.0
			 ctx.moveTo(x, y);
			 x += xd;
		 }
		 ctx.stroke();

	};

	Object.defineProperties(this, {
		"start": {
			get: function() {
				return this._start;
			},
			set: function(v) {
				this._start = v;
				this.redraw();
			}
		},
		"end": {
			get: function() {
				return this._end;
			},
			set: function(v) {
				this._end = v;
				this.redraw();
			}
		},
		"step": {
			get: function() {
				return this._step;
			},
			set: function(v) {
				this._step = v;
				this.redraw();
			}
		},
	});

	this.start = 13900;
	this.end = 14500;
	this.step = 5;
	this.data = [];

	this.startScan = function() {
		this.data = [];
		this.redraw();
	};

	this.endScan = function() {
		this.redraw();
	};

	this.update = function(dataPoint) {
		this.data.push(dataPoint);
		this.redraw();
	};

	window.onresize = function() {
		that.redraw();
	};

	setTimeout(function() {
		that.redraw();
	}, 2000);

}

function Open60App() {

	var that = this;

	Object.defineProperties(this, {
		"ready": {
			get: function() {
				return this._ready;
			},
			set: function(v) {
				this._ready = v;
			}
		},
		"connected": {
			get: function() {
				return this._connected;
			},
			set: function(v) {
				var b = document.getElementById("cmd-button");
				if (b) {
					var msg = v ? "disconnect" : "connect";
					b.textContent = msg;
				}
				this._connected = v;
			}
		},
		"start": {
			get: function() {
				return this._start;
			},
			set: function(v) {
				this._start = v;
				if (this.graph) this.graph.start = v;
			}
		},
		"end": {
			get: function() {
				return this._end;
			},
			set: function(v) {
				this._end = v;
				if (this.graph) this.graph.end = v;
			}
		},
		"step": {
			get: function() {
				return this._step;
			},
			set: function(v) {
				this._step = v;
				if (this.graph) this.graph.step = v;
			}
		},
	});

	this.ready = false;
	this.connected = false;
	this.start = 14000.0;
	this.end = 14350.0;
	this.step = 5;

	function trace(msg) {
		console.log(msg);
	}

	function alert(msg) {
		if (navigator.showToast) {
			navigator.showToast(msg);
		}
		console.log("alert: " + msg);
	}

	function error(msg) {
		console.log("error: " + msg);
		if (navigator.showToast) {
			navigator.showToast(msg);
		}
	}

	this.addGraph = function() {
		this.graph = new Graph(this.start, this.end, this.step);
	};

	this.checkConnect = function() {
		function success() {
			that.connected = true;
		}

		function failure() {
			that.connected = false;
		}
		bluetoothSerial.isConnected(success, failure);
	};

	this.connect = function(device) {
		function receive(data) {
			that.receive(data);
		}

		function subscribeFailure(msg) {
			error("subscribe: " + msg);
		}

		function connectSuccess() {
			that.connected = true;
			bluetoothSerial.subscribe('\n', receive, subscribeFailure);
			//bluetoothSerial.subscribeRawData(receive, subscribeFailure);
		}

		function connectFailure(msg) {
			that.connected = false;
			error("connect: " + msg);
		}
		bluetoothSerial.connect(device.address, connectSuccess, connectFailure);
	};

	this.disconnect = function() {
		function success() {
			that.connected = false;
		}

		function failure(msg) {
			that.connected = false;
		}
		if (that.connected) {
			bluetoothSerial.unsubscribe();
			bluetoothSerial.disconnect(success, failure);
		}
	};

	this.receive = function(data) {
		console.log(data);
		data = data.trim();
		if (data.startsWith('Start')) {
			this.graph.startScan();
		} else if (data.startsWith("End")) {
			this.graph.endScan();
		} else {
			var arr = data.split(',');
			if (arr.length === 4) {
				var dp = {
					swr: parseFloat(arr[0]),
					r: parseFloat(arr[1]),
					x: parseFloat(arr[2]),
					z: parseFloat(arr[3])
				};
				this.graph.update(dp);
			}
		}
	};

	this.send = function(msg) {
		if (!this.connected) {
			return;
		}

		function success() {
			trace("sent!");
		}

		function failure(msg) {
			error("send: " + msg);
		}
		bluetoothSerial.write(msg + '\r\n', success, failure);
	};

	this.findMini60AndConnect = function() {
		function success(devices) {
			var dev = devices.find(function(d) {
				var name = d.name;
				return name.startsWith("MINI60");
			});
			if (!dev) {
				error("Paired device 'MINI60' not found");
			}
			that.connect(dev);
		}

		function failure(msg) {
			error("cannot list paired devices");
		}
		bluetoothSerial.list(success, failure);
	};

	this.scan = function() {
		var start = this.start * 1000;
		var end = this.end * 1000;
		var step = this.step * 1000;
		var cmd = "scan " + start + " " + end + " " + step;
		this.send(cmd);
	};

	var toolbarComponent = {
		template: '
' +
			'<button id="cmd-button" class="cmd-button" v-on:click="toggleConnect()">connect</button>' +
			'start<input v-model="start">' +
			'end<input v-model="end">' +
			'step<input v-model="step">' +
			'<button class="cmd-button" v-on:click="scan()">scan</button>' +
			'
',
		data: function() {
			return {
				connected: that.connected,
				start: that.start,
				end: that.end,
				step: that.step,
			};
		},
		methods: {
			toggleConnect: function() {
				if (that.connected) {
					that.disconnect();
				} else {
					that.findMini60AndConnect();
				}
			},
			disconnect: function() {
				that.disconnect();
			},
			scan: function() {
				that.scan();
			}
		}
	};

	Vue.component('toolbar-component', toolbarComponent);

	this.refreshDevices = function() {
		function success(devices) {
			btData.devices = devices.slice(0);
		}

		function failure(msg) {
			console.log("bluetooth list error: " + msg);
		}

		if (typeof bluetoothSerial !== "undefined") {
			bluetoothSerial.list(success, failure);
		} else {
			btData.devices = [{
					name: "device1"
				},
				{
					name: "device2"
				},
				{
					name: "device3"
				}
			];
		}
	};

	function onDeviceReady() {
		that.ready = true;
	}

	if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
		document.addEventListener("deviceready", onDeviceReady, false);
	} else {
		onDeviceReady(); //this is a browser
	}

}

var open60app = new Open60App();

document.addEventListener("DOMContentLoaded", function() {
	open60app.addGraph();
	var app = new Vue({
		el: '#app',
		data: {}
	});
});
<commit_msg>fix startup bug<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

function Graph() {

	var that = this;
	this.canvas = document.getElementById('graph');
	this.ctx = this.canvas.getContext("2d");
	this.data = [];

	this.redraw = function() {
		var ctx = this.ctx;
		var w = this.canvas.width;
		var h = this.canvas.height;
		var start = this.start;
		var end = this.end;
		var step = this.step;
		ctx.fillStyle = "black";
		ctx.fillRect(0, 0, w, h);
		var top = 10;
		var bottom = h - 20;
		var left = 35;
		var right = w - 35;
		ctx.font = 'bold 12pt Courier';

		/**
		 * Draw columns
		 */
		var nrCol = 20;
		var diff = (right - left) / nrCol;
		ctx.strokeStyle = "yellow";
		var x = left;
		var i;
		for (i = 0; i <= nrCol; i++) {
			ctx.beginPath();
			ctx.moveTo(x, top);
			ctx.lineTo(x, bottom);
			ctx.stroke();
			x += diff;
		}

		/**
		 * Draw frequencies
		 */
		x = left - 25;
		var freq = start;
		nrCol = 10;
		var freqDiff = (end - start) / nrCol;
		diff = (right - left) / nrCol;
		for (i = 0; i <= nrCol; i++) {
			ctx.fillStyle = "white";
			ctx.fillText(freq.toFixed(0), x, h - 5);
			x += diff;
			freq += freqDiff;
		}

		/**
		 * Draw rows
		 */
		var nrRow = 20;
		diff = (bottom - top) / nrRow;
		var y = top;
		for (i = 0; i <= nrRow; i++) {
			ctx.beginPath();
			ctx.moveTo(left, y);
			ctx.lineTo(right, y);
			ctx.stroke();
			y += diff;
		}

		/**
		 * Draw SWR and R numbers
		 */
		y = bottom + 2;
		var swr = 1.0;
		var swrDiff = 5.0 / nrRow;
		var r = 0;
		var rDiff = 300 / nrRow;
		for (i = 0; i <= nrRow; i++) {
			ctx.fillStyle = "red";
			ctx.fillText(swr.toFixed(1), 2, y);
			ctx.fillStyle = "green";
			ctx.fillText(r.toFixed(0), right + 2, y);
			y -= diff;
			swr += swrDiff;
			r += rDiff;
		}

		/**
		 * Draw swr
		 */
		 var datapoints = this.data;
		 var p;
		 var len = datapoints.length;
		 var nrSteps = (this.end - this.start) / this.step;
		 var xd = (right - left) / nrSteps;
		 ctx.beginPath();
		 x = left;
		 for (i = 0 ; i < len ; i++) {
			 dp = datapoints[i];
			 y = bottom - (bottom - top) * (dp.swr - 1) / 6.0
			 ctx.moveTo(x, y);
			 x += xd;
		 }
		 ctx.stroke();

	};

	Object.defineProperties(this, {
		"start": {
			get: function() {
				return this._start;
			},
			set: function(v) {
				this._start = v;
				this.redraw();
			}
		},
		"end": {
			get: function() {
				return this._end;
			},
			set: function(v) {
				this._end = v;
				this.redraw();
			}
		},
		"step": {
			get: function() {
				return this._step;
			},
			set: function(v) {
				this._step = v;
				this.redraw();
			}
		},
	});

	this.start = 13900;
	this.end = 14500;
	this.step = 5;
	this.data = [];

	this.startScan = function() {
		this.data = [];
		this.redraw();
	};

	this.endScan = function() {
		this.redraw();
	};

	this.update = function(dataPoint) {
		this.data.push(dataPoint);
		this.redraw();
	};

	window.onresize = function() {
		that.redraw();
	};

	setTimeout(function() {
		that.redraw();
	}, 2000);

}

function Open60App() {

	var that = this;

	Object.defineProperties(this, {
		"ready": {
			get: function() {
				return this._ready;
			},
			set: function(v) {
				this._ready = v;
			}
		},
		"connected": {
			get: function() {
				return this._connected;
			},
			set: function(v) {
				var b = document.getElementById("cmd-button");
				if (b) {
					var msg = v ? "disconnect" : "connect";
					b.textContent = msg;
				}
				this._connected = v;
			}
		},
		"start": {
			get: function() {
				return this._start;
			},
			set: function(v) {
				this._start = v;
				if (this.graph) this.graph.start = v;
			}
		},
		"end": {
			get: function() {
				return this._end;
			},
			set: function(v) {
				this._end = v;
				if (this.graph) this.graph.end = v;
			}
		},
		"step": {
			get: function() {
				return this._step;
			},
			set: function(v) {
				this._step = v;
				if (this.graph) this.graph.step = v;
			}
		},
	});

	this.ready = false;
	this.connected = false;
	this.start = 14000.0;
	this.end = 14350.0;
	this.step = 5;

	function trace(msg) {
		console.log(msg);
	}

	function alert(msg) {
		if (navigator.showToast) {
			navigator.showToast(msg);
		}
		console.log("alert: " + msg);
	}

	function error(msg) {
		console.log("error: " + msg);
		if (navigator.showToast) {
			navigator.showToast(msg);
		}
	}

	this.addGraph = function() {
		this.graph = new Graph(this.start, this.end, this.step);
	};

	this.checkConnect = function() {
		function success() {
			that.connected = true;
		}

		function failure() {
			that.connected = false;
		}
		bluetoothSerial.isConnected(success, failure);
	};

	this.connect = function(device) {
		function receive(data) {
			that.receive(data);
		}

		function subscribeFailure(msg) {
			error("subscribe: " + msg);
		}

		function connectSuccess() {
			that.connected = true;
			bluetoothSerial.subscribe('\n', receive, subscribeFailure);
			//bluetoothSerial.subscribeRawData(receive, subscribeFailure);
		}

		function connectFailure(msg) {
			that.connected = false;
			error("connect: " + msg);
		}
		bluetoothSerial.connect(device.address, connectSuccess, connectFailure);
	};

	this.disconnect = function() {
		function success() {
			that.connected = false;
		}

		function failure(msg) {
			that.connected = false;
		}
		if (that.connected) {
			bluetoothSerial.unsubscribe();
			bluetoothSerial.disconnect(success, failure);
		}
	};

	this.receive = function(data) {
		console.log(data);
		data = data.trim();
		if (data.startsWith('Start')) {
			this.graph.startScan();
		} else if (data.startsWith("End")) {
			this.graph.endScan();
		} else {
			var arr = data.split(',');
			if (arr.length === 4) {
				var dp = {
					swr: parseFloat(arr[0]),
					r: parseFloat(arr[1]),
					x: parseFloat(arr[2]),
					z: parseFloat(arr[3])
				};
				this.graph.update(dp);
			}
		}
	};

	this.send = function(msg) {
		if (!this.connected) {
			return;
		}

		function success() {
			trace("sent!");
		}

		function failure(msg) {
			error("send: " + msg);
		}
		bluetoothSerial.write(msg + '\r\n', success, failure);
	};

	this.findMini60AndConnect = function() {
		function success(devices) {
			var dev = devices.find(function(d) {
				var name = d.name;
				return name.startsWith("MINI60");
			});
			if (!dev) {
				error("Paired device 'MINI60' not found");
			}
			that.connect(dev);
		}

		function failure(msg) {
			error("cannot list paired devices");
		}
		bluetoothSerial.list(success, failure);
	};

	this.scan = function() {
		var start = this.start * 1000;
		var end = this.end * 1000;
		var step = this.step * 1000;
		var cmd = "scan " + start + " " + end + " " + step;
		this.send(cmd);
	};

	var toolbarComponent = {
		template: '
' +
			'<button id="cmd-button" class="cmd-button" v-on:click="toggleConnect()">connect</button>' +
			'start<input v-model="start">' +
			'end<input v-model="end">' +
			'step<input v-model="step">' +
			'<button class="cmd-button" v-on:click="scan()">scan</button>' +
			'
',
		data: function() {
			return {
				connected: that.connected,
				start: that.start,
				end: that.end,
				step: that.step,
			};
		},
		methods: {
			toggleConnect: function() {
				if (that.connected) {
					that.disconnect();
				} else {
					that.findMini60AndConnect();
				}
			},
			disconnect: function() {
				that.disconnect();
			},
			scan: function() {
				that.scan();
			}
		}
	};

	Vue.component('toolbar-component', toolbarComponent);

	this.refreshDevices = function() {
		function success(devices) {
			btData.devices = devices.slice(0);
		}

		function failure(msg) {
			console.log("bluetooth list error: " + msg);
		}

		if (typeof bluetoothSerial !== "undefined") {
			bluetoothSerial.list(success, failure);
		} else {
			btData.devices = [{
					name: "device1"
				},
				{
					name: "device2"
				},
				{
					name: "device3"
				}
			];
		}
	};

	function onDeviceReady() {
		that.ready = true;
	}

	if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry|IEMobile)/)) {
		document.addEventListener("deviceready", onDeviceReady, false);
	} else {
		onDeviceReady(); //this is a browser
	}

}

var open60app = new Open60App();

document.addEventListener("DOMContentLoaded", function() {
	open60app.addGraph();
	var app = new Vue({
		el: '#app',
		data: {}
	});
});
<|endoftext|>


<commit_before>var app = {
  initialize: function () {
    this.bind();
  },
  bind: function () {
    document.addEventListener('deviceready', this.deviceready, false);
    document.addEventListener('resume', this.resume, false);
  },
<<<<<<< HEAD
  deviceready: function () {

    // See http://docs.phonegap.com/en/edge/cordova_notification_notification.md.html#Notification
    alert = navigator.notification.alert;
    prompt = navigator.notification.prompt;
    confirm = navigator.notification.confirm;

    // Begin listening for NFC Tags
    nfcRing.nfcEvent.init();

    if (device.platform == "Win32NT") {
      $('#read').hide();
      $('.win32').show(); // Note to Designer, by default this needs to be hidden
    }

    // Handle back events
    document.addEventListener("backbutton", nfcRing.ui.handleBack, false);

    FastClick.attach(document.body);

  },
  intentEvent: function() {
    // alert("Intent passed, handling that way");
    window.plugins.webintent.getExtra(window.plugins.webintent.EXTRA_TEXT, function(value) {
      if(!value) value = "http://nfcring.com/getStarted";

      // console.log("Intent value is ", value);
      nfcRing.userValues.activity = "write";
      nfcRing.userValues.toWrite = value;
      nfcRing.userValues.location = "writeRing";
      // nfcRing.userValues.intent = true;

      // If the first chars are http we should assume this is a URL
      // We need this functionality for intent events

      if(nfcRing.userValues.toWrite.substring(0,4) === "http"){
        nfcRing.userValues.isUrl = true;
        console.log("deciding it's a url");
      }

      nfcRing.heatmap.init();
      nfcRing.ui.displayPage("writeRing");
      nfcRing.ui.prepareWritePage("write");

    }, function(){
      console.log("ERROR XVMA123");
=======
  webintentListener: function () {
    if(typeof cordova !== 'undefined'){
      console.log("Checking for intent", webintent);
      webintent.hasExtra(webintent.EXTRA_TEXT,
        function(hasExtra) {
          if(hasExtra){
            console.log("Intent passed, handling that way");
            webintent.getExtra(webintent.EXTRA_TEXT, function(value) {
              if(!value) value = "http://nfcring.com/getStarted";
              console.log("Intent value is ", value);
              nfcRing.userValues.activity = "write";
              nfcRing.userValues.intentSet = true;
              nfcRing.userValues.toWrite = value;
              setTimeout(function(){
                nfcRing.heatmap.init();
                nfcRing.ui.displayPage("writeRing");
                nfcRing.ui.prepareWritePage("write");
              }, 500);
            }, function(){
              console.log("ERROR XVMA123");
            });
          }
        }, function() {
          console.log("ERROR XVMA172");
        }
      );
    }

    webintent.onNewIntent(function(intent, test) {
      console.log("new intent event detected", intent, test);
      webintent.hasExtra(webintent.EXTRA_TEXT, function(hasExtra) {
        if(hasExtra){
          console.log("Intent passed, handling that way");
        }
      });
    });

    //handle app invoke via activity
    window.plugins.webintent.getUri(function(invokeUrl) {
      console.log("[INTENT] handleAndroidOpen: " +  invokeUrl);
>>>>>>> b12dcbde699aa38cfe62bf20ccb5a316da76f07e
    });
  },
  resume: function () {
    console.log("Resuming");
    app.webintentListener();
  },

  deviceready: function () {

    // See http://docs.phonegap.com/en/edge/cordova_notification_notification.md.html#Notification
    alert = navigator.notification.alert;
    prompt = navigator.notification.prompt;
    confirm = navigator.notification.confirm;

    // Begin listening for NFC Tags
    nfcRing.nfcEvent.init();

    if (device.platform == "Win32NT") {
      $('#read').hide();
      $('.win32').show(); // Note to Designer, by default this needs to be hidden
    }

    // Handle back events
    document.addEventListener("backbutton", nfcRing.ui.handleBack, false);

    FastClick.attach(document.body);

    // Check to see if intent is available
    app.webintentListener();

  }
};

window.onerror = function(e,f,g){
   console.log("window.onerror ", e, f, g);
};
<commit_msg>rebase<commit_after>var app = {
  initialize: function () {
    this.bind();
  },
  bind: function () {
    document.addEventListener('deviceready', this.deviceready, false);
    document.addEventListener('resume', this.resume, false);
  },
  deviceready: function () {

    // See http://docs.phonegap.com/en/edge/cordova_notification_notification.md.html#Notification
    alert = navigator.notification.alert;
    prompt = navigator.notification.prompt;
    confirm = navigator.notification.confirm;

    // Begin listening for NFC Tags
    nfcRing.nfcEvent.init();

    if (device.platform == "Win32NT") {
      $('#read').hide();
      $('.win32').show(); // Note to Designer, by default this needs to be hidden
    }

    // Handle back events
    document.addEventListener("backbutton", nfcRing.ui.handleBack, false);

    FastClick.attach(document.body);

  }

  /*
  ,

  intentEvent: function() {
    // alert("Intent passed, handling that way");
    window.plugins.webintent.getExtra(window.plugins.webintent.EXTRA_TEXT, function(value) {
      if(!value) value = "http://nfcring.com/getStarted";

      // console.log("Intent value is ", value);
      nfcRing.userValues.activity = "write";
      nfcRing.userValues.toWrite = value;
      nfcRing.userValues.location = "writeRing";
      // nfcRing.userValues.intent = true;

      // If the first chars are http we should assume this is a URL
      // We need this functionality for intent events

      if(nfcRing.userValues.toWrite.substring(0,4) === "http"){
        nfcRing.userValues.isUrl = true;
        console.log("deciding it's a url");
      }

      nfcRing.heatmap.init();
      nfcRing.ui.displayPage("writeRing");
      nfcRing.ui.prepareWritePage("write");

    }, function(){
      console.log("ERROR XVMA123");
    });
  },

  webintentListener: function () {
    if(typeof cordova !== 'undefined'){
      console.log("Checking for intent", webintent);
      webintent.hasExtra(webintent.EXTRA_TEXT,
        function(hasExtra) {
          if(hasExtra){
            console.log("Intent passed, handling that way");
            webintent.getExtra(webintent.EXTRA_TEXT, function(value) {
              if(!value) value = "http://nfcring.com/getStarted";
              console.log("Intent value is ", value);
              nfcRing.userValues.activity = "write";
              nfcRing.userValues.intentSet = true;
              nfcRing.userValues.toWrite = value;
              setTimeout(function(){
                nfcRing.heatmap.init();
                nfcRing.ui.displayPage("writeRing");
                nfcRing.ui.prepareWritePage("write");
              }, 500);
            }, function(){
              console.log("ERROR XVMA123");
            });
          }
        }, function() {
          console.log("ERROR XVMA172");
        }
      );
    }

    webintent.onNewIntent(function(intent, test) {
      console.log("new intent event detected", intent, test);
      webintent.hasExtra(webintent.EXTRA_TEXT, function(hasExtra) {
        if(hasExtra){
          console.log("Intent passed, handling that way");
        }
      });
    });

    //handle app invoke via activity
    window.plugins.webintent.getUri(function(invokeUrl) {
      console.log("[INTENT] handleAndroidOpen: " +  invokeUrl);
    });
  },
  resume: function () {
    console.log("Resuming");
    app.webintentListener();
  }
  */

};

window.onerror = function(e,f,g){
   console.log("window.onerror ", e, f, g);
};
<|endoftext|>


<commit_before>/*
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

function tchange(){
	if(window.localStorage.getItem("name") !=null && window.localStorage.getItem("time")!=null){
		if(document.getElementById('inPls').innerHTML==='Let Me In'){
			document.getElementById('inPls').innerHTML='Cancel Karma';
			document.getElementById('check').innerHTML='Karma Recived';
			rR = true;
			requestKarma(function(data){

			});
		}else if(document.getElementById('inPls').innerHTML==='Cancel Karma'){
			document.getElementById('inPls').innerHTML='Let Me In';
			document.getElementById('check').innerHTML='Check In';
			rR = false;
			killKarma(function(data){

			});
		}else if(document.getElementById('inPls').innerHTML==='Answer Karma'){
			if(ul.firstChild != null){
				fillKarma( function(data){

			});
			}
		}
	}else{
		alert("Please set up username and time in the settings");
	}
}

function bchange(){
	if(window.localStorage.getItem("name") !=null && window.localStorage.getItem("time") !=null){
		if(document.getElementById('check').innerHTML==='Check In'){
			document.getElementById('check').innerHTML='Check Out';
			document.getElementById('inPls').innerHTML='Answer Karma';
			rG = true;
			readyKarma(function(data){

			});
		}else if(document.getElementById('check').innerHTML==='Check Out'){
			document.getElementById('check').innerHTML='Check In';
			document.getElementById('inPls').innerHTML='Let Me In';
			rG = false;
			unreadyKarma(function(data){

			});
		}else if(document.getElementById('check').innerHTML==='Karma Recived'){
			document.getElementById('inPls').innerHTML='Let Me In';
			document.getElementById('check').innerHTML='Check In';
			rR = false;
		}
	}else{
		alert("Please set up username and time in the settings");
	}
}

function mchange(){
	window.location="secondPage.html";
}
function pchange(){
	$("#navi").toggleClass("expanded-nav");
}

var tButton = document.getElementById('inPls');
if(tButton.addEventListener){
	tButton.addEventListener("click", tchange, false);
}else if(tButton.attachEvent){
	tButton.attachEvent('onclick', tchange);
}

var bButton = document.getElementById('check');
if(bButton.addEventListener){
	bButton.addEventListener("click", bchange, false);
}else if(tButton.attachEvent){
	bButton.attachEvent('onclick', bchange);
}

var mClick = document.getElementById("menu");
if(mClick.addEventListener){
	mClick.addEventListener("click", mchange, false);
}else if(mClick.attachEvent){
	mClick.attachEvent('onclick', mchange);
}

var pClick = document.getElementById("people");
if(pClick.addEventListener){
	pClick.addEventListener("click", pchange, false);
}else if(pClick.attachEvent){
	pClick.attachEvent('onclick', pchange);
}
var ul= document.getElementById("listPeople");
var rR = false;
var rG = false;
var myVar = setInterval(function(){myTimer()}, Math.abs(window.localStorage.getItem("time") * 1000));
function myTimer(){
	if(window.localStorage.getItem("changeTime")){
		stopTimer(myVar);
		window.localStorage.setItem("changeTime", false);
		myVar = setInterval(function(){myTimer()},Math.abs(window.localStorage.getItem("time")) * 1000);
	}
	if(rR){
		waitingPollKarma(function(data){
		console.log(data);
			if(JSON.parse(data).onTheWay)
			{
				alert("Someone is on the way!");
			}
		});
	}
	if(rG){
		userlistKarma(function(data){
		console.log(data);

		var people=JSON.parse(data).tickets;
		while(ul.firstChild)
		{
			ul.removeChild(ul.firstChild);
		}

		for(var key in people)
		{
			if(people.hasOwnProperty(key)) {
				var temp=document.createElement(people[key]);
				ul.appendChild(temp);
				temp.innerHTML=people[key];
			}
		}
		});
	}
}

var sysM = setInterval(function(){sysTimer()}, 60000);
function sysTimer(){
	messagePollKarma(function(data){
		console.log(data);
		console.log(JSON.parse(data).message);
		alert("System message: " + JSON.parse(data).message);
	});
}

function stopTimer(thing){
	clearInterval(thing);
}
<commit_msg>ui stuff<commit_after>/*
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
var app = {
    // Application Constructor
    initialize: function() {
        this.bindEvents();
    },
    // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicity call 'app.receivedEvent(...);'
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    // Update DOM on a Received Event
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');

        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');

        console.log('Received Event: ' + id);
    }
};

function tchange(){
	if(window.localStorage.getItem("name") !=null && window.localStorage.getItem("time")!=null){
		if(document.getElementById('inPls').innerHTML==='Let Me In'){
			document.getElementById('inPls').innerHTML='Cancel Karma';
			document.getElementById('check').innerHTML='Karma Recived';
			rR = true;
			requestKarma(function(data){

			});
		}else if(document.getElementById('inPls').innerHTML==='Cancel Karma'){
			document.getElementById('inPls').innerHTML='Let Me In';
			document.getElementById('check').innerHTML='Check In';
			rR = false;
			killKarma(function(data){

			});
		}else if(document.getElementById('inPls').innerHTML==='Answer Karma'){
			if(ul.firstChild != null){
				fillKarma( function(data){

			});
			}
		}
	}else{
		alert("Please set up username and time in the settings");
	}
}

function bchange(){
	if(window.localStorage.getItem("name") !=null && window.localStorage.getItem("time") !=null){
		if(document.getElementById('check').innerHTML==='Check In'){
			document.getElementById('check').innerHTML='Check Out';
			document.getElementById('inPls').innerHTML='Answer Karma';
			rG = true;
			readyKarma(function(data){

			});
		}else if(document.getElementById('check').innerHTML==='Check Out'){
			document.getElementById('check').innerHTML='Check In';
			document.getElementById('inPls').innerHTML='Let Me In';
			rG = false;
			unreadyKarma(function(data){

			});
		}else if(document.getElementById('check').innerHTML==='Karma Recived'){
			document.getElementById('inPls').innerHTML='Let Me In';
			document.getElementById('check').innerHTML='Check In';
			rR = false;
		}
	}else{
		alert("Please set up username and time in the settings");
	}
}

function mchange(){
	window.location="secondPage.html";
}
function pchange(){
	$("#navi").toggleClass("expanded-nav");
}

var tButton = document.getElementById('inPls');
if(tButton.addEventListener){
	tButton.addEventListener("click", tchange, false);
}else if(tButton.attachEvent){
	tButton.attachEvent('onclick', tchange);
}

var bButton = document.getElementById('check');
if(bButton.addEventListener){
	bButton.addEventListener("click", bchange, false);
}else if(tButton.attachEvent){
	bButton.attachEvent('onclick', bchange);
}

var mClick = document.getElementById("menu");
if(mClick.addEventListener){
	mClick.addEventListener("click", mchange, false);
}else if(mClick.attachEvent){
	mClick.attachEvent('onclick', mchange);
}

var pClick = document.getElementById("people");
if(pClick.addEventListener){
	pClick.addEventListener("click", pchange, false);
}else if(pClick.attachEvent){
	pClick.attachEvent('onclick', pchange);
}
var ul= document.getElementById("listPeople");
var rR = false;
var rG = false;
var myVar = setInterval(function(){myTimer()}, Math.abs(window.localStorage.getItem("time") * 1000));
function myTimer(){
	if(window.localStorage.getItem("changeTime")){
		stopTimer(myVar);
		window.localStorage.setItem("changeTime", false);
		myVar = setInterval(function(){myTimer()},Math.abs(window.localStorage.getItem("time")) * 1000);
	}
	if(rR){
		waitingPollKarma(function(data){
		console.log(data);
			if(JSON.parse(data).onTheWay)
			{
				alert("Someone is on the way!");
			}
		});

		userlistKarma(function(data){
		console.log(data);

		var people=JSON.parse(data).ready;
		while(ul.firstChild)
		{
			ul.removeChild(ul.firstChild);
		}

		for(var key in people)
		{
			if(people.hasOwnProperty(key)) {
				var temp=document.createElement(people[key]);
				temp.type = "li";
				ul.appendChild(temp);
				temp.innerHTML=people[key];
			}
		}
		});

	}
	if(rG){
		userlistKarma(function(data){
		console.log(data);

		var people=JSON.parse(data).tickets;
		while(ul.firstChild)
		{
			ul.removeChild(ul.firstChild);
		}

		for(var key in people)
		{
			if(people.hasOwnProperty(key)) {
				var temp=document.createElement(people[key]);
				temp.type = "li";
				ul.appendChild(temp);
				temp.innerHTML=people[key];
			}
		}
		});
	}
}

var sysM = setInterval(function(){sysTimer()}, 60000);
function sysTimer(){
	messagePollKarma(function(data){
		console.log(data);
		console.log(JSON.parse(data).message);
		alert("System message: " + JSON.parse(data).message);
	});
}

function stopTimer(thing){
	clearInterval(thing);
}
<|endoftext|>


<commit_before>var post = function(action, data){
  return new Promise(function(resolve, reject){

    console.log("About to make a post call - ");
    console.log(action);
    console.log(data);

    var request = $.post(action, data);

    request.done(function(serverData){
      resolve(serverData)
    });

    request.fail(function(serverData){
      reject(serverData)
    });
  });
}

var get = function(action, data){
  return new Promise(function(resolve, reject){

    console.log("About to make a get call - ");
    console.log(action);
    console.log(data);

    var request = $.get(action, data);

    request.done(function(serverData){
      resolve(serverData)
    });

    request.fail(function(serverData){
      reject(serverData)
    });
  });
}

var view = {
  goTo: function(contentId){
    $(":mobile-pagecontainer").pagecontainer("change", contentId);
  },
  errorMessage: function(errorTarget, message){
    $(errorTarget).text("There was an error signing in. " + message);
  },
  loginUser: function(){
    this.updatePersonalInfo();
    this.goTo('#cardsPage');
  },
  logoutUser: function(){
    this.goTo('#loginPage');
  },
  updatePersonalInfo: function(){
    $(".uidSpan").text(localStorage.getItem("uid"));
  }
}

var app = {
  initialize: function() {
    this.bindEvents();
  },
  bindEvents: function() {
    $("#loginForm").submit(this.submitLoginForm);
    $("#logoutLink").click(this.handleLogOut);
  },
  handleLogOut: function(){
    localStorage.removeItem("uid");
    localStorage.removeItem("utoken");
    view.logoutUser();
  },
  submitLoginForm: function(){
    var data = $("#loginForm").serialize();
    post('http://localhost:3000/api/v1/login', data)
      .then(function(serverData){
        localStorage.setItem("uid", serverData.id);
        localStorage.setItem("utoken", serverData.token);

        view.goTo('#cardsPage');
        view.loginUser();
      })
      .catch(function(serverData){
        view.errorMessage('#loginError', serverData.responseText);
      });

    return false;
  }
};<commit_msg>Make initial getObservations function - returns success<commit_after>var post = function(action, data){
  return new Promise(function(resolve, reject){

    console.log("About to make a post call - ");
    console.log(action);
    console.log(data);

    var request = $.post(action, data);

    request.done(function(serverData){
      resolve(serverData)
    });

    request.fail(function(serverData){
      reject(serverData)
    });
  });
}

var get = function(action, data){
  return new Promise(function(resolve, reject){

    console.log("About to make a get call - ");
    console.log(action);
    console.log(data);

    var request = $.get(action, data);

    request.done(function(serverData){
      resolve(serverData)
    });

    request.fail(function(serverData){
      reject(serverData)
    });
  });
}

var view = {
  goTo: function(contentId){
    $(":mobile-pagecontainer").pagecontainer("change", contentId);
  },
  errorMessage: function(errorTarget, message){
    $(errorTarget).text("There was an error signing in. " + message);
  },
  loginUser: function(){
    this.updatePersonalInfo();
    this.goTo('#cardsPage');
  },
  logoutUser: function(){
    this.goTo('#loginPage');
  },
  updatePersonalInfo: function(){
    $(".uidSpan").text(localStorage.getItem("uid"));
  }
}

var app = {
  initialize: function() {
    this.bindEvents();
  },
  bindEvents: function() {
    $("#loginForm").submit(this.submitLoginForm);
    $("#logoutLink").click(this.handleLogOut);
  },
  handleLogOut: function(){
    localStorage.removeItem("uid");
    localStorage.removeItem("utoken");
    view.logoutUser();
  },
  getObservations: function(user_id, authenticity_token){
    console.log('got to getObservations');
    console.log(user_id);
    console.log(authenticity_token);
    var data = "user_id=" + user_id + "&authenticity_token=" + authenticity_token;
    console.log(data);

    get('http://localhost:3000/api/v1/observations?' + data)
      .then(function(serverData){
        console.log('success');
      })
      .catch(function(serverData){
        console.log('error');
        console.log(serverData.responseText)
      });
  },
  submitLoginForm: function(){
    var data = $("#loginForm").serialize();
    post('http://localhost:3000/api/v1/login', data)
      .then(function(serverData){
        localStorage.setItem("uid", serverData.id);
        localStorage.setItem("utoken", serverData.token);

        app.getObservations(serverData.id, serverData.token);
        view.loginUser();
      })
      .catch(function(serverData){
        view.errorMessage('#loginError', serverData.responseText);
      });

    return false;
  }
};<|endoftext|>


<commit_before>jQuery(document).ready(function () {
    jQuery('#clickme').on('click', function () {
        jQuery('#display').text("Hello worldlings!");
    });
    var url = 'http://pjc.gear.host/api/Hello';
    $.ajax({
        type: 'GET',
        url: url,
        dataType: 'json',
        success: function (data, status) {
            $.each(data, function (key, item) {
                $('<li>', { text: formatItem(item) }).appendTo($('#records'));
            });
        },
        error: function () {
            //error loading data
        }
    });

    function formatItem(item) {
        return item.helloID + ":" + item.helloLanguage + ":" + item.helloMessage + ".";
    }
});<commit_msg>Change index js to getPage js<commit_after><|endoftext|>


<commit_before>var STACK = (function () {
    var obj = {};

    var _stack = [];
    var _nextStack = null;
    var _currentSlide = 0;

    var _stackTimer = null;
    var _rotateTimer = null;
    var _mouseMoveTimer = null;

    var _stackRequest = null;
    var _rotateRequest = null;

    var _mouseMoveCounter = 0;

    /*
     * Setup the stack display.
     */
    obj.start = function() {
        $stack.show();

        $('body').on('mousemove', onMoveMouse);
        $headerControls.hover(onControlsHover, offControlsHover);
        $audioPlayer.jPlayer('play');

        updateStack();
    }

    /*
     * Stop running the stack.
     */
    obj.stop = function() {
        if (_stackTimer) {
            clearTimeout(_stackTimer);
            _stackTimer = null;
        }

        if (_stackRequest) {
            _stackRequest.abort();
            _stackRequest = null;
        }

        if (_rotateTimer) {
            clearTimeout(_rotateTimer);
            _rotateTimer = null;
        }

        if (_rotateRequest) {
            _rotateRequest.abort();
            _rotateRequest = null;
        }

        if (_mouseMoveTimer) {
            clearTimeout(_mouseMoveTimer);
            _mouseMoveTimer = null;
        }

        $audioPlayer.jPlayer('pause');

        $stack.hide();
    }

    /*
     * Show the header.
     */
    var onMoveMouse = function() {
        _mouseMoveCounter += 1;

        if (!($('body').data('mouse-moving')) && _mouseMoveCounter > 20) {
            $header.fadeOut(200, function() {
                $headerControls.fadeIn(200);
            });

            $('body').data('mouse-moving', true);
            _mouseMoveCounter = 0;
        }

        if (_mouseMoveTimer) {
            clearTimeout(_mouseMoveTimer);
        }

        _mouseMoveTimer = setTimeout(onEndMouse, 500);
    }

    /*
     * Hide the header.
     */
    var onEndMouse = function() {
        _mouseMoveCounter = 0;

        if (!($headerControls.data('hover'))) {
            $('body').data('mouse-moving', false);
            $headerControls.fadeOut(200, function() {
                $header.fadeIn(200);
            });
        }
    }

    /*
     * Rotate to the next slide in the stack.
     */
    var rotateSlide = function() {
        _currentSlide += 1;

        if (_currentSlide >= _stack.length) {
            if (_nextStack.length > 0) {
                _stack = _nextStack;
                _nextStack = [];
            }

            _currentSlide = 0;
        }

        var slug = _stack[_currentSlide]['slug'];

        if (slug === 'state') {
            // If no state selected, skip to next
            if (!state) {
                rotateSlide();
                return;
            }

            slide_path = 'slides/state-' + state + '.html';
        } else {
            slide_path = 'slides/' + slug + '.html';
        }

        console.log('Rotating to next slide:', slide_path);

        _rotateRequest = $.ajax({
            url: APP_CONFIG.S3_BASE_URL + '/' + slide_path,
            success: function(data) {
                var $oldSlide = $stack.find('.slide');
                var $newSlide = $(data);

                if ($oldSlide.length > 0) {
                    $oldSlide.fadeOut(800, function() {
                        $(this).remove();
                        $stack.append($newSlide);
                        resizeSlide($newSlide)
                        if ($newSlide.find('.results-header').length > 0) {
                            $header.find('.leaderboard').fadeOut();
                        }
                        else {
                            $header.find('.leaderboard').fadeIn();
                        }

                        $newSlide.fadeIn(800, function(){
                            _rotateTimer = setTimeout(rotateSlide, APP_CONFIG.SLIDE_ROTATE_INTERVAL * 1000);
                        });
                    });
                }

                else {
                    $stack.append($newSlide);
                    resizeSlide($newSlide)
                    if ($newSlide.find('.results-header').length > 0) {
                        $header.find('.leaderboard').fadeOut();
                    }
                    else {
                        $header.find('.leaderboard').fadeIn();
                    }
                    $newSlide.fadeIn(800, function(){
                        _rotateTimer = setTimeout(rotateSlide, APP_CONFIG.SLIDE_ROTATE_INTERVAL * 1000);
                    });
                }
            }
        });
    }

    /*
     * Update the slide stack.
     */
    function updateStack() {
        _stackRequest = $.ajax({
            url: APP_CONFIG.S3_BASE_URL + '/live-data/stack.json',
            dataType: 'json',
            success: function(data) {
                _nextStack = data;

                if (!_rotateTimer) {
                    rotateSlide();
                }

                _stackTimer = setTimeout(updateStack, APP_CONFIG.STACK_UPDATE_INTERVAL * 1000);
            }
        });
    }

    return obj;
}());
<commit_msg>per Brian, don't wait to show the header controls<commit_after>var STACK = (function () {
    var obj = {};

    var _stack = [];
    var _nextStack = null;
    var _currentSlide = 0;

    var _stackTimer = null;
    var _rotateTimer = null;
    var _mouseMoveTimer = null;

    var _stackRequest = null;
    var _rotateRequest = null;

    /*
     * Setup the stack display.
     */
    obj.start = function() {
        $stack.show();

        $('body').on('mousemove', onMoveMouse);
        $headerControls.hover(onControlsHover, offControlsHover);
        $audioPlayer.jPlayer('play');

        updateStack();
    }

    /*
     * Stop running the stack.
     */
    obj.stop = function() {
        if (_stackTimer) {
            clearTimeout(_stackTimer);
            _stackTimer = null;
        }

        if (_stackRequest) {
            _stackRequest.abort();
            _stackRequest = null;
        }

        if (_rotateTimer) {
            clearTimeout(_rotateTimer);
            _rotateTimer = null;
        }

        if (_rotateRequest) {
            _rotateRequest.abort();
            _rotateRequest = null;
        }

        if (_mouseMoveTimer) {
            clearTimeout(_mouseMoveTimer);
            _mouseMoveTimer = null;
        }

        $audioPlayer.jPlayer('pause');

        $stack.hide();
    }

    /*
     * Show the header.
     */
    var onMoveMouse = function() {
        if (!($('body').data('mouse-moving'))) {
            $header.fadeOut(200, function() {
                $headerControls.fadeIn(200);
            });

            $('body').data('mouse-moving', true);
        }

        if (_mouseMoveTimer) {
            clearTimeout(_mouseMoveTimer);
        }

        _mouseMoveTimer = setTimeout(onEndMouse, 500);
    }

    /*
     * Hide the header.
     */
    var onEndMouse = function() {

        if (!($headerControls.data('hover'))) {
            $('body').data('mouse-moving', false);
            $headerControls.fadeOut(200, function() {
                $header.fadeIn(200);
            });
        }
    }

    /*
     * Rotate to the next slide in the stack.
     */
    var rotateSlide = function() {
        _currentSlide += 1;

        if (_currentSlide >= _stack.length) {
            if (_nextStack.length > 0) {
                _stack = _nextStack;
                _nextStack = [];
            }

            _currentSlide = 0;
        }

        var slug = _stack[_currentSlide]['slug'];

        if (slug === 'state') {
            // If no state selected, skip to next
            if (!state) {
                rotateSlide();
                return;
            }

            slide_path = 'slides/state-' + state + '.html';
        } else {
            slide_path = 'slides/' + slug + '.html';
        }

        console.log('Rotating to next slide:', slide_path);

        _rotateRequest = $.ajax({
            url: APP_CONFIG.S3_BASE_URL + '/' + slide_path,
            success: function(data) {
                var $oldSlide = $stack.find('.slide');
                var $newSlide = $(data);

                if ($oldSlide.length > 0) {
                    $oldSlide.fadeOut(800, function() {
                        $(this).remove();
                        $stack.append($newSlide);
                        resizeSlide($newSlide)
                        if ($newSlide.find('.results-header').length > 0) {
                            $header.find('.leaderboard').fadeOut();
                        }
                        else {
                            $header.find('.leaderboard').fadeIn();
                        }

                        $newSlide.fadeIn(800, function(){
                            _rotateTimer = setTimeout(rotateSlide, APP_CONFIG.SLIDE_ROTATE_INTERVAL * 1000);
                        });
                    });
                }

                else {
                    $stack.append($newSlide);
                    resizeSlide($newSlide)
                    if ($newSlide.find('.results-header').length > 0) {
                        $header.find('.leaderboard').fadeOut();
                    }
                    else {
                        $header.find('.leaderboard').fadeIn();
                    }
                    $newSlide.fadeIn(800, function(){
                        _rotateTimer = setTimeout(rotateSlide, APP_CONFIG.SLIDE_ROTATE_INTERVAL * 1000);
                    });
                }
            }
        });
    }

    /*
     * Update the slide stack.
     */
    function updateStack() {
        _stackRequest = $.ajax({
            url: APP_CONFIG.S3_BASE_URL + '/live-data/stack.json',
            dataType: 'json',
            success: function(data) {
                _nextStack = data;

                if (!_rotateTimer) {
                    rotateSlide();
                }

                _stackTimer = setTimeout(updateStack, APP_CONFIG.STACK_UPDATE_INTERVAL * 1000);
            }
        });
    }

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


<commit_before>jQuery(document).ready(function() {
    var uri = 'http://pjcdbrebuild.gear.host/api/';
    var loginToken = window.localStorage.getItem("token");
    var totalTasks = 0;
    var taskNames = [];
    var taskDescriptions = [];
    var expectedDurations = [];
    var routineList = JSON.parse(localStorage.getItem('routineList'));
    var jobTitle = localStorage.getItem('jobName');
    var parentOrCoach = "";
    var now = [];
    var jobStartTime = formatCurrentDateTime();
    var jobNotesArray;
    var taskNotesArray;
    var completedTasks = 0;
    var reminderArray = ["blah blah blah blah","Tahtahtahtahthaothatata","This chicken is good!!","Esdfasdfasfasfsafs"];
    document.getElementById("routineName").innerHTML = jobTitle;
    $.each(routineList, function (key, item) {
        if (item.routineTitle === jobTitle) {
            console.log(item);
            totalTasks = item.Tasks.length;
            for (var i = 0; i < totalTasks; i++) {
                taskNames[i] = item.Tasks[i].taskName
                taskDescriptions[i] = item.Tasks[i].taskDescription;
                expectedDurations[i] = item.Tasks[i].expectedDuration;
                parentOrCoach = item.creatorUserName;
            }
        }
    });

    for (var i = 0; i < totalTasks; i++) {
         $("
" +
				"
" + taskNames[i] + "
" +
				"Finish Task" +
                "
" +
                    "
" +
						"Task Time	" +
						"00:00:00	" +
					"
" +
					"
" +
						"Estimated Time	" +
						"" + expectedDurations[i] + "	" +
					"
" +
				"
" +
                "
" +
				"
" +
					"
Description
" +
					"

" + taskDescriptions[i] + "

" +
					"

" +
                "
" +
			    "Make Note" +
			"
").appendTo($("#tasksList"));

            $('.finishTask').css('border-color', '#1d873b');
			$('.finishTask').css('background-color', '#1de27c');
            $('.finishTask').css('border-width', '3px');

            if (i == 0) {
                $('.individualTask').attr('data-collapsed', 'false');
            } else {

            }
            $('#tasksList').collapsibleset('refresh');
    }
    document.getElementById("progress").innerHTML = "Overall Progress - " + completedTasks + "/" + totalTasks;

    $(".finishTask:not(:first)").prop("disabled", true);
    $("h3:not(:first)").addClass("avoid-clicks");

$(function(){
	$( "#progressbar" ).progressbar({
		value: 0
	});
});

//This function handles
jQuery('#final-yes').on('click', function() {
    if(completedTasks < totalTasks){
		resetTaskTimer();
		keepAliveTwo(loginToken);
		var progressbar = $( "#progressbar" );
		var total = progressbar.progressbar("value");
		progressbar.progressbar("value", total + (100 / totalTasks));
        $(this).prop('disabled', true);
        $('#task' + completedTasks).collapsible({collapsed: true}).addClass("avoid-clicks");
       // $(this).parents(':eq(0)').siblings("h3").addClass("avoid-clicks");
       // $('#task'+ completedTasks).addClass("avoid-clicks");
		completedTasks++;
        $('#task' + completedTasks).collapsible({collapsed: false});
        $('.finishTask').each(function(index) {
             if (completedTasks === index) {

                 $(this).parents(':eq(0)').siblings().removeClass("avoid-clicks");
                $(this).prop('disabled', false);

             }
        });
        document.getElementById("progress").innerHTML = "Overall Progress - " + completedTasks + "/" + totalTasks;

        if(expectedDurations[completedTasks] != null){
        	document.getElementById("expectedDuration" + completedTasks).innerHTML = expectedDurations[completedTasks];
        }
        else{
            if (completedTasks != totalTasks) {
                document.getElementById("expectedDuration" + completedTasks).innerHTML = "00:00:00";
            }
        }

		if(completedTasks == totalTasks){
			document.getElementById("progress").innerHTML += " - Completed";
            clearInterval(overallTimer);
		    clearInterval(partialTimer);
            $("
" +
                "Congratulations!" +
                "
You've finished the job! You did very well! Good job! Please click on the button below to go back to the home screen!
" +
                "Complete Job" +
            "
").insertAfter('#tasksList');
		}
	}
    keepAliveTwo(loginToken);
    $( "#finalVerification" ).popup("close");
});

    $(".finishTask").on('click',function(){
        console.log(completedTasks);
        $("#reminder").text(reminderArray[completedTasks]);
    });

    // When a user clicks "No" on a reminder popup it i will disable the final verification pop up from showing up.
    $("#reminder-no").on('click',function(){
        $( "#finalVerification" ).popup( "option", "disabled", true );
    });

    // Whe a user clicks "yes" on a reminder popup it will enable the final popup.
    $("#reminder-yes").on('click',function(){
        $( "#finalVerification" ).popup( "option", "disabled", false );
        $("#verification").popup("close");

    });

    // This causes the final verification popup to show af
    $( "#verification" ).on({
        popupafterclose: function() {
            setTimeout(function() { $( "#finalVerification" ).popup( "open" ) }, 100 );
        }
    });

jQuery('.make-note').on('click', function() {
    var self = jQuery(this);
    document.getElementById("stepNumber").value = self.closest('.ui-collapsible').attr('stepnumber');
});

//post job data
jQuery('[data-role="main"]').on('click', 'a#completeJob', function() {

      var job = {
        'creatorUsername':parentOrCoach,
        'routineTitle':jobTitle,
        'startTime':jobStartTime,
        'stepEndTimes':[],
        'jobNotes':[],
        'stepNotes':[]};

      for (var i = 0; i < totalTasks; i++) {
          job.stepEndTimes.push(now[i]);
      }

      jobNotesArray = JSON.parse(localStorage.getItem('jobNotesArray'+jobTitle));
      taskNotesArray = JSON.parse(localStorage.getItem('taskNotesArray'));

      $.each(jobNotesArray, function (key, item) {
          job.jobNotes.push({"noteTitle":item.name, "noteMessage":item.note});
      });

      $.each(taskNotesArray, function (key, item) {
          var stepNumber = item.stepNumber;
          job.stepNotes.push({"stepNo":stepNumber, "note":{"noteTitle":item.name, "noteMessage":item.note}});
      });

      $.ajax({
        type: 'POST',
        dataType: 'json',
        data: job,
        url: uri + "Job?token=" + loginToken,
        success: function(data){
          window.location.href = "splash.html";
        },
        error: function(){
          alert("failure posting job");
          console.log("Failure posting job");
          window.location.href = "splash.html";
        }
      });
      window.localStorage.removeItem("jobNotesArray"+jobTitle);
      window.localStorage.removeItem("taskNotesArray");
      job = {};
});

var overallTimer = setInterval(jobTimer, 1000);
var seconds = 0;
var minutes = 0;
var hours = 0;
function jobTimer(){
	seconds++;
	if(seconds == 60){
		minutes++;
		seconds = 0;
	}
	if(minutes == 60){
		hours++;
		minutes = 0;
	}
    document.getElementById("overallTime").innerHTML = "Overall Time - " + pad(hours) + ":" + pad(minutes) + ":" + pad(seconds);
}

var partialTimer = setInterval(taskTimer, 1000);
var tSeconds = 0;
var tMinutes = 0;
var tHours = 0;
function taskTimer(index){
	tSeconds++;
	if(tSeconds == 60){
		tMinutes++;
		tSeconds = 0;
	}
	if(tMinutes == 60){
		tHours++;
		tMinutes = 0;
	}
    document.getElementById("taskTime" + completedTasks).innerHTML = pad(tHours) + ":" + pad(tMinutes) + ":" + pad(tSeconds);
}
function resetTaskTimer(index){
    document.getElementById("taskTime" + completedTasks).innerHTML = pad(tHours) + ":" + pad(tMinutes) + ":" + pad(tSeconds);

    now[completedTasks] = formatCurrentDateTime();
    tSeconds = 0;
	tMinutes = 0;
	tHours = 0;
}

function formatCurrentDateTime(){
    var currDate = new Date();
    var h = addZero(currDate.getHours());
    var m = addZero(currDate.getMinutes());
    var s = addZero(currDate.getSeconds());
    var currdate = currDate.getFullYear() + '-' + addZero(currDate.getMonth() + 1) + '-' + addZero(currDate.getDate());
    return currdate + " " + h + ":" + m + ":" + s;
}

function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

function pad(number){
	if(number < 10){
		return "0" + number;
	}
	return number;
}

setTimeout(function() {
    keepAliveTwo(loginToken);
}, 500);
});<commit_msg>Made messages for dummy Array<commit_after>jQuery(document).ready(function() {
    var uri = 'http://pjcdbrebuild.gear.host/api/';
    var loginToken = window.localStorage.getItem("token");
    var totalTasks = 0;
    var taskNames = [];
    var taskDescriptions = [];
    var expectedDurations = [];
    var routineList = JSON.parse(localStorage.getItem('routineList'));
    var jobTitle = localStorage.getItem('jobName');
    var parentOrCoach = "";
    var now = [];
    var jobStartTime = formatCurrentDateTime();
    var jobNotesArray;
    var taskNotesArray;
    var completedTasks = 0;
    var reminderArray = ["Did you shake their hand?","Are there streaks on the mirror?","Are there any spots on the floor",
        "Are there any marks?", "Is it full?", "Did you order the pizza?"];
    document.getElementById("routineName").innerHTML = jobTitle;
    $.each(routineList, function (key, item) {
        if (item.routineTitle === jobTitle) {
            console.log(item);
            totalTasks = item.Tasks.length;
            for (var i = 0; i < totalTasks; i++) {
                taskNames[i] = item.Tasks[i].taskName
                taskDescriptions[i] = item.Tasks[i].taskDescription;
                expectedDurations[i] = item.Tasks[i].expectedDuration;
                parentOrCoach = item.creatorUserName;
            }
        }
    });

    for (var i = 0; i < totalTasks; i++) {
         $("
" +
				"
" + taskNames[i] + "
" +
				"Finish Task" +
                "
" +
                    "
" +
						"Task Time	" +
						"00:00:00	" +
					"
" +
					"
" +
						"Estimated Time	" +
						"" + expectedDurations[i] + "	" +
					"
" +
				"
" +
                "
" +
				"
" +
					"
Description
" +
					"

" + taskDescriptions[i] + "

" +
					"

" +
                "
" +
			    "Make Note" +
			"
").appendTo($("#tasksList"));

            $('.finishTask').css('border-color', '#1d873b');
			$('.finishTask').css('background-color', '#1de27c');
            $('.finishTask').css('border-width', '3px');

            if (i == 0) {
                $('.individualTask').attr('data-collapsed', 'false');
            } else {

            }
            $('#tasksList').collapsibleset('refresh');
    }
    document.getElementById("progress").innerHTML = "Overall Progress - " + completedTasks + "/" + totalTasks;

    $(".finishTask:not(:first)").prop("disabled", true);
    $("h3:not(:first)").addClass("avoid-clicks");

$(function(){
	$( "#progressbar" ).progressbar({
		value: 0
	});
});

//This function handles
jQuery('#final-yes').on('click', function() {
    if(completedTasks < totalTasks){
		resetTaskTimer();
		keepAliveTwo(loginToken);
		var progressbar = $( "#progressbar" );
		var total = progressbar.progressbar("value");
		progressbar.progressbar("value", total + (100 / totalTasks));
        $(this).prop('disabled', true);
        $('#task' + completedTasks).collapsible({collapsed: true}).addClass("avoid-clicks");
       // $(this).parents(':eq(0)').siblings("h3").addClass("avoid-clicks");
       // $('#task'+ completedTasks).addClass("avoid-clicks");
		completedTasks++;
        $('#task' + completedTasks).collapsible({collapsed: false});
        $('.finishTask').each(function(index) {
             if (completedTasks === index) {

                 $(this).parents(':eq(0)').siblings().removeClass("avoid-clicks");
                $(this).prop('disabled', false);

             }
        });
        document.getElementById("progress").innerHTML = "Overall Progress - " + completedTasks + "/" + totalTasks;

        if(expectedDurations[completedTasks] != null){
        	document.getElementById("expectedDuration" + completedTasks).innerHTML = expectedDurations[completedTasks];
        }
        else{
            if (completedTasks != totalTasks) {
                document.getElementById("expectedDuration" + completedTasks).innerHTML = "00:00:00";
            }
        }

		if(completedTasks == totalTasks){
			document.getElementById("progress").innerHTML += " - Completed";
            clearInterval(overallTimer);
		    clearInterval(partialTimer);
            $("
" +
                "Congratulations!" +
                "
You've finished the job! You did very well! Good job! Please click on the button below to go back to the home screen!
" +
                "Complete Job" +
            "
").insertAfter('#tasksList');
		}
	}
    keepAliveTwo(loginToken);
    $( "#finalVerification" ).popup("close");
});

    $(".finishTask").on('click',function(){
        console.log(completedTasks);
        $("#reminder").text(reminderArray[completedTasks]);
    });

    // When a user clicks "No" on a reminder popup it i will disable the final verification pop up from showing up.
    $("#reminder-no").on('click',function(){
        $( "#finalVerification" ).popup( "option", "disabled", true );
    });

    // Whe a user clicks "yes" on a reminder popup it will enable the final popup.
    $("#reminder-yes").on('click',function(){
        $( "#finalVerification" ).popup( "option", "disabled", false );
        $("#verification").popup("close");

    });

    // This causes the final verification popup to show af
    $( "#verification" ).on({
        popupafterclose: function() {
            setTimeout(function() { $( "#finalVerification" ).popup( "open" ) }, 100 );
        }
    });

jQuery('.make-note').on('click', function() {
    var self = jQuery(this);
    document.getElementById("stepNumber").value = self.closest('.ui-collapsible').attr('stepnumber');
});

//post job data
jQuery('[data-role="main"]').on('click', 'a#completeJob', function() {

      var job = {
        'creatorUsername':parentOrCoach,
        'routineTitle':jobTitle,
        'startTime':jobStartTime,
        'stepEndTimes':[],
        'jobNotes':[],
        'stepNotes':[]};

      for (var i = 0; i < totalTasks; i++) {
          job.stepEndTimes.push(now[i]);
      }

      jobNotesArray = JSON.parse(localStorage.getItem('jobNotesArray'+jobTitle));
      taskNotesArray = JSON.parse(localStorage.getItem('taskNotesArray'));

      $.each(jobNotesArray, function (key, item) {
          job.jobNotes.push({"noteTitle":item.name, "noteMessage":item.note});
      });

      $.each(taskNotesArray, function (key, item) {
          var stepNumber = item.stepNumber;
          job.stepNotes.push({"stepNo":stepNumber, "note":{"noteTitle":item.name, "noteMessage":item.note}});
      });

      $.ajax({
        type: 'POST',
        dataType: 'json',
        data: job,
        url: uri + "Job?token=" + loginToken,
        success: function(data){
          window.location.href = "splash.html";
        },
        error: function(){
          alert("failure posting job");
          console.log("Failure posting job");
          window.location.href = "splash.html";
        }
      });
      window.localStorage.removeItem("jobNotesArray"+jobTitle);
      window.localStorage.removeItem("taskNotesArray");
      job = {};
});

var overallTimer = setInterval(jobTimer, 1000);
var seconds = 0;
var minutes = 0;
var hours = 0;
function jobTimer(){
	seconds++;
	if(seconds == 60){
		minutes++;
		seconds = 0;
	}
	if(minutes == 60){
		hours++;
		minutes = 0;
	}
    document.getElementById("overallTime").innerHTML = "Overall Time - " + pad(hours) + ":" + pad(minutes) + ":" + pad(seconds);
}

var partialTimer = setInterval(taskTimer, 1000);
var tSeconds = 0;
var tMinutes = 0;
var tHours = 0;
function taskTimer(index){
	tSeconds++;
	if(tSeconds == 60){
		tMinutes++;
		tSeconds = 0;
	}
	if(tMinutes == 60){
		tHours++;
		tMinutes = 0;
	}
    document.getElementById("taskTime" + completedTasks).innerHTML = pad(tHours) + ":" + pad(tMinutes) + ":" + pad(tSeconds);
}
function resetTaskTimer(index){
    document.getElementById("taskTime" + completedTasks).innerHTML = pad(tHours) + ":" + pad(tMinutes) + ":" + pad(tSeconds);

    now[completedTasks] = formatCurrentDateTime();
    tSeconds = 0;
	tMinutes = 0;
	tHours = 0;
}

function formatCurrentDateTime(){
    var currDate = new Date();
    var h = addZero(currDate.getHours());
    var m = addZero(currDate.getMinutes());
    var s = addZero(currDate.getSeconds());
    var currdate = currDate.getFullYear() + '-' + addZero(currDate.getMonth() + 1) + '-' + addZero(currDate.getDate());
    return currdate + " " + h + ":" + m + ":" + s;
}

function addZero(i) {
    if (i < 10) {
        i = "0" + i;
    }
    return i;
}

function pad(number){
	if(number < 10){
		return "0" + number;
	}
	return number;
}

setTimeout(function() {
    keepAliveTwo(loginToken);
}, 500);
});<|endoftext|>