<commit_before>/*jshint node: true, -W106 */
'use strict';

/*
* Name : index.js
* Module : SystemTest
* Location : /SystemTest
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-06-27   Filippo Rampado    Initial code
* =========================================================
*/
var Helper=require('./helper.js');

console.log('Hello Norris');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);

// Includo e creo l'ustanza di Norris
var Norris = require('../norris-nrti.js');
var norris = new Norris(app,io,'/norris','http://norris-nrti-dev.herokuapp.com');

var page1=Helper.newPage(norris, 'page1', 'Pagina creazione grafici');
var page2=Helper.newPage(norris, 'page2', 'Pagina aggiornamento grafici');

//var barChart=Helper.newBarChart(page2, 'Test aggiornamento dati Bar Chart');
//var lineChart=Helper.newLineChart(page2, 'Test aggiornamento dati Line Chart');
var mapChart=Helper.newMapChart(page2, 'Test aggiornamento dati Map Chart');
//var table=Helper.newTable(page2, 'Test aggiornamento dati Table');

var TS1 = require('./TS1.js');
var TS2 = require('./TS2.js');
var TS3 = require('./TS3.js');
var TS4 = require('./TS4.js');
var TS5 = require('./TS5.js');
var TS6 = require('./TS6.js');
var TS7 = require('./TS7.js');
var TS8 = require('./TS8.js');
var TS9 = require('./TS9.js');

/*TS1(norris);
TS2(page1);
TS3(page1);
TS4(page1);
TS5(page1);
TS6(barChart);
TS7(lineChart);*/
TS8(mapChart);
//TS9(table);

/////////////////////////////////////////////
app.get('/', function (req, res) {
	var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
	console.log(' Test di sistema '+ fullUrl);
	res.send(' Test di sistema '+ fullUrl);
});

var port = process.env.PORT || 3000;
server.listen(port);<commit_msg>enable all test<commit_after>/*jshint node: true, -W106 */
'use strict';

/*
* Name : index.js
* Module : SystemTest
* Location : /SystemTest
*
* History :
*
* Version   Date         Programmer         Description
* =========================================================
* 0.0.1     2015-06-27   Filippo Rampado    Initial code
* =========================================================
*/
var Helper=require('./helper.js');

console.log('Hello Norris');

var express = require('express');
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io')(server);

// Includo e creo l'ustanza di Norris
var Norris = require('../norris-nrti.js');
var norris = new Norris(app,io,'/norris','http://norris-nrti-dev.herokuapp.com');

var page1=Helper.newPage(norris, 'page1', 'Pagina creazione grafici');
var page2=Helper.newPage(norris, 'page2', 'Pagina aggiornamento grafici');

var barChart=Helper.newBarChart(page2, 'Test aggiornamento dati Bar Chart');
var lineChart=Helper.newLineChart(page2, 'Test aggiornamento dati Line Chart');
var mapChart=Helper.newMapChart(page2, 'Test aggiornamento dati Map Chart');
var table=Helper.newTable(page2, 'Test aggiornamento dati Table');

var TS1 = require('./TS1.js');
var TS2 = require('./TS2.js');
var TS3 = require('./TS3.js');
var TS4 = require('./TS4.js');
var TS5 = require('./TS5.js');
var TS6 = require('./TS6.js');
var TS7 = require('./TS7.js');
var TS8 = require('./TS8.js');
var TS9 = require('./TS9.js');

TS1(norris);
TS2(page1);
TS3(page1);
TS4(page1);
TS5(page1);
TS6(barChart);
TS7(lineChart);
TS8(mapChart);
TS9(table);

/////////////////////////////////////////////
app.get('/', function (req, res) {
	var fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
	console.log(' Test di sistema '+ fullUrl);
	res.send(' Test di sistema '+ fullUrl);
});

var port = process.env.PORT || 3000;
server.listen(port);<|endoftext|>


<commit_before>/*jslint browser:true devel:true*/
/*global self, Promise, resolve*/

var queueLength = 0;

function upload(data) {
    "use strict";
    var xhr = new XMLHttpRequest();
    while (xhr.status !== 200) {
        xhr = new XMLHttpRequest();
        xhr.open("POST", "/api/v1/faset", false);
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.timeout = 5000;
        try {
            xhr.send(data);
        } catch (ignore) {

        }
    }
    self.postMessage("");
}

self.addEventListener('message', function (e) {
    'use strict';
    queueLength += 1;
    self.postMessage("Some submissions are being uploaded.");
    upload(e.data);
}, false);
<commit_msg>Improved error handling for permanent errors<commit_after>/*jslint browser:true devel:true*/
/*global self, Promise, resolve*/

var queueLength = 0;

function upload(data) {
    "use strict";
    var xhr = new XMLHttpRequest();
    while (xhr.status !== 200) {
        xhr = new XMLHttpRequest();
        xhr.open("POST", "/api/v1/faset", false);
        xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
        xhr.timeout = 5000;
        try {
            xhr.send(data);
            if (xhr.status >= 400) {
                self.postMessage("There was a permanent error uploading a response.")
                return;
            }
        } catch (e) {
            self.postMessage("There was a temporary error uploading a response. Retrying...");
        }
    }
    self.postMessage("");
}

self.addEventListener('message', function (e) {
    'use strict';
    queueLength += 1;
    self.postMessage("Some submissions are being uploaded.");
    upload(e.data);
}, false);
<|endoftext|>


<commit_before>/*
    ***** BEGIN LICENSE BLOCK *****

    Copyright © 2009 Center for History and New Media
                     George Mason University, Fairfax, Virginia, USA
                     http://zotero.org

    This file is part of Zotero.

    Zotero is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Zotero is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Zotero.  If not, see <http://www.gnu.org/licenses/>.

    ***** END LICENSE BLOCK *****
*/

Zotero.Connector_Debug = new function() {
	/**
	 * Call a callback depending upon whether debug output is being stored
	 */
	this.storing = function(callback) {
		callback(Zotero.Debug.storing);
	}

	/**
	 * Call a callback with the lines themselves
	 */
	this.get = function(callback) {
		callback(Zotero.Debug.get());
	}

	/**
	 * Call a callback with the number of lines of output
	 */
	this.count = function(callback) {
		callback(Zotero.Debug.count());
	}

	/**
	 * Submit data to the sserver
	 */
	this.submitReport = function(callback) {
		var uploadCallback = function (xmlhttp) {
			var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
									.getService(Components.interfaces.nsIPromptService);

			if (!xmlhttp.responseXML) {
				callback(false, 'Invalid response from server');
				return;
			}
			var reported = xmlhttp.responseXML.getElementsByTagName('reported');
			if (reported.length != 1) {
				callback(false, 'The server returned an error. Please try again.');
				return;
			}

			var reportID = reported[0].getAttribute('reportID');
			callback(true, reportID);
		}

		Zotero.HTTP.doPost("http://www.zotero.org/repo/report?debug=1", output,
			function(xmlhttp) {
				if (!xmlhttp.responseXML) {
					callback(false, 'Invalid response from server');
					return;
				}
				var reported = xmlhttp.responseXML.getElementsByTagName('reported');
				if (reported.length != 1) {
					callback(false, 'The server returned an error. Please try again.');
					return;
				}

				var reportID = reported[0].getAttribute('reportID');
				callback(true, reportID);
			}, {"Content-Type":"application/octet-stream"});
	}
}<commit_msg>Fix error<commit_after>/*
    ***** BEGIN LICENSE BLOCK *****

    Copyright © 2009 Center for History and New Media
                     George Mason University, Fairfax, Virginia, USA
                     http://zotero.org

    This file is part of Zotero.

    Zotero is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Zotero is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with Zotero.  If not, see <http://www.gnu.org/licenses/>.

    ***** END LICENSE BLOCK *****
*/

Zotero.Connector_Debug = new function() {
	/**
	 * Call a callback depending upon whether debug output is being stored
	 */
	this.storing = function(callback) {
		callback(Zotero.Debug.storing);
	}

	/**
	 * Call a callback with the lines themselves
	 */
	this.get = function(callback) {
		callback(Zotero.Debug.get());
	}

	/**
	 * Call a callback with the number of lines of output
	 */
	this.count = function(callback) {
		callback(Zotero.Debug.count());
	}

	/**
	 * Submit data to the sserver
	 */
	this.submitReport = function(callback) {
		var uploadCallback = function (xmlhttp) {
			var ps = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
									.getService(Components.interfaces.nsIPromptService);

			if (!xmlhttp.responseXML) {
				callback(false, 'Invalid response from server');
				return;
			}
			var reported = xmlhttp.responseXML.getElementsByTagName('reported');
			if (reported.length != 1) {
				callback(false, 'The server returned an error. Please try again.');
				return;
			}

			var reportID = reported[0].getAttribute('reportID');
			callback(true, reportID);
		}

		Zotero.HTTP.doPost("http://www.zotero.org/repo/report?debug=1", Zotero.Debug.get(),
			function(xmlhttp) {
				if (!xmlhttp.responseXML) {
					callback(false, 'Invalid response from server');
					return;
				}
				var reported = xmlhttp.responseXML.getElementsByTagName('reported');
				if (reported.length != 1) {
					callback(false, 'The server returned an error. Please try again.');
					return;
				}

				var reportID = reported[0].getAttribute('reportID');
				callback(true, reportID);
			}, {"Content-Type":"application/octet-stream"});
	}
}<|endoftext|>


<commit_before>
// Call this function when the page loads (the "ready" event)
$(document).ready(function() {

	$('#submit-btn').click(loginFunction);
	$('#btn-back').click(cancelFunction);
	$('.btn-register').click(goToSignUp);
	$('#makeact-btn').click(signupFunction);
	$('#btn-cancel').click(cancelFunction);
	$('#btn-add').click(addMilestoneFunction);
	$('#btn-menu').click(menuFunction);
	$('#btn-back-homescreen').click(cancelFunction);
	$('.logout').click(logOutFunction);
	$('#add-goal').click(addGoalFunction);
	$('#submit-milestone-btn').click(addMilestonePost);
	//$('#submit-btn').click(cancelFunction);
	console.log('blah');
	addMilestones($('.milestone-list'));
	addEvents($('.timeline-wrapper'));
	addGoals($('#goal-list'));
	//getMilestones();
})

function addMilestones(e){
	if(e.length ==0)
		return;
	console.log('blah');
	$.get('/data', gotMilestones);
}

function gotMilestones(result){
	var milestoneList = $('.milestone-list');
	console.log(result);
	var goalname = $('#goal-name-hack').html();
	console.log($('#goal-name-hack').html());
	var goals = result[0]['goals'];
	var realgoal ;
	for(var i = 0 ; i < goals.length; ++i){
		if(goals[i].name == goalname)
			realgoal = goals[i];
	}
	console.log(realgoal);
	for(var i = 0; i < realgoal.milestones.length; ++i){
		milestoneList.append('<button type="button" class="btn btn-default">' + realgoal.milestones[i].name+'</button>')
	}

}

function addGoals(e){
	if(e.length ==0)
		return;
	console.log('blah');
	$.get('/data', gotGoals);
}

function gotGoals(result){
	console.log(result);
	if($('#mainmenu').length==0){
		var goalList = $('#goal-list');
		console.log(result);
		var goals = result[0]['goals'];
		console.log(goals);
		for(var i = 0; i< goals.length; ++i){
			var string = '
' + goals[i].name +  '
';
			goalList.append(string);
		}
	}
	else{
		var goalList = $('#goal-list');
		console.log(result);
		var goals = result[0]['goals'];
		console.log(goals);
		for(var i = 0; i< goals.length; ++i){
			var string = '
' + goals[i].name +  '
';
			goalList.append(string);
			// $('#'+ goals[i]._id+' a[class = delete]').bind("click", function(e){
			// 	e.preventDefault();
			// 	console.log("clicked");
			// 	console.log( $(this).parent().parent().attr('id'));
			// 	$.post('/delgoal', {id: $(this).parent().attr('id')});
			// 	//window.location.href = '/menu';
			// });
		}
	}
}

function addEvents(e){
	if(e.length ==0)
		return;
	console.log('blah');
	$.get('/data', gotEvents);
}

function gotEvents(result){

	var timeline = $('.timeline-wrapper');

	if(result[0] == undefined || result[0].goals.length ==0){
		$('.goal-header').remove();
		$('#btn-add').remove();
		console.log('nothing to show');
		return;
	}
	else{
		$('.help-wrapper').hide();
	}
	console.log(result);
	var goals = result[0]['goals'];

	console.log(goals);
	var milestones = new Array();

	var goalname = $('#goal-name-hack').html();
	console.log(goalname);
	var realgolnum;
	if(goalname != ''){
		var realgoal ;
		for(var i = 0 ; i < goals.length; ++i){
			if(goals[i].name == goalname){
				realgoal = goals[i];
				realgolnum = i;

				break;
			}
		}
		makeGoalHeader(result, realgolnum);
		var milestonelist = realgoal.milestones;
		for(var j = 0; j <milestonelist.length; ++j){
			milestonelist[j].actualDate = new Date(milestonelist[j]['date']);
			milestonelist[j].goalNum = realgolnum;
			milestonelist[j].milestoneNum = j;
			milestones.push(milestonelist[j]);
		}
	}
	else{
		makeGoalHeader(result, -1);
		for(var i = 0; i < goals.length; ++i){
			var milestonelist = goals[i]['milestones'];
			for(var j = 0; j <milestonelist.length; ++j){
				milestonelist[j].actualDate = new Date(milestonelist[j]['date']);
				milestonelist[j].goalNum = i;
				milestonelist[j].milestoneNum = j;
				milestones.push(milestonelist[j]);
			}
		}
	}

	milestones.sort(dateComp);

	console.log(milestones);
	for(var i = 0; i < milestones.length ; ){
		var date = milestones[i].actualDate;
		if(isNaN(date.getTime())){
			i++;
			continue;
		}

		var dayMilestones = new Array();
		console.log(date);

		while(i < milestones.length && milestones[i].actualDate.getTime() == date.getTime()){
			dayMilestones.push(milestones[i]);
			i++;

		}

		var string = '
'+ date.toDateString() + '
'
		for(var j = 0; j < dayMilestones.length; ++j){
			if(dayMilestones[j].actualDate > Date.now()){
				string+= '
';
				string+= '
' + goals[dayMilestones[j].goalNum].name + '
';
			}
			else{
				string+= '
';
				string+= '
' + goals[dayMilestones[j].goalNum].name + '
';
			}
			string+=
                '
' +
                	(dayMilestones[j].milestoneNum+1) + '/'+goals[dayMilestones[j].goalNum]['milestones'].length+
                '

' +
    			'
  '+ dayMilestones[j].name + '
' +
    			'
';
		}
		string = '
' + string  + '
';
   		timeline.append(string);
	}

	$('.glyphicon-ok').click(function(e){
		$(this).toggleClass("black");
		var id = $(this).parent().attr('id');
		var goalname = $(this).parent().parent().find('p.event-complete-time').text();

		var goalnum= 0;
		for(; goalnum < result[0].goals.length; goalnum++){
			if(result[0].goals[goalnum].name == goalname)
				break;
		}

		var milestonestatus;
		var milestonename;
		for(var i = 0; i < result[0].goals[goalnum].milestones.length; ++i){
			if(result[0].goals[goalnum].milestones[i]._id == id){
				milestonestatus = result[0].goals[goalnum].milestones[i].completed;
				milestonename =result[0].goals[goalnum].milestones[i].name;
			}
		}

		console.log("switching from " + milestonestatus + " to " + !milestonestatus);

		var callback = function(data, status){
			if(status =='success'){
				console.log(data);
				$.get('/data', function(res){
					console.log(res);
					countGoals(res, realgolnum);
				});
			}
		};

		$.post('/milestoneupdate', {'milestonestatus' : !milestonestatus, 'milestonename': milestonename, 'milestoneid':id, 'goalname': goalname}
			, callback);
	});

	console.log(milestones);
}

function dateComp(a,b){
	return new Date(a.actualDate)-new Date(b.actualDate);
}

function countGoals(results, goalnum){
	var smallnum =0;
	var bignum =0;
	var goalname;
	var object = results[0];
	console.log('number is' + goalnum);
	if(goalnum != undefined){
		var goal = object['goals'][goalnum];
		goalname = goal.name;
		for(var i = 0 ; i < goal.milestones.length; ++i)
			if(goal.milestones[i].completed)
				smallnum++;
		bignum = goal.milestones.length;
	}
	else{
		goalname = "All Goals";
		for(var i = 0; i < object['goals'].length; ++i){
			var goal = object['goals'][i];
			for(var j = 0 ; j< goal.milestones.length; ++j)
				if(goal.milestones[j].completed)
					smallnum++;
			bignum += goal.milestones.length
		}
	}

	var percent = smallnum/bignum*100  + "%";
	$("#meter-span").width(percent)
}

function makeGoalHeader(results, goalnum){
	var smallnum =0;
	var bignum =0;
	var goalname, goaldate;
	if(goalnum != -1){
		var goal = results[0]['goals'][goalnum];
		goalname = goal.name;
		goaldate = new Date(goal.completionDate);
		goaldate = ((goaldate.getMonth() + 1) + '/' + goaldate.getDate() + '/' +  goaldate.getFullYear());

		var smallnum = 0;
		for(var i = 0 ; i < goal.milestones.length; ++i)
			if(goal.milestones[i].completed)
				smallnum++;
		bignum = goal.milestones.length;
	}
	else{
		goalname = "All Goals";
		for(var i = 0; i < results[0]['goals'].length; ++i){
			var goal = results[0]['goals'][i];
			goaldate = goal.completionDate;
			for(var j = 0 ; j< goal.milestones.length; ++j)
				if(goal.milestones[j].completed)
					smallnum++;
			bignum += goal.milestones.length
		}
	}

	var string = '

'+goalname+'

';
        if(goalnum!=-1)
            string += 'Finish by ' +  goaldate + '
';

        string += ''+  smallnum + ' of '+ bignum + ' milestones completed'+
           '
'+
                ''+
             '
' +
         '

';

        $(".goal-header").append(string);
}

function loginFunction(e){
	e.preventDefault();
	console.log('loggingin');
	$.post('/', {
		"user": $('#name').val(),
		"pass": $('#password').val(),
		"remember-me": 'true'
	}, function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});
}

function signupFunction(e){
	e.preventDefault();
	//replace this with actual login information
	console.log('signingup');
	$.post('/signup', {
		"name": $('#name').val(),
		"user": $('#username').val(),
		"email" : $('#email').val(),
		"pass": $('#password').val()
	}, function(data, status){
		if(data == 'ok'){
			$.post('/', {
				"user": $('#name').val(),
				"pass": $('#password').val(),
				"remember-me": 'true'
			}, function(a, b){
				console.log(a);
				console.log(b);
				window.location.href = "/";
			});
		}
		else{
			window.location.href = "/";
			console.log(data);
		}

	});
	// $.get('/');
};

function logOutFunction(e){
	e.preventDefault();

	$.post('/logout', {},
		function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});
};

function addGoalFunction(e){
	e.preventDefault();

	console.log('clicked');
	console.log( $('#name').val() );
	$.post('/addgoal', {
		"name" : $('#name').val() ,
		"date": $('#date').val()
	},
	function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});
	//window.location.href = "/";
};

function addMilestonePost(e){
	e.preventDefault;
	console.log('trying to add milestone');
	console.log($('#goal-name-hack').html());
	$.post('/addmilestonepost', {
		"name" : $('#goalname').val() ,
		"date": $('#complete').val(),
		"goal": $('#goal-name-hack').html()
	}, function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});

}

function goToSignUp(e){
	e.preventDefault();
	window.location.href= '/signup';
}

function cancelFunction(e){
	e.preventDefault();
	window.location.href= '/homescreen';
};

function addFunction(e){
	e.preventDefault();
	window.location.href= '/add-goal';
};

function addMilestoneFunction(e){
	e.preventDefault();
	if($('#goal-name-hack').html()){
		window.location.href= '/add-milestone/' + $('#goal-name-hack').html();
	}
	else
		window.location.href= '/choose-goal';
}

function menuFunction(e){
	e.preventDefault();
	window.location.href= '/menu';
};

function getMilestones(){
	console.log('stuff');
	$.post('/getms', {},
		function(data, status){
	});

	$.post('/addgoal', {},
		function(data, status){
	});
}
<commit_msg>fixed login<commit_after>
// Call this function when the page loads (the "ready" event)
$(document).ready(function() {

	$('#submit-btn').click(loginFunction);
	$('#btn-back').click(cancelFunction);
	$('.btn-register').click(goToSignUp);
	$('#makeact-btn').click(signupFunction);
	$('#btn-cancel').click(cancelFunction);
	$('#btn-add').click(addMilestoneFunction);
	$('#btn-menu').click(menuFunction);
	$('#btn-back-homescreen').click(cancelFunction);
	$('.logout').click(logOutFunction);
	$('#add-goal').click(addGoalFunction);
	$('#submit-milestone-btn').click(addMilestonePost);
	//$('#submit-btn').click(cancelFunction);
	console.log('blah');
	addMilestones($('.milestone-list'));
	addEvents($('.timeline-wrapper'));
	addGoals($('#goal-list'));
	//getMilestones();
})

function addMilestones(e){
	if(e.length ==0)
		return;
	console.log('blah');
	$.get('/data', gotMilestones);
}

function gotMilestones(result){
	var milestoneList = $('.milestone-list');
	console.log(result);
	var goalname = $('#goal-name-hack').html();
	console.log($('#goal-name-hack').html());
	var goals = result[0]['goals'];
	var realgoal ;
	for(var i = 0 ; i < goals.length; ++i){
		if(goals[i].name == goalname)
			realgoal = goals[i];
	}
	console.log(realgoal);
	for(var i = 0; i < realgoal.milestones.length; ++i){
		milestoneList.append('<button type="button" class="btn btn-default">' + realgoal.milestones[i].name+'</button>')
	}

}

function addGoals(e){
	if(e.length ==0)
		return;
	console.log('blah');
	$.get('/data', gotGoals);
}

function gotGoals(result){
	console.log(result);
	if($('#mainmenu').length==0){
		var goalList = $('#goal-list');
		console.log(result);
		var goals = result[0]['goals'];
		console.log(goals);
		for(var i = 0; i< goals.length; ++i){
			var string = '
' + goals[i].name +  '
';
			goalList.append(string);
		}
	}
	else{
		var goalList = $('#goal-list');
		console.log(result);
		var goals = result[0]['goals'];
		console.log(goals);
		for(var i = 0; i< goals.length; ++i){
			var string = '
' + goals[i].name +  '
';
			goalList.append(string);
			// $('#'+ goals[i]._id+' a[class = delete]').bind("click", function(e){
			// 	e.preventDefault();
			// 	console.log("clicked");
			// 	console.log( $(this).parent().parent().attr('id'));
			// 	$.post('/delgoal', {id: $(this).parent().attr('id')});
			// 	//window.location.href = '/menu';
			// });
		}
	}
}

function addEvents(e){
	if(e.length ==0)
		return;
	console.log('blah');
	$.get('/data', gotEvents);
}

function gotEvents(result){

	var timeline = $('.timeline-wrapper');

	if(result[0] == undefined || result[0].goals.length ==0){
		$('.goal-header').remove();
		$('#btn-add').remove();
		console.log('nothing to show');
		return;
	}
	else{
		$('.help-wrapper').hide();
	}
	console.log(result);
	var goals = result[0]['goals'];

	console.log(goals);
	var milestones = new Array();

	var goalname = $('#goal-name-hack').html();
	console.log(goalname);
	var realgolnum;
	if(goalname != ''){
		var realgoal ;
		for(var i = 0 ; i < goals.length; ++i){
			if(goals[i].name == goalname){
				realgoal = goals[i];
				realgolnum = i;

				break;
			}
		}
		makeGoalHeader(result, realgolnum);
		var milestonelist = realgoal.milestones;
		for(var j = 0; j <milestonelist.length; ++j){
			milestonelist[j].actualDate = new Date(milestonelist[j]['date']);
			milestonelist[j].goalNum = realgolnum;
			milestonelist[j].milestoneNum = j;
			milestones.push(milestonelist[j]);
		}
	}
	else{
		makeGoalHeader(result, -1);
		for(var i = 0; i < goals.length; ++i){
			var milestonelist = goals[i]['milestones'];
			for(var j = 0; j <milestonelist.length; ++j){
				milestonelist[j].actualDate = new Date(milestonelist[j]['date']);
				milestonelist[j].goalNum = i;
				milestonelist[j].milestoneNum = j;
				milestones.push(milestonelist[j]);
			}
		}
	}

	milestones.sort(dateComp);

	console.log(milestones);
	for(var i = 0; i < milestones.length ; ){
		var date = milestones[i].actualDate;
		if(isNaN(date.getTime())){
			i++;
			continue;
		}

		var dayMilestones = new Array();
		console.log(date);

		while(i < milestones.length && milestones[i].actualDate.getTime() == date.getTime()){
			dayMilestones.push(milestones[i]);
			i++;

		}

		var string = '
'+ date.toDateString() + '
'
		for(var j = 0; j < dayMilestones.length; ++j){
			if(dayMilestones[j].actualDate > Date.now()){
				string+= '
';
				string+= '
' + goals[dayMilestones[j].goalNum].name + '
';
			}
			else{
				string+= '
';
				string+= '
' + goals[dayMilestones[j].goalNum].name + '
';
			}
			string+=
                '
' +
                	(dayMilestones[j].milestoneNum+1) + '/'+goals[dayMilestones[j].goalNum]['milestones'].length+
                '

' +
    			'
  '+ dayMilestones[j].name + '
' +
    			'
';
		}
		string = '
' + string  + '
';
   		timeline.append(string);
	}

	$('.glyphicon-ok').click(function(e){
		$(this).toggleClass("black");
		var id = $(this).parent().attr('id');
		var goalname = $(this).parent().parent().find('p.event-complete-time').text();

		var goalnum= 0;
		for(; goalnum < result[0].goals.length; goalnum++){
			if(result[0].goals[goalnum].name == goalname)
				break;
		}

		var milestonestatus;
		var milestonename;
		for(var i = 0; i < result[0].goals[goalnum].milestones.length; ++i){
			if(result[0].goals[goalnum].milestones[i]._id == id){
				milestonestatus = result[0].goals[goalnum].milestones[i].completed;
				milestonename =result[0].goals[goalnum].milestones[i].name;
			}
		}

		console.log("switching from " + milestonestatus + " to " + !milestonestatus);

		var callback = function(data, status){
			if(status =='success'){
				console.log(data);
				$.get('/data', function(res){
					console.log(res);
					countGoals(res, realgolnum);
				});
			}
		};

		$.post('/milestoneupdate', {'milestonestatus' : !milestonestatus, 'milestonename': milestonename, 'milestoneid':id, 'goalname': goalname}
			, callback);
	});

	console.log(milestones);
}

function dateComp(a,b){
	return new Date(a.actualDate)-new Date(b.actualDate);
}

function countGoals(results, goalnum){
	var smallnum =0;
	var bignum =0;
	var goalname;
	var object = results[0];
	console.log('number is' + goalnum);
	if(goalnum != undefined){
		var goal = object['goals'][goalnum];
		goalname = goal.name;
		for(var i = 0 ; i < goal.milestones.length; ++i)
			if(goal.milestones[i].completed)
				smallnum++;
		bignum = goal.milestones.length;
	}
	else{
		goalname = "All Goals";
		for(var i = 0; i < object['goals'].length; ++i){
			var goal = object['goals'][i];
			for(var j = 0 ; j< goal.milestones.length; ++j)
				if(goal.milestones[j].completed)
					smallnum++;
			bignum += goal.milestones.length
		}
	}

	var percent = smallnum/bignum*100  + "%";
	$("#meter-span").width(percent)
}

function makeGoalHeader(results, goalnum){
	var smallnum =0;
	var bignum =0;
	var goalname, goaldate;
	if(goalnum != -1){
		var goal = results[0]['goals'][goalnum];
		goalname = goal.name;
		goaldate = new Date(goal.completionDate);
		goaldate = ((goaldate.getMonth() + 1) + '/' + goaldate.getDate() + '/' +  goaldate.getFullYear());

		var smallnum = 0;
		for(var i = 0 ; i < goal.milestones.length; ++i)
			if(goal.milestones[i].completed)
				smallnum++;
		bignum = goal.milestones.length;
	}
	else{
		goalname = "All Goals";
		for(var i = 0; i < results[0]['goals'].length; ++i){
			var goal = results[0]['goals'][i];
			goaldate = goal.completionDate;
			for(var j = 0 ; j< goal.milestones.length; ++j)
				if(goal.milestones[j].completed)
					smallnum++;
			bignum += goal.milestones.length
		}
	}

	var string = '

'+goalname+'

';
        if(goalnum!=-1)
            string += 'Finish by ' +  goaldate + '
';

        string += ''+  smallnum + ' of '+ bignum + ' milestones completed'+
           '
'+
                ''+
             '
' +
         '

';

        $(".goal-header").append(string);
}

function loginFunction(e){
	e.preventDefault();
	console.log('loggingin');
	$.post('/', {
		"user": $('#name').val(),
		"pass": $('#password').val(),
		"remember-me": 'true'
	}, function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});
}

function signupFunction(e){
	e.preventDefault();
	console.log('signingup');
	$.post('/signup', {
		"name": $('#name').val(),
		"user": $('#username').val(),
		"email" : $('#email').val(),
		"pass": $('#password').val()
	}, function(data, status){
		if(status == 'ok'){
			$.post('/', {
				"user": $('#name').val(),
				"pass": $('#password').val(),
				"remember-me": 'true'
			}, function(a, b){
				console.log(a);
				console.log(b);
				window.location.href = "/";
			});
		}
		else{
			alert(status);
			console.log(data);
		}
		window.location.href = "/";
	});
	// $.get('/');
};

function logOutFunction(e){
	e.preventDefault();

	$.post('/logout', {},
		function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});
};

function addGoalFunction(e){
	e.preventDefault();

	console.log('clicked');
	console.log( $('#name').val() );
	$.post('/addgoal', {
		"name" : $('#name').val() ,
		"date": $('#date').val()
	},
	function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});
	//window.location.href = "/";
};

function addMilestonePost(e){
	e.preventDefault;
	console.log('trying to add milestone');
	console.log($('#goal-name-hack').html());
	$.post('/addmilestonepost', {
		"name" : $('#goalname').val() ,
		"date": $('#complete').val(),
		"goal": $('#goal-name-hack').html()
	}, function(data, status){
		console.log(data);
		console.log(status);
		window.location.href = "/";
	});

}

function goToSignUp(e){
	e.preventDefault();
	window.location.href= '/signup';
}

function cancelFunction(e){
	e.preventDefault();
	window.location.href= '/homescreen';
};

function addFunction(e){
	e.preventDefault();
	window.location.href= '/add-goal';
};

function addMilestoneFunction(e){
	e.preventDefault();
	if($('#goal-name-hack').html()){
		window.location.href= '/add-milestone/' + $('#goal-name-hack').html();
	}
	else
		window.location.href= '/choose-goal';
}

function menuFunction(e){
	e.preventDefault();
	window.location.href= '/menu';
};

function getMilestones(){
	console.log('stuff');
	$.post('/getms', {},
		function(data, status){
	});

	$.post('/addgoal', {},
		function(data, status){
	});
}
<|endoftext|>


<commit_before>// itranswarp.js

function showSignin() {
    //
}

// JS Template:

function Template(tpl) {
    var
        fn,
        match,
        code = ['var r=[];\nvar _html = function (str) { return str.replace(/&/g, \'&\').replace(/"/g, \'"\').replace(/\'/g, \''\').replace(/</g, \'<\').replace(/>/g, \'>\'); };'],
        re = /\{\s*([a-zA-Z\.\_0-9()]+)(\s*\|\s*safe)?\s*\}/m,
        addLine = function (text) {
            code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
        };
    while (match = re.exec(tpl)) {
        if (match.index > 0) {
            addLine(tpl.slice(0, match.index));
        }
        if (match[2]) {
            code.push('r.push(String(this.' + match[1] + '));');
        }
        else {
            code.push('r.push(_html(String(this.' + match[1] + ')));');
        }
        tpl = tpl.substring(match.index + match[0].length);
    }
    addLine(tpl);
    code.push('return r.join(\'\');');
    fn = new Function(code.join('\n'));
    this.render = function (model) {
        return fn.apply(model);
    };
}

// load topics as comments:

var
    tplComment = null,
    tplCommentInfo = null;

function buildComments(data) {
    if (tplComment === null) {
        tplComment = new Template($('#tplComment').html());
    }
    if (tplCommentInfo === null) {
        tplCommentInfo = new Template($('#tplCommentInfo').html());
    }
    if (data.topics.length === 0) {
        return '
No comment yet.
';
    }
    var i, j, topic, reply, s, L = [], page = data.page;
    for (i=0; i<data.topics.length; i++) {
        topic = data.topics[i];
        L.push('
');
        L.push(tplComment.render(topic));
        L.push('
')
        if (topic.replies.length > 0) {
            for (j=0; j<topic.replies.length; j++) {
                reply = topic.replies[j];
                L.push('
');
                L.push(tplComment.render(reply));
                L.push('
');
            }
        }
        L.push(tplCommentInfo.render(topic));
        L.push('
');
        L.push('
');
    }
    return L.join('');
}

function ajaxLoadComments(insertIntoId, ref_id, page_index) {
    var errorHtml = 'Error when loading. Retry';
    $insertInto = $('#' + insertIntoId);
    $insertInto.html(' Loading...');
    $.getJSON('/api/ref/' + ref_id + '/topics?page=' + page_index).done(function(data) {
        if (data.error) {
            $insertInto.html(errorHtml);
            return;
        }
        // build comment list:
        $insertInto.html(buildComments(data));
        $insertInto.find('.x-auto-content').each(function () {
            makeCollapsable(this, 400);
        });
    }).fail(function() {
        $insertInto.html(errorHtml);
    });
}

var tmp_collapse = 1;

function makeCollapsable(obj, max_height) {
    var $o = $(obj);
    if ($o.height() <= (max_height + 60)) {
        $o.show();
        return;
    }
    console.log('detect height: ' + $o.height());
    var maxHeight = max_height + 'px';
    $o.css('max-height', maxHeight);
    $o.css('overflow', 'hidden');
    $o.after('
' +
        ' Read More' +
        ' Collapse' +
        '
');
    var aName = 'COLLAPSE-' + tmp_collapse;
    tmp_collapse ++;
    $o.parent().before('

')
    console.log($o.next().html());
    var $p = $o.next();
    var $aDown = $p.find('a:first');
    var $aUp = $p.find('a:last');
    $aDown.click(function () {
        $o.css('max-height', 'none');
        $aDown.hide();
        $aUp.show();
    });
    $aUp.click(function () {
        $o.css('max-height', maxHeight);
        $aUp.hide();
        $aDown.show();
        location.assign('#' + aName);
    });
    $o.show();
}

function loadComments(ref_id) {
    $(function () {
        var
            isCommentsLoaded = false,
            $window = $(window),
            targetOffset = $('#x-comment-list').get(0).offsetTop,
            checkOffset = function () {
                if (!isCommentsLoaded && (window.pageYOffset + window.innerHeight >= targetOffset)) {
                    isCommentsLoaded = true;
                    $window.off('scroll', checkOffset);
                    console.log('loading comments...');
                    ajaxLoadComments('x-comment-list', ref_id, 1);
                }
            };
        console.log('will load comments at offset: ' + targetOffset);
        $window.scroll(checkOffset);
        checkOffset();
    });

}

$(function() {
    $('.x-auto-content').each(function () {
        makeCollapsable(this, 300);
    });
});

if (! window.console) {
    window.console = {
        log: function(s) {
        }
    };
}

if (! String.prototype.trim) {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };
}

if (! Number.prototype.toDateTime) {
    var replaces = {
        'yyyy': function(dt) {
            return dt.getFullYear().toString();
        },
        'yy': function(dt) {
            return (dt.getFullYear() % 100).toString();
        },
        'MM': function(dt) {
            var m = dt.getMonth() + 1;
            return m < 10 ? '0' + m : m.toString();
        },
        'M': function(dt) {
            var m = dt.getMonth() + 1;
            return m.toString();
        },
        'dd': function(dt) {
            var d = dt.getDate();
            return d < 10 ? '0' + d : d.toString();
        },
        'd': function(dt) {
            var d = dt.getDate();
            return d.toString();
        },
        'hh': function(dt) {
            var h = dt.getHours();
            return h < 10 ? '0' + h : h.toString();
        },
        'h': function(dt) {
            var h = dt.getHours();
            return h.toString();
        },
        'mm': function(dt) {
            var m = dt.getMinutes();
            return m < 10 ? '0' + m : m.toString();
        },
        'm': function(dt) {
            var m = dt.getMinutes();
            return m.toString();
        },
        'ss': function(dt) {
            var s = dt.getSeconds();
            return s < 10 ? '0' + s : s.toString();
        },
        's': function(dt) {
            var s = dt.getSeconds();
            return s.toString();
        },
        'a': function(dt) {
            var h = dt.getHours();
            return h < 12 ? 'AM' : 'PM';
        }
    };
    var token = /([a-zA-Z]+)/;
    Number.prototype.toDateTime = function(format) {
        var fmt = format || 'yyyy-MM-dd hh:mm:ss'
        var dt = new Date(this);
        var arr = fmt.split(token);
        for (var i=0; i<arr.length; i++) {
            var s = arr[i];
            if (s && s in replaces) {
                arr[i] = replaces[s](dt);
            }
        }
        return arr.join('');
    };
    Number.prototype.toSmartDate = function () {
        return toSmartDate(this);
    };
}

function encodeHtml(str) {
    return String(str)
        .replace(/&/g, '&')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/</g, '<')
        .replace(/>/g, '>');
}

function toSmartDate(timestamp) {
    if (typeof(timestamp)==='string') {
        timestamp = parseInt(timestamp);
    }
    if (isNaN(timestamp)) {
        return '';
    }
    var
        today = new Date(g_time),
        now = today.getTime(),
        s = '1分钟前',
        t = now - timestamp;
    if (t > 604800000) {
        // 1 week ago:
        var that = new Date(timestamp);
        var
            y = that.getFullYear(),
            m = that.getMonth() + 1,
            d = that.getDate(),
            hh = that.getHours(),
            mm = that.getMinutes();
        s = y===today.getFullYear() ? '' : y + '-';
        s = s + m + '-' + d + ' ' + hh + ':' + (mm < 10 ? '0' : '') + mm;
    }
    else if (t >= 86400000) {
        // 1-6 days ago:
        s = Math.floor(t / 86400000) + '天前';
    }
    else if (t >= 3600000) {
        // 1-23 hours ago:
        s = Math.floor(t / 3600000) + '小时前';
    }
    else if (t >= 60000) {
        s = Math.floor(t / 60000) + '分钟前';
    }
    return s;
}

$(function() {
    // activate nav:
    var xnav = $('meta[property="x-nav"]').attr('content');
    xnav && xnav.trim() && $('#ul-navbar li a[href="' + xnav.trim() + '"]').parent().addClass('uk-active');

    // init scroll:
    var $window = $(window);
    var $body = $('body');
    var $gotoTop = $('div.x-goto-top');
    $window.scroll(function() {
        var t = $window.scrollTop();
        if (t > 1600) {
            $gotoTop.show();
        }
        else {
            $gotoTop.hide();
        }
    });

    // go-top:
    $gotoTop.click(function() {
        $('html, body').animate({scrollTop: 0}, 1000);
    });

    // smart date:
    $('.x-smartdate').each(function() {
        var f = parseInt($(this).attr('date'));
        $(this).text(toSmartDate(f));
    });

    // search query:
    // var input_search = $('input.search-query');
    // var old_width = input_search.css('width');
    // input_search.bind('focusin', function() {
    //     input_search.animate({'width': '160px'}, 500);
    // }).bind('focusout', function() {
    //     input_search.animate({'width': old_width}, 500);
    // });

    hljs.initHighlighting();
    // END
});
<commit_msg>add auth for js<commit_after>// itranswarp.js

var signinModal = null;

function showSignin() {
    if (g_signins.length === 1) {
        return authFrom(g_signins[0].id);
    }
    if (signinModal === null) {
        signinModal = UIkit.modal('#modal-signin', {
            bgclose: false,
            center: true
        });
    }
    signinModal.show();
}

// JS Template:

function Template(tpl) {
    var
        fn,
        match,
        code = ['var r=[];\nvar _html = function (str) { return str.replace(/&/g, \'&\').replace(/"/g, \'"\').replace(/\'/g, \''\').replace(/</g, \'<\').replace(/>/g, \'>\'); };'],
        re = /\{\s*([a-zA-Z\.\_0-9()]+)(\s*\|\s*safe)?\s*\}/m,
        addLine = function (text) {
            code.push('r.push(\'' + text.replace(/\'/g, '\\\'').replace(/\n/g, '\\n').replace(/\r/g, '\\r') + '\');');
        };
    while (match = re.exec(tpl)) {
        if (match.index > 0) {
            addLine(tpl.slice(0, match.index));
        }
        if (match[2]) {
            code.push('r.push(String(this.' + match[1] + '));');
        }
        else {
            code.push('r.push(_html(String(this.' + match[1] + ')));');
        }
        tpl = tpl.substring(match.index + match[0].length);
    }
    addLine(tpl);
    code.push('return r.join(\'\');');
    fn = new Function(code.join('\n'));
    this.render = function (model) {
        return fn.apply(model);
    };
}

// load topics as comments:

var
    tplComment = null,
    tplCommentInfo = null;

function buildComments(data) {
    if (tplComment === null) {
        tplComment = new Template($('#tplComment').html());
    }
    if (tplCommentInfo === null) {
        tplCommentInfo = new Template($('#tplCommentInfo').html());
    }
    if (data.topics.length === 0) {
        return '
No comment yet.
';
    }
    var i, j, topic, reply, s, L = [], page = data.page;
    for (i=0; i<data.topics.length; i++) {
        topic = data.topics[i];
        L.push('
');
        L.push(tplComment.render(topic));
        L.push('
')
        if (topic.replies.length > 0) {
            for (j=0; j<topic.replies.length; j++) {
                reply = topic.replies[j];
                L.push('
');
                L.push(tplComment.render(reply));
                L.push('
');
            }
        }
        L.push(tplCommentInfo.render(topic));
        L.push('
');
        L.push('
');
    }
    return L.join('');
}

function ajaxLoadComments(insertIntoId, ref_id, page_index) {
    var errorHtml = 'Error when loading. Retry';
    $insertInto = $('#' + insertIntoId);
    $insertInto.html(' Loading...');
    $.getJSON('/api/ref/' + ref_id + '/topics?page=' + page_index).done(function(data) {
        if (data.error) {
            $insertInto.html(errorHtml);
            return;
        }
        // build comment list:
        $insertInto.html(buildComments(data));
        $insertInto.find('.x-auto-content').each(function () {
            makeCollapsable(this, 400);
        });
    }).fail(function() {
        $insertInto.html(errorHtml);
    });
}

var tmp_collapse = 1;

function makeCollapsable(obj, max_height) {
    var $o = $(obj);
    if ($o.height() <= (max_height + 60)) {
        $o.show();
        return;
    }
    console.log('detect height: ' + $o.height());
    var maxHeight = max_height + 'px';
    $o.css('max-height', maxHeight);
    $o.css('overflow', 'hidden');
    $o.after('
' +
        ' Read More' +
        ' Collapse' +
        '
');
    var aName = 'COLLAPSE-' + tmp_collapse;
    tmp_collapse ++;
    $o.parent().before('

')
    console.log($o.next().html());
    var $p = $o.next();
    var $aDown = $p.find('a:first');
    var $aUp = $p.find('a:last');
    $aDown.click(function () {
        $o.css('max-height', 'none');
        $aDown.hide();
        $aUp.show();
    });
    $aUp.click(function () {
        $o.css('max-height', maxHeight);
        $aUp.hide();
        $aDown.show();
        location.assign('#' + aName);
    });
    $o.show();
}

function loadComments(ref_id) {
    $(function () {
        var
            isCommentsLoaded = false,
            $window = $(window),
            targetOffset = $('#x-comment-list').get(0).offsetTop,
            checkOffset = function () {
                if (!isCommentsLoaded && (window.pageYOffset + window.innerHeight >= targetOffset)) {
                    isCommentsLoaded = true;
                    $window.off('scroll', checkOffset);
                    console.log('loading comments...');
                    ajaxLoadComments('x-comment-list', ref_id, 1);
                }
            };
        console.log('will load comments at offset: ' + targetOffset);
        $window.scroll(checkOffset);
        checkOffset();
    });

}

$(function() {
    $('.x-auto-content').each(function () {
        makeCollapsable(this, 300);
    });
});

if (! window.console) {
    window.console = {
        log: function(s) {
        }
    };
}

if (! String.prototype.trim) {
    String.prototype.trim = function() {
        return this.replace(/^\s+|\s+$/g, '');
    };
}

if (! Number.prototype.toDateTime) {
    var replaces = {
        'yyyy': function(dt) {
            return dt.getFullYear().toString();
        },
        'yy': function(dt) {
            return (dt.getFullYear() % 100).toString();
        },
        'MM': function(dt) {
            var m = dt.getMonth() + 1;
            return m < 10 ? '0' + m : m.toString();
        },
        'M': function(dt) {
            var m = dt.getMonth() + 1;
            return m.toString();
        },
        'dd': function(dt) {
            var d = dt.getDate();
            return d < 10 ? '0' + d : d.toString();
        },
        'd': function(dt) {
            var d = dt.getDate();
            return d.toString();
        },
        'hh': function(dt) {
            var h = dt.getHours();
            return h < 10 ? '0' + h : h.toString();
        },
        'h': function(dt) {
            var h = dt.getHours();
            return h.toString();
        },
        'mm': function(dt) {
            var m = dt.getMinutes();
            return m < 10 ? '0' + m : m.toString();
        },
        'm': function(dt) {
            var m = dt.getMinutes();
            return m.toString();
        },
        'ss': function(dt) {
            var s = dt.getSeconds();
            return s < 10 ? '0' + s : s.toString();
        },
        's': function(dt) {
            var s = dt.getSeconds();
            return s.toString();
        },
        'a': function(dt) {
            var h = dt.getHours();
            return h < 12 ? 'AM' : 'PM';
        }
    };
    var token = /([a-zA-Z]+)/;
    Number.prototype.toDateTime = function(format) {
        var fmt = format || 'yyyy-MM-dd hh:mm:ss'
        var dt = new Date(this);
        var arr = fmt.split(token);
        for (var i=0; i<arr.length; i++) {
            var s = arr[i];
            if (s && s in replaces) {
                arr[i] = replaces[s](dt);
            }
        }
        return arr.join('');
    };
    Number.prototype.toSmartDate = function () {
        return toSmartDate(this);
    };
}

function encodeHtml(str) {
    return String(str)
        .replace(/&/g, '&')
        .replace(/"/g, '"')
        .replace(/'/g, ''')
        .replace(/</g, '<')
        .replace(/>/g, '>');
}

function toSmartDate(timestamp) {
    if (typeof(timestamp)==='string') {
        timestamp = parseInt(timestamp);
    }
    if (isNaN(timestamp)) {
        return '';
    }
    var
        today = new Date(g_time),
        now = today.getTime(),
        s = '1分钟前',
        t = now - timestamp;
    if (t > 604800000) {
        // 1 week ago:
        var that = new Date(timestamp);
        var
            y = that.getFullYear(),
            m = that.getMonth() + 1,
            d = that.getDate(),
            hh = that.getHours(),
            mm = that.getMinutes();
        s = y===today.getFullYear() ? '' : y + '-';
        s = s + m + '-' + d + ' ' + hh + ':' + (mm < 10 ? '0' : '') + mm;
    }
    else if (t >= 86400000) {
        // 1-6 days ago:
        s = Math.floor(t / 86400000) + '天前';
    }
    else if (t >= 3600000) {
        // 1-23 hours ago:
        s = Math.floor(t / 3600000) + '小时前';
    }
    else if (t >= 60000) {
        s = Math.floor(t / 60000) + '分钟前';
    }
    return s;
}

// parse query string as object:

function parseQueryString() {
    var
        q = location.search,
        r = {},
        i, pos, s, qs;
    if (q && q.charAt(0)==='?') {
        qs = q.substring(1).split('&');
        for (i=0; i<qs.length; i++) {
            s = qs[i];
            pos = s.indexOf('=');
            if (pos <= 0) {
                continue;
            }
            r[s.substring(0, pos)] = decodeURIComponent(s.substring(pos+1)).replace(/\+/g, ' ');
        }
    }
    return r;
}

function gotoPage(i) {
    var r = parseQueryString();
    r.page = i;
    location.assign('?' + $.param(r));
}

function refresh() {
    var r = parseQueryString();
    r.t = new Date().getTime();
    location.assign('?' + $.param(r));
}

// extends jQuery.form:

$(function () {
    console.log('Extends $form...');
    $.fn.extend({
        showFormError: function (err) {
            return this.each(function () {
                var
                    $form = $(this),
                    $alert = $form && $form.find('.uk-alert-danger'),
                    fieldName = err && err.data;
                if (! $form.is('form')) {
                    console.error('Cannot call showFormError() on non-form object.');
                    return;
                }
                $form.find('input').removeClass('uk-form-danger');
                $form.find('select').removeClass('uk-form-danger');
                $form.find('textarea').removeClass('uk-form-danger');
                if ($alert.length === 0) {
                    console.warn('Cannot find .uk-alert-danger element.');
                    return;
                }
                if (err) {
                    $alert.text(err.message ? err.message : (err.error ? err.error : err)).removeClass('uk-hidden').show();
                    if (($alert.offset().top - 60) < $(window).scrollTop()) {
                        $('html,body').animate({ scrollTop: $alert.offset().top - 60 });
                    }
                    if (fieldName) {
                        $form.find('[name=' + fieldName + ']').addClass('uk-form-danger');
                    }
                }
                else {
                    $alert.addClass('uk-hidden').hide();
                    $form.find('.uk-form-danger').removeClass('uk-form-danger');
                }
            });
        },
        showFormLoading: function (isLoading) {
            return this.each(function () {
                var
                    $form = $(this),
                    $submit = $form && $form.find('button[type=submit]'),
                    $buttons = $form && $form.find('button');
                    $i = $submit && $submit.find('i'),
                    iconClass = $i && $i.attr('class');
                if (! $form.is('form')) {
                    console.error('Cannot call showFormLoading() on non-form object.');
                    return;
                }
                if (!iconClass || iconClass.indexOf('uk-icon') < 0) {
                    console.warn('Icon " not found.');
                    return;
                }
                if (isLoading) {
                    $buttons.attr('disabled', 'disabled');
                    $i && $i.addClass('uk-icon-spinner').addClass('uk-icon-spin');
                }
                else {
                    $buttons.removeAttr('disabled');
                    $i && $i.removeClass('uk-icon-spinner').removeClass('uk-icon-spin');
                }
            });
        },
        postJSON: function (url, data, callback) {
            if (arguments.length===2) {
                callback = data;
                data = {};
            }
            return this.each(function () {
                var $form = $(this);
                $form.showFormError();
                $form.showFormLoading(true);
                _httpJSON('POST', url, data, function (err, r) {
                    if (err) {
                        $form.showFormError(err);
                        $form.showFormLoading(false);
                    }
                    if (callback) {
                        if (callback(err, r)) {
                            $form.showFormLoading(false);
                        }
                    }
                });
            });
        }
    });
});

// ajax submit form:

function _httpJSON(method, url, data, callback) {
    var opt = {
        type: method,
        dataType: 'json'
    };
    if (method==='GET') {
        opt.url = url + '?' + data;
    }
    if (method==='POST') {
        opt.url = url;
        opt.data = JSON.stringify(data || {});
        opt.contentType = 'application/json';
    }
    $.ajax(opt).done(function (r) {
        if (r && r.error) {
            return callback(r);
        }
        return callback(null, r);
    }).fail(function (jqXHR, textStatus) {
        return callback({'error': 'http_bad_response', 'data': '' + jqXHR.status, 'message': '网络好像出问题了 (HTTP ' + jqXHR.status + ')'});
    });
}

function getJSON(url, data, callback) {
    if (arguments.length===2) {
        callback = data;
        data = {};
    }
    if (typeof (data)==='object') {
        var arr = [];
        $.each(data, function (k, v) {
            arr.push(k + '=' + encodeURIComponent(v));
        });
        data = arr.join('&');
    }
    _httpJSON('GET', url, data, callback);
}

function postJSON(url, data, callback) {
    if (arguments.length===2) {
        callback = data;
        data = {};
    }
    _httpJSON('POST', url, data, callback);
}

$(function() {
    // activate nav:
    var xnav = $('meta[property="x-nav"]').attr('content');
    xnav && xnav.trim() && $('#ul-navbar li a[href="' + xnav.trim() + '"]').parent().addClass('uk-active');

    // init scroll:
    var $window = $(window);
    var $body = $('body');
    var $gotoTop = $('div.x-goto-top');
    $window.scroll(function() {
        var t = $window.scrollTop();
        if (t > 1600) {
            $gotoTop.show();
        }
        else {
            $gotoTop.hide();
        }
    });

    // go-top:
    $gotoTop.click(function() {
        $('html, body').animate({scrollTop: 0}, 1000);
    });

    // smart date:
    $('.x-smartdate').each(function() {
        var f = parseInt($(this).attr('date'));
        $(this).text(toSmartDate(f));
    });

    // search query:
    // var input_search = $('input.search-query');
    // var old_width = input_search.css('width');
    // input_search.bind('focusin', function() {
    //     input_search.animate({'width': '160px'}, 500);
    // }).bind('focusout', function() {
    //     input_search.animate({'width': old_width}, 500);
    // });

    hljs.initHighlighting();
    // END
});

// signin with oauth:

var isDesktop = (function() {
    var ua = navigator.userAgent.toLowerCase();
    return ua.indexOf('windows nt')>=0 || ua.indexOf('macintosh')>=0;
})();

function onAuthCallback(user) {
    if (signinModal !== null) {
        signinModal.hide();
    }
    g_user = {
        id: user.id,
        name: user.name,
        image_url: user.image_url
    };
    // update user info:
    $('.x-user-name').text(g_user.name);
    // update css:
    $('#x-doc-style').text('.x-display-if-signin {}\n.x-display-if-not-signin { display: none; }\n');
    // reload if neccessary:
    if (typeof(g_reload_after_signin) !== 'undefined' && g_reload_after_signin === true) {
        location.reload();
    }
    else {
        if (typeof(onAuthSuccess) === 'function') {
            onAuthSuccess();
        }
    }
}

function authFrom(provider) {
    var
        url = '/auth/from/' + provider,
        popupId = location.hostname.replace(/\./g, '_');
    if (isDesktop) {
        var w = window.open(url + '?jscallback=onAuthCallback', popupId, 'top=200,left=400,width=600,height=380,directories=no,menubar=no,toolbar=no,resizable=no');
    }
    else {
        location.assign(url);
    }
}
<|endoftext|>


<commit_before>var message_fetch = (function () {

var exports = {};

var consts = {
    backfill_idle_time: 10*1000,
    error_retry_time: 5000,
    backfill_batch_size: 1000,
    narrow_before: 50,
    narrow_after: 50,
    num_before_pointer: 200,
    num_after_pointer: 200,
    backward_batch_size: 100,
    catch_up_batch_size: 1000,
};

function process_result(data, opts) {
    var messages = data.messages;

    $('#connection-error').removeClass("show");

    if ((messages.length === 0) && (current_msg_list === message_list.narrowed) &&
        message_list.narrowed.empty()) {
        // Even after trying to load more messages, we have no
        // messages to display in this narrow.
        narrow.show_empty_narrow_message();
    }

    _.each(messages, message_store.set_message_booleans);
    messages = _.map(messages, message_store.add_message_metadata);

    // If we're loading more messages into the home view, save them to
    // the message_list.all as well, as the home_msg_list is reconstructed
    // from message_list.all.
    if (opts.msg_list === home_msg_list) {
        message_util.do_unread_count_updates(messages);
        message_util.add_messages(messages, message_list.all, {messages_are_new: false});
    }

    if (messages.length !== 0) {
        message_util.add_messages(messages, opts.msg_list, {messages_are_new: false});
    }

    activity.process_loaded_messages(messages);
    stream_list.update_streams_sidebar();
    pm_list.update_private_messages();

    if (opts.cont !== undefined) {
        opts.cont(data);
    }
}

function get_messages_success(data, opts) {
    if (opts.msg_list.narrowed && opts.msg_list !== current_msg_list) {
        // We unnarrowed before receiving new messages so
        // don't bother processing the newly arrived messages.
        return;
    }
    if (! data) {
        // The server occasionally returns no data during a
        // restart.  Ignore those responses and try again
        setTimeout(function () {
            exports.load_messages(opts);
        }, 0);
        return;
    }

    process_result(data, opts);
    resize.resize_bottom_whitespace();
}

exports.load_messages = function (opts) {
    var data = {anchor: opts.anchor,
                num_before: opts.num_before,
                num_after: opts.num_after};

    if (opts.msg_list.narrowed && narrow_state.active()) {
        var operators = narrow_state.public_operators();
        if (page_params.narrow !== undefined) {
            operators = operators.concat(page_params.narrow);
        }
        data.narrow = JSON.stringify(operators);
    }
    if (opts.msg_list === home_msg_list && page_params.narrow_stream !== undefined) {
        data.narrow = JSON.stringify(page_params.narrow);
    }
    if (opts.use_first_unread_anchor) {
        data.use_first_unread_anchor = true;
    }

    data.client_gravatar = true;

    channel.get({
        url:      '/json/messages',
        data:     data,
        idempotent: true,
        success: function (data) {
            get_messages_success(data, opts);
        },
        error: function (xhr) {
            if (opts.msg_list.narrowed && opts.msg_list !== current_msg_list) {
                // We unnarrowed before getting an error so don't
                // bother trying again or doing further processing.
                return;
            }
            if (xhr.status === 400) {
                // Bad request: We probably specified a narrow operator
                // for a nonexistent stream or something.  We shouldn't
                // retry or display a connection error.
                //
                // FIXME: Warn the user when this has happened?
                var data = {
                    messages: [],
                };
                process_result(data, opts);
                return;
            }

            // We might want to be more clever here
            $('#connection-error').addClass("show");
            setTimeout(function () {
                exports.load_messages(opts);
            }, consts.error_retry_time);
        },
    });
};

exports.load_messages_for_narrow = function (opts) {
    var msg_list = message_list.narrowed;

    msg_list.fetch_status.start_initial_narrow();

    message_fetch.load_messages({
        anchor: opts.then_select_id.toFixed(),
        num_before: consts.narrow_before,
        num_after: consts.narrow_after,
        msg_list: msg_list,
        use_first_unread_anchor: opts.use_initial_narrow_pointer,
        cont: function (data) {
            msg_list.fetch_status.finish_initial_narrow({
                found_oldest: data.found_oldest,
                found_newest: data.found_newest,
            });
            message_scroll.hide_indicators();
            opts.cont();
        },
    });
};

exports.maybe_load_older_messages = function (opts) {
    // This function gets called when you scroll to the top
    // of your window, and you want to get messages older
    // than what the browers originally fetched.
    var msg_list = opts.msg_list;
    var oldest_message_id;
    if (!msg_list.fetch_status.can_load_older_messages()) {
        // We may already be loading old messages or already
        // got the oldest one.
        return;
    }
    opts.show_loading();
    msg_list.fetch_status.start_older_batch();
    if (msg_list.first() === undefined) {
        oldest_message_id = page_params.pointer;
    } else {
        oldest_message_id = msg_list.first().id;
    }

    var batch_size = consts.backward_batch_size;

    exports.load_messages({
        anchor: oldest_message_id.toFixed(),
        num_before: batch_size,
        num_after: 0,
        msg_list: msg_list,
        cont: function (data) {
            opts.hide_loading();
            msg_list.fetch_status.finish_older_batch({
                found_oldest: data.found_oldest,
            });
        },
    });
};

exports.initialize = function () {
    // get the initial message list
    function load_more(data) {
        var messages = data.messages;

        // If we received the initially selected message, select it on the client side,
        // but not if the user has already selected another one during load.
        //
        // We fall back to the closest selected id, as the user may have removed
        // a stream from the home before already
        if (home_msg_list.selected_id() === -1 && !home_msg_list.empty()) {
            home_msg_list.select_id(page_params.pointer,
                                    {then_scroll: true, use_closest: true,
                                     target_scroll_offset: page_params.initial_offset});
        }

        // catch the user up
        if (messages.length !== 0) {
            var latest_id = messages[messages.length-1].id;
            if (latest_id < page_params.max_message_id) {
                exports.load_messages({
                    anchor: latest_id.toFixed(),
                    num_before: 0,
                    num_after: consts.catch_up_batch_size,
                    msg_list: home_msg_list,
                    cont: load_more,
                });
                return;
            }
        }

        server_events.home_view_loaded();

        // backfill more messages after the user is idle
        $(document).idle({idle: consts.backfill_idle_time,
                          onIdle: function () {
                              var first_id = message_list.all.first().id;
                              exports.load_messages({
                                  anchor: first_id,
                                  num_before: consts.backfill_batch_size,
                                  num_after: 0,
                                  msg_list: home_msg_list,
                              });
                          }});
    }

    if (page_params.have_initial_messages) {
        exports.load_messages({
            anchor: page_params.pointer,
            num_before: consts.num_before_pointer,
            num_after: consts.num_after_pointer,
            msg_list: home_msg_list,
            cont: load_more,
        });
    } else {
        server_events.home_view_loaded();
    }
};

return exports;

}());
if (typeof module !== 'undefined') {
    module.exports = message_fetch;
}
<commit_msg>Extract start_backfilling_messages().<commit_after>var message_fetch = (function () {

var exports = {};

var consts = {
    backfill_idle_time: 10*1000,
    error_retry_time: 5000,
    backfill_batch_size: 1000,
    narrow_before: 50,
    narrow_after: 50,
    num_before_pointer: 200,
    num_after_pointer: 200,
    backward_batch_size: 100,
    catch_up_batch_size: 1000,
};

function process_result(data, opts) {
    var messages = data.messages;

    $('#connection-error').removeClass("show");

    if ((messages.length === 0) && (current_msg_list === message_list.narrowed) &&
        message_list.narrowed.empty()) {
        // Even after trying to load more messages, we have no
        // messages to display in this narrow.
        narrow.show_empty_narrow_message();
    }

    _.each(messages, message_store.set_message_booleans);
    messages = _.map(messages, message_store.add_message_metadata);

    // If we're loading more messages into the home view, save them to
    // the message_list.all as well, as the home_msg_list is reconstructed
    // from message_list.all.
    if (opts.msg_list === home_msg_list) {
        message_util.do_unread_count_updates(messages);
        message_util.add_messages(messages, message_list.all, {messages_are_new: false});
    }

    if (messages.length !== 0) {
        message_util.add_messages(messages, opts.msg_list, {messages_are_new: false});
    }

    activity.process_loaded_messages(messages);
    stream_list.update_streams_sidebar();
    pm_list.update_private_messages();

    if (opts.cont !== undefined) {
        opts.cont(data);
    }
}

function get_messages_success(data, opts) {
    if (opts.msg_list.narrowed && opts.msg_list !== current_msg_list) {
        // We unnarrowed before receiving new messages so
        // don't bother processing the newly arrived messages.
        return;
    }
    if (! data) {
        // The server occasionally returns no data during a
        // restart.  Ignore those responses and try again
        setTimeout(function () {
            exports.load_messages(opts);
        }, 0);
        return;
    }

    process_result(data, opts);
    resize.resize_bottom_whitespace();
}

exports.load_messages = function (opts) {
    var data = {anchor: opts.anchor,
                num_before: opts.num_before,
                num_after: opts.num_after};

    if (opts.msg_list.narrowed && narrow_state.active()) {
        var operators = narrow_state.public_operators();
        if (page_params.narrow !== undefined) {
            operators = operators.concat(page_params.narrow);
        }
        data.narrow = JSON.stringify(operators);
    }
    if (opts.msg_list === home_msg_list && page_params.narrow_stream !== undefined) {
        data.narrow = JSON.stringify(page_params.narrow);
    }
    if (opts.use_first_unread_anchor) {
        data.use_first_unread_anchor = true;
    }

    data.client_gravatar = true;

    channel.get({
        url:      '/json/messages',
        data:     data,
        idempotent: true,
        success: function (data) {
            get_messages_success(data, opts);
        },
        error: function (xhr) {
            if (opts.msg_list.narrowed && opts.msg_list !== current_msg_list) {
                // We unnarrowed before getting an error so don't
                // bother trying again or doing further processing.
                return;
            }
            if (xhr.status === 400) {
                // Bad request: We probably specified a narrow operator
                // for a nonexistent stream or something.  We shouldn't
                // retry or display a connection error.
                //
                // FIXME: Warn the user when this has happened?
                var data = {
                    messages: [],
                };
                process_result(data, opts);
                return;
            }

            // We might want to be more clever here
            $('#connection-error').addClass("show");
            setTimeout(function () {
                exports.load_messages(opts);
            }, consts.error_retry_time);
        },
    });
};

exports.load_messages_for_narrow = function (opts) {
    var msg_list = message_list.narrowed;

    msg_list.fetch_status.start_initial_narrow();

    message_fetch.load_messages({
        anchor: opts.then_select_id.toFixed(),
        num_before: consts.narrow_before,
        num_after: consts.narrow_after,
        msg_list: msg_list,
        use_first_unread_anchor: opts.use_initial_narrow_pointer,
        cont: function (data) {
            msg_list.fetch_status.finish_initial_narrow({
                found_oldest: data.found_oldest,
                found_newest: data.found_newest,
            });
            message_scroll.hide_indicators();
            opts.cont();
        },
    });
};

exports.maybe_load_older_messages = function (opts) {
    // This function gets called when you scroll to the top
    // of your window, and you want to get messages older
    // than what the browers originally fetched.
    var msg_list = opts.msg_list;
    var oldest_message_id;
    if (!msg_list.fetch_status.can_load_older_messages()) {
        // We may already be loading old messages or already
        // got the oldest one.
        return;
    }
    opts.show_loading();
    msg_list.fetch_status.start_older_batch();
    if (msg_list.first() === undefined) {
        oldest_message_id = page_params.pointer;
    } else {
        oldest_message_id = msg_list.first().id;
    }

    var batch_size = consts.backward_batch_size;

    exports.load_messages({
        anchor: oldest_message_id.toFixed(),
        num_before: batch_size,
        num_after: 0,
        msg_list: msg_list,
        cont: function (data) {
            opts.hide_loading();
            msg_list.fetch_status.finish_older_batch({
                found_oldest: data.found_oldest,
            });
        },
    });
};

exports.start_backfilling_messages = function () {
    // backfill more messages after the user is idle
    $(document).idle({idle: consts.backfill_idle_time,
                      onIdle: function () {
                          var first_id = message_list.all.first().id;
                          exports.load_messages({
                              anchor: first_id,
                              num_before: consts.backfill_batch_size,
                              num_after: 0,
                              msg_list: home_msg_list,
                          });
                      }});
};

exports.initialize = function () {
    // get the initial message list
    function load_more(data) {
        var messages = data.messages;

        // If we received the initially selected message, select it on the client side,
        // but not if the user has already selected another one during load.
        //
        // We fall back to the closest selected id, as the user may have removed
        // a stream from the home before already
        if (home_msg_list.selected_id() === -1 && !home_msg_list.empty()) {
            home_msg_list.select_id(page_params.pointer,
                                    {then_scroll: true, use_closest: true,
                                     target_scroll_offset: page_params.initial_offset});
        }

        // catch the user up
        if (messages.length !== 0) {
            var latest_id = messages[messages.length-1].id;
            if (latest_id < page_params.max_message_id) {
                exports.load_messages({
                    anchor: latest_id.toFixed(),
                    num_before: 0,
                    num_after: consts.catch_up_batch_size,
                    msg_list: home_msg_list,
                    cont: load_more,
                });
                return;
            }
        }

        server_events.home_view_loaded();

        exports.start_backfilling_messages();
    }

    if (page_params.have_initial_messages) {
        exports.load_messages({
            anchor: page_params.pointer,
            num_before: consts.num_before_pointer,
            num_after: consts.num_after_pointer,
            msg_list: home_msg_list,
            cont: load_more,
        });
    } else {
        server_events.home_view_loaded();
    }
};

return exports;

}());
if (typeof module !== 'undefined') {
    module.exports = message_fetch;
}
<|endoftext|>


<commit_before>/* global $, _, phiURL, arealist, urlbar:true */

urlbar = function(){
   if (!(this instanceof urlbar)) return new urlbar();

   this.history = [];
   this.curr = -1;
};

urlbar.prototype.attach = function($element){
   var $urlbar = $element;
   var _urlbar = this;

   this.$URL     = $urlbar.find('#URL');
   this.$back    = $urlbar.find('#back');
   this.$forward = $urlbar.find('#forward');

   this.$back.on('click', function(){
      _urlbar.back();
   });
   this.$forward.on('click', function(){
      _urlbar.forward();
   });
   this.$URL.on('keyup', null, 'return', function(){
      _urlbar.open( this.value );
   });

};

urlbar.prototype.open = function(URL){
   if(this.curr >= 0 ){
      this.history.length = this.curr + 1;
   }
   this.history.push(URL);
   this.curr++;

   this.$URL.val(URL);
   this.$forward.attr('disabled', 'disabled');
   if( this.curr > 0 ) this.$back.removeAttr('disabled');

   this.render(URL);
};

urlbar.prototype.forward = function(){
   if( this.history.length <= 0 || this.history.length <= this.curr + 1 ){
      return;
   }
   this.curr++;
   var URL = this.history[this.curr];

   this.$URL.val(URL);
   if( this.history.length <= this.curr + 1 ) {
      this.$forward.attr('disabled', 'disabled');
   }
   if( this.curr > 0 ) this.$back.removeAttr('disabled');

   this.render(URL);
};

urlbar.prototype.back = function(){
   if( this.curr <= 0 ) return;
   this.curr--;
   var URL = this.history[this.curr];

   this.$URL.val(URL);
   this.$forward.removeAttr('disabled');
   if( this.curr <= 0 ) this.$back.attr('disabled', 'disabled');

   this.render(URL);
};

urlbar.prototype.render = function(URL){
   var parsedURL;
   try {
      parsedURL = phiURL(URL);
   } catch(e) {
      return this.reportErrorHTML(
         _.escapeHTML(e.message)
      );
   }
   if( parsedURL.scheme !== 'area' ){
      return this.reportErrorHTML([
         'Sorry, the URL scheme ',
         parsedURL.scheme,
         ' is not supported.'
      ].join(''));
   }
   arealist(); // TODO: really use parsedURLs to determine rendering
};

urlbar.prototype.reportErrorHTML = function(errorHTML){
   $('#content').html(['
',
      '
',
      errorHTML,
   '
'].join(''));
};<commit_msg>handle “Go” button<commit_after>/* global $, _, phiURL, arealist, urlbar:true */

urlbar = function(){
   if (!(this instanceof urlbar)) return new urlbar();

   this.history = [];
   this.curr = -1;
};

urlbar.prototype.attach = function($element){
   var $urlbar = $element;
   var _urlbar = this;

   this.$URL     = $urlbar.find('#URL');
   this.$goToURL = $urlbar.find('#goToURL');
   this.$back    = $urlbar.find('#back');
   this.$forward = $urlbar.find('#forward');

   this.$back.on('click', function(){
      _urlbar.back();
   });
   this.$forward.on('click', function(){
      _urlbar.forward();
   });
   this.$URL.on('keyup', null, 'return', function(){
      _urlbar.open( this.value );
   });
   this.$goToURL.on('click', function(){
      _urlbar.open( _urlbar.$URL.val() );
   });

};

urlbar.prototype.open = function(URL){
   if(this.curr >= 0 ){
      this.history.length = this.curr + 1;
   }
   this.history.push(URL);
   this.curr++;

   this.$URL.val(URL);
   this.$forward.attr('disabled', 'disabled');
   if( this.curr > 0 ) this.$back.removeAttr('disabled');

   this.render(URL);
};

urlbar.prototype.forward = function(){
   if( this.history.length <= 0 || this.history.length <= this.curr + 1 ){
      return;
   }
   this.curr++;
   var URL = this.history[this.curr];

   this.$URL.val(URL);
   if( this.history.length <= this.curr + 1 ) {
      this.$forward.attr('disabled', 'disabled');
   }
   if( this.curr > 0 ) this.$back.removeAttr('disabled');

   this.render(URL);
};

urlbar.prototype.back = function(){
   if( this.curr <= 0 ) return;
   this.curr--;
   var URL = this.history[this.curr];

   this.$URL.val(URL);
   this.$forward.removeAttr('disabled');
   if( this.curr <= 0 ) this.$back.attr('disabled', 'disabled');

   this.render(URL);
};

urlbar.prototype.render = function(URL){
   var parsedURL;
   try {
      parsedURL = phiURL(URL);
   } catch(e) {
      return this.reportErrorHTML(
         _.escapeHTML(e.message)
      );
   }
   if( parsedURL.scheme !== 'area' ){
      return this.reportErrorHTML([
         'Sorry, the URL scheme ',
         parsedURL.scheme,
         ' is not supported.'
      ].join(''));
   }
   arealist(); // TODO: really use parsedURLs to determine rendering
};

urlbar.prototype.reportErrorHTML = function(errorHTML){
   $('#content').html(['
',
      '
',
      errorHTML,
   '
'].join(''));
};<|endoftext|>


<commit_before>/*
Graphical Module BBH1 Building Block Histogram.

This module has all functionalities for graphical display of user data.

Module Dependencies: d3, THREE, BBMathematics, BBStatistics.

*/
define( [ 'd3', 'THREE' ], function( d3, THREE ){
  "use strict";

  // Object Constructor BBH1 Building Block Histogram 1D.
  function BBTH1( name, title, nbinsx, xmin, xmax ){
    this.fDimension = 1; // Dimension of the plot data.
    this.name = name;
    this.title = title;
    this.nbinsx = nbinsx;
    this.xmin = xmin;
    this.xmax = xmax;
    this.rawData = []; // data array filled by Fill function.
    this.freqData = new Array( nbinsx + 2 ); // data array of frequencies for each bin. Two bins extra have been added, one for underflow and the another one for overflow.
  }

  BBTH1.prototype = {
    constructor: BBTH1,

    Fill: function( value ) {
      return this.rawData.push( value );
    },

    // Deattach data preparation
    Prepare: function(){
      var binxlow = this.xmin;
      var binwidth = ( this.xmax - this.xmin ) / this.nbinsx;
      var binxup = binxlow + binwidth;

      // Initialize frequencies to zero.
      for( var i = 0; i < this.freqData.length; i++ ){
        this.freqData[ i ] = 0;
      }

      // First fill array of frequencies for each bin: freqData.
      for( var i = 0; i < this.rawData.length; i++ ){
        binxlow = this.xmin;
        binxup = binxlow + binwidth;
        if( this.rawData[ i ] < this.xmin ) this.freqData[ 0 ] += 1; // Underflow.
        if( this.rawData[ i ] >= this.xmax ) this.freqData[ nbinsx + 1 ] += 1; // Overflow.
        // From index 1 til index nbinsx-2 of freqData Array.
        for( var j = 1; j < this.freqData.length - 1; j++ ){
          if( this.rawData[ i ] >= binxlow && this.rawData[ i ] < binxup ){
            this.freqData[ j ] += 1;
            break;
          }
          // Go to the next bin
          binxlow = binxup;
          binxup += binwidth;
        }
      }
      console.log(this.freqData);

    },

    Draw: function(){
      this.Prepare();
      var binwidth = ( this.xmax - this.xmin ) / this.nbinsx;
      // **************************************************************
      // Now start visualization
      // **************************************************************
      var margin = { top:20, right:40, bottom: 30, left:60 };
      var width = 640 -  margin.left - margin.right ;
      var height = 400 -  margin.top - margin.bottom ;
      var svg = d3.select( "#c1" ).append( "svg" )
        .attr( "width", height + margin.left + margin.right )
        .attr( "height", width + margin.top + margin.bottom );
      // Drawing a chart inside the svg
      var chart = svg.append( "g" )
        .attr( "transform", "translate(" + margin.left + "," + margin.top + ")" );
      // Scaling the data
      var xScale = d3.scale.linear().range( [ 0, width ] );
      var yScale = d3.scale.linear().range( [ height, 0 ] );
      // Defining the plot's domain
      xScale.domain([ this.xmin, this.xmax ]).nice();
      yScale.domain([ 0, d3.max( this.rawData ) ]).nice();

      var xAxis = d3.svg.axis()
        .scale( xScale )
        .orient( "bottom" );

      var yAxis = d3.svg.axis()
        .scale( yScale )
        .orient( "left" );

      var xAxisGroup = chart.append( "g" )
        .attr( "transform", "translate(0," + height + ")" );

      var yAxisGroup = chart.append( "g" )
        .attr( "transform", "translate(0," + height + ")" );

      xAxis( xAxisGroup );
      yAxis( yAxisGroup );
      // Definining text labels for axis.
      // Don't do it because that need to be accessed by the user

      // Displaying data
      this.freqData.forEach(function(d,i){
		        chart.append( "rect" )
          .attr( "x", function(){return (i-1)*xScale(binwidth);} )
          .attr( "width", xScale(binwidth)-2)
          .attr( "y", yScale(d) )
          .attr( "height", function(){return height-yScale(d);}  )
		        .attr("fill", "steelblue");
      });
    }, // Ends function Draw

  };

  return BBTH1;

}); // Ends Module BBTH1

<commit_msg>Dependence on BBTAxis added.<commit_after>/*
Graphical Module BBH1 Building Block Histogram.

This module has all functionalities for graphical display of user data.

Module Dependencies: d3, THREE, BBMathematics, BBStatistics.

*/
define( [ 'd3', 'THREE', 'BBTAxis' ], function( d3, THREE, BBTAxis ){
  "use strict";

  // Object Constructor BBH1 Building Block Histogram 1D.
  function BBTH1( name, title, nbinsx, xmin, xmax ){
    this.fDimension = 1; // Dimension of the plot data.
    this.name = name;
    this.title = title;
    this.nbinsx = nbinsx;
    this.xmin = xmin;
    this.xmax = xmax;
    this.rawData = []; // data array filled by Fill function.
    this.freqData = new Array( nbinsx + 2 ); // data array of frequencies for each bin. Two bins extra have been added, one for underflow and the another one for overflow.
  }

  BBTH1.prototype = {
    constructor: BBTH1,

    Fill: function( value ) {
      return this.rawData.push( value );
    },

    // Deattach data preparation
    Prepare: function(){
      var binxlow = this.xmin;
      var binwidth = ( this.xmax - this.xmin ) / this.nbinsx;
      var binxup = binxlow + binwidth;

      // Initialize frequencies to zero.
      for( var i = 0; i < this.freqData.length; i++ ){
        this.freqData[ i ] = 0;
      }

      // First fill array of frequencies for each bin: freqData.
      for( var i = 0; i < this.rawData.length; i++ ){
        binxlow = this.xmin;
        binxup = binxlow + binwidth;
        if( this.rawData[ i ] < this.xmin ) this.freqData[ 0 ] += 1; // Underflow.
        if( this.rawData[ i ] >= this.xmax ) this.freqData[ nbinsx + 1 ] += 1; // Overflow.
        // From index 1 til index nbinsx-2 of freqData Array.
        for( var j = 1; j < this.freqData.length - 1; j++ ){
          if( this.rawData[ i ] >= binxlow && this.rawData[ i ] < binxup ){
            this.freqData[ j ] += 1;
            break;
          }
          // Go to the next bin
          binxlow = binxup;
          binxup += binwidth;
        }
      }
      console.log(this.freqData);

    },

    Draw: function(){
      this.Prepare();
      var binwidth = ( this.xmax - this.xmin ) / this.nbinsx;
      // **************************************************************
      // Now start visualization
      // **************************************************************
      var margin = { top:20, right:40, bottom: 30, left:60 };
      var width = 640 -  margin.left - margin.right ;
      var height = 400 -  margin.top - margin.bottom ;
      var svg = d3.select( "#c1" ).append( "svg" )
        .attr( "width", height + margin.left + margin.right )
        .attr( "height", width + margin.top + margin.bottom );
      // Drawing a chart inside the svg
      var chart = svg.append( "g" )
        .attr( "transform", "translate(" + margin.left + "," + margin.top + ")" );
      // Scaling the data
      var xScale = d3.scale.linear().range( [ 0, width ] );
      var yScale = d3.scale.linear().range( [ height, 0 ] );
      // Defining the plot's domain
      xScale.domain([ this.xmin, this.xmax ]).nice();
      yScale.domain([ 0, d3.max( this.rawData ) ]).nice();

      var xAxis = d3.svg.axis()
        .scale( xScale )
        .orient( "bottom" );

      var yAxis = d3.svg.axis()
        .scale( yScale )
        .orient( "left" );

      var xAxisGroup = chart.append( "g" )
        .attr( "transform", "translate(0," + height + ")" );

      var yAxisGroup = chart.append( "g" )
        .attr( "transform", "translate(0," + height + ")" );

      xAxis( xAxisGroup );
      yAxis( yAxisGroup );
      // Definining text labels for axis.
      // Don't do it because that need to be accessed by the user

      // Displaying data
      this.freqData.forEach(function(d,i){
		        chart.append( "rect" )
          .attr( "x", function(){return (i-1)*xScale(binwidth);} )
          .attr( "width", xScale(binwidth)-2)
          .attr( "y", yScale(d) )
          .attr( "height", function(){return height-yScale(d);}  )
		        .attr("fill", "steelblue");
      });
    }, // Ends function Draw

  };

  return BBTH1;

}); // Ends Module BBTH1

<|endoftext|>