<commit_before>window.onload = function() {
  chrome.tabs.getSelected(null, function(tab) {
      tabUrl = tab.url;
  });

  request_handler('http://localhost:3000/users_folders', '.basket-list')
  request_handler('http://localhost:3000/users_friends', '.friend-list')

  $('.basket-list').on('click', '.basket-click', function(){
      sendData('new_link', tabUrl)
      console.log("Basket has been clicked!");
  })

  $('.friend-list-wrapper').on('click', '.friend-container', function(){
      //   sendData('sent_link', tabUrl)
      console.log('Friend has been clicked!');
  })
}

function request_handler(url, changed_div) {
  var req = new XMLHttpRequest();
  req.open('GET', url, true);
  req.onreadystatechange = function(){
      // successful response
      if (req.readyState==4 && req.status==200) {
          // console.log(req.responseText);
          document.querySelector(changed_div).innerHTML = (req.responseText);
      }
  }
  req.send();
}

function sendData(path, url){
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    chrome.tabs.sendMessage(tabs[0].id, {ping: "Send Page Info"}, function(response) {
      pageInfo = response.page_info;

      var id = $(this).attr('value');
      var req = new XMLHttpRequest();

      req.open("POST", 'http://localhost:3000/' + path);
      req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      req.send(JSON.stringify({url: url,
                              unqiueId: id,
                              pageInfo: pageInfo}));
    });
  });
};
<commit_msg>removed console.log tests<commit_after>window.onload = function() {
  chrome.tabs.getSelected(null, function(tab) {
      tabUrl = tab.url;
  });

  request_handler('http://localhost:3000/users_folders', '.basket-list')
  request_handler('http://localhost:3000/users_friends', '.friend-list')

  $('.basket-list').on('click', '.basket-click', function(){
    sendData('new_link', tabUrl)
  })

  $('.friend-list-wrapper').on('click', '.friend-container', function(){
    sendData('sent_link', tabUrl)
  })
}

function request_handler(url, changed_div) {
  var req = new XMLHttpRequest();
  req.open('GET', url, true);
  req.onreadystatechange = function(){
      // successful response
      if (req.readyState==4 && req.status==200) {
          // console.log(req.responseText);
          document.querySelector(changed_div).innerHTML = (req.responseText);
      }
  }
  req.send();
}

function sendData(path, url){
  chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    chrome.tabs.sendMessage(tabs[0].id, {ping: "Send Page Info"}, function(response) {
      pageInfo = response.page_info;

      var id = $(this).attr('value');
      var req = new XMLHttpRequest();

      req.open("POST", 'http://localhost:3000/' + path);
      req.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      req.send(JSON.stringify({url: url,
                              unqiueId: id,
                              pageInfo: pageInfo}));
    });
  });
};
<|endoftext|>


<commit_before>var totalHeight = 0; //Total height of the body of the popup
//Gets all windows
function getWindows(windowList,tabList,callback){
	if (typeof tabList=='function'){
		callback = tabList;
		tabList = null;
	}
	removeChildren(windowList);
	if (tabList==null){
		chrome.windows.getAll(function(windows){
			//loop through every window and append it ot the list
			windows.forEach(function(currentWindow,i){
				getTabs(currentWindow.id,i,function(li,ul){
					li.appendChild(ul);
					windowList.appendChild(li);
  					callback(li);
				});
			});
		});
	}
	else{
		tabList.forEach(function(tabs,i){
			setupTabs(tabs,i,function(li,ul){
				li.appendChild(ul);
				windowList.appendChild(li);
				callback(li);
			});
		});
	}

}
//Gets all tabs in a window and sets them up
function getTabs(windowId,windowIndex,callback){
	var windowTabs = []
	chrome.tabs.query({'windowId':windowId},function(tabs){
		tabs.forEach(function(currentTab){
			setupTab(currentTab,function(li){
				windowTabs.push(li);
			});
		});
		setupTabs(windowTabs,windowIndex,callback);
	});
}

//Sets up all tabs to be in their window elements
function setupTabs(tabs,windowIndex,callback){
	var li = document.createElement("li");
	var ul = document.createElement("ul");
	var windowName = document.createElement("span");
	var windowNum = document.createElement("span");
	var seperator = document.createElement("span");
	var tabCount = document.createElement("span");
	var tabWord = document.createElement("span");
	li.classList.add("window");
	li.classList.add("noselect");
	ul.classList.add("tabs");
	windowName.classList.add("windowName");
	windowName.textContent = "Window ";
	windowNum.classList.add("windowIndex");
	windowNum.textContent = (windowIndex+1).toString();
	seperator.textContent=" - "
	tabCount.classList.add("tabCount");
	tabCount.textContent = tabs.length.toString();
	tabWord.classList.add("tabWord");
	tabWord.textContent = (tabs.length>1 ? " tabs":" tab");
	li.appendChild(windowName);
	li.appendChild(windowNum);
	li.appendChild(seperator)
	li.appendChild(tabCount);
	li.appendChild(tabWord);
	tabs.forEach(function(currentTab){
		ul.appendChild(currentTab);
	});
	callback(li,ul);
}

function setupTab(currentTab,callback){
	var li = document.createElement("li");
	var textSpan = document.createElement("span");
	var closeButton = document.createElement("i");
	var pinButton = document.createElement("i");
	closeButton.classList.add("fa");
	closeButton.classList.add("fa-remove");
	closeButton.classList.add("close");
	closeButton.classList.add("noselect");
	closeButton.classList.add("pointer");
	pinButton.classList.add("fa");
	pinButton.classList.add("fa-thumb-tack");
	pinButton.classList.add("pin");
	pinButton.classList.add("noselect");
	closeButton.classList.add("pointer");
	if (currentTab.pinned){
		pinButton.classList.add("pinned");
	}
	li.classList.add("tab");
	li.classList.add("noselect");
	li.classList.add("pointer");
	//Setup favicon
	li.style.backgroundImage = "url(\'"+(currentTab.favIconUrl!==undefined && currentTab.favIconUrl!==null ? currentTab.favIconUrl:"img/default-favicon.png")+"\')";
	textSpan.classList.add("tabName");
	textSpan.textContent=currentTab.title;
	if (textSpan.textContent==""){
		textSpan.textContent="Untitled";
	}

	closeButton.onclick = function(event){
		event.preventDefault();
		event.stopPropagation();
		chrome.tabs.remove(currentTab.id);
		decrementTabCount(li);
		li.parentNode.removeChild(li);
	}
	pinButton.onclick = function(event){
		event.preventDefault();
		event.stopPropagation();
		if (currentTab.pinned || pinButton.classList.contains('pinned')){
			pinButton.classList.remove("pinned");
			chrome.tabs.update(currentTab.id, {'pinned':false});
		}
		else{
			pinButton.classList.add("pinned");
			chrome.tabs.update(currentTab.id, {'pinned':true});
		}
	}
	//Switches to the tab clicked
	li.onclick = function(event){
		event.stopPropagation();
		chrome.windows.getCurrent(function(resultWindow){
			if (currentTab.id!=resultWindow.id){
				chrome.windows.update(currentTab.windowId,{'focused':true});
			}
			chrome.tabs.update(currentTab.id,{'highlighted':true,'active':true});
		});
	}

	li.appendChild(textSpan);
	textSpan.appendChild(pinButton);
	textSpan.appendChild(closeButton);
	callback(li);
}

function decrementTabCount(tabLi){
	var ul = tabLi.parentNode;
	if (ul.tagName.toLowerCase()!='ul' || !ul.classList.contains("tabs")){
		throw "Not a tab li";
	}
	var li = ul.parentNode;
	if (li.tagName.toLowerCase()!='li' || !li.classList.contains("window")){
		throw "Not a tab li";
	}
	var tabCount = li.querySelector('span.tabCount');
	var num = parseInt(tabCount.textContent)-1;
	tabCount.textContent=num.toString();
	if (num===0){
		var windows = li.parentNode;
		if (windows.tagName.toLowerCase()!='ul' || windows.id!="windows"){
			throw "Not a tab li";
		}
		var index = li.querySelector("span.windowIndex");
		if (index==null){
			throw "Not a tab li";
		}
		index = parseInt(index.textContent);
		decrementWindowCount(li.parentNode,index);
		windows.removeChild(li);
	}
}
//Decremeent every window with a lower number than it
function decrementWindowCount(windowList,minWindow){
	Array.prototype.slice.call(windowList.childNodes).forEach(function(child){
		if (child.tagName.toLowerCase()!='li' || !child.classList.contains("window")){
			return;
		}
		Array.prototype.slice.call(child.childNodes).forEach(function(child2){
			if (child2.tagName.toLowerCase()!='span' || !child2.classList.contains("windowIndex")){
				return;
			}
			if (parseInt(child2.textContent)>minWindow){
				child2.textContent=(parseInt(child2.textContent)-1).toString();
			}
		});
	});
}

function removeChildren(element){
	Array.prototype.slice.call(element.childNodes).forEach(function(child){
		element.removeChild(child);
	})
}

function createSearchableWindows(callback){
	var result = [];
	chrome.windows.getAll(function(windows){
		var tabs = [];
		windows.forEach(function(currentWindow,i){
			getTabs(currentWindow.id,i,function(li,ul){
				tabs = Array.prototype.slice.call(ul.childNodes);
				result.push(tabs);
				if (i==windows.length-1){
					callback(result);
				}
			});
		});
	});
}
function search(query,windows,callback){
	windows = windows.slice(); //Clone the JSON object so we don't modify the origional
	windows.forEach(function(tabs,i){
		matchedTabs = [];
		tabs.forEach(function(currentTab){
			if (currentTab.textContent.toLowerCase().indexOf(query.toLowerCase())>-1)
				matchedTabs.push(currentTab);
		});
		windows[i] = matchedTabs;
	});
	callback(windows);
}
function setHeights(tabs){
	var body = document.getElementsByTagName("body")[0];
	var html = document.getElementsByTagName("html")[0];
	totalHeight+=tabs.clientHeight;
	var height = 600+"px";
	if (totalHeight<600){
		height = totalHeight+"px";
	}
	html.style.height = height;
	body.style.height = height;
}
document.addEventListener('DOMContentLoaded', function() {
	var mainList = document.getElementById("windows");
	var filterInput = document.getElementById("search");
	getWindows(mainList,setHeights);
	filterInput.oninput = function(){
		createSearchableWindows(function(result){
			search(filterInput.value,result,function(windows){
				totalHeight = 0;
				getWindows(mainList, windows, setHeights);
			});
		});
	};
});<commit_msg>Recalculate heights when tabs close<commit_after>var totalHeight = 0; //Total height of the body of the popup
//Gets all windows
function getWindows(windowList,tabList,callback){
	if (typeof tabList=='function'){
		callback = tabList;
		tabList = null;
	}
	removeChildren(windowList);
	if (tabList==null){
		chrome.windows.getAll(function(windows){
			//loop through every window and append it ot the list
			windows.forEach(function(currentWindow,i){
				getTabs(currentWindow.id,i,function(li,ul){
					li.appendChild(ul);
					windowList.appendChild(li);
  					callback(li);
				});
			});
		});
	}
	else{
		tabList.forEach(function(tabs,i){
			setupTabs(tabs,i,function(li,ul){
				li.appendChild(ul);
				windowList.appendChild(li);
				callback(li);
			});
		});
	}

}
//Gets all tabs in a window and sets them up
function getTabs(windowId,windowIndex,callback){
	var windowTabs = []
	chrome.tabs.query({'windowId':windowId},function(tabs){
		tabs.forEach(function(currentTab){
			setupTab(currentTab,function(li){
				windowTabs.push(li);
			});
		});
		setupTabs(windowTabs,windowIndex,callback);
	});
}

//Sets up all tabs to be in their window elements
function setupTabs(tabs,windowIndex,callback){
	var li = document.createElement("li");
	var ul = document.createElement("ul");
	var windowName = document.createElement("span");
	var windowNum = document.createElement("span");
	var seperator = document.createElement("span");
	var tabCount = document.createElement("span");
	var tabWord = document.createElement("span");
	li.classList.add("window");
	li.classList.add("noselect");
	ul.classList.add("tabs");
	windowName.classList.add("windowName");
	windowName.textContent = "Window ";
	windowNum.classList.add("windowIndex");
	windowNum.textContent = (windowIndex+1).toString();
	seperator.textContent=" - "
	tabCount.classList.add("tabCount");
	tabCount.textContent = tabs.length.toString();
	tabWord.classList.add("tabWord");
	tabWord.textContent = (tabs.length>1 ? " tabs":" tab");
	li.appendChild(windowName);
	li.appendChild(windowNum);
	li.appendChild(seperator)
	li.appendChild(tabCount);
	li.appendChild(tabWord);
	tabs.forEach(function(currentTab){
		ul.appendChild(currentTab);
	});
	callback(li,ul);
}

function setupTab(currentTab,callback){
	var li = document.createElement("li");
	var textSpan = document.createElement("span");
	var closeButton = document.createElement("i");
	var pinButton = document.createElement("i");
	closeButton.classList.add("fa");
	closeButton.classList.add("fa-remove");
	closeButton.classList.add("close");
	closeButton.classList.add("noselect");
	closeButton.classList.add("pointer");
	pinButton.classList.add("fa");
	pinButton.classList.add("fa-thumb-tack");
	pinButton.classList.add("pin");
	pinButton.classList.add("noselect");
	closeButton.classList.add("pointer");
	if (currentTab.pinned){
		pinButton.classList.add("pinned");
	}
	li.classList.add("tab");
	li.classList.add("noselect");
	li.classList.add("pointer");
	//Setup favicon
	li.style.backgroundImage = "url(\'"+(currentTab.favIconUrl!==undefined && currentTab.favIconUrl!==null ? currentTab.favIconUrl:"img/default-favicon.png")+"\')";
	textSpan.classList.add("tabName");
	textSpan.textContent=currentTab.title;
	if (textSpan.textContent==""){
		textSpan.textContent="Untitled";
	}

	closeButton.onclick = function(event){
		event.preventDefault();
		event.stopPropagation();
		chrome.tabs.remove(currentTab.id);
		decrementTabCount(li);
		li.parentNode.removeChild(li);
	}
	pinButton.onclick = function(event){
		event.preventDefault();
		event.stopPropagation();
		if (currentTab.pinned || pinButton.classList.contains('pinned')){
			pinButton.classList.remove("pinned");
			chrome.tabs.update(currentTab.id, {'pinned':false});
		}
		else{
			pinButton.classList.add("pinned");
			chrome.tabs.update(currentTab.id, {'pinned':true});
		}
	}
	//Switches to the tab clicked
	li.onclick = function(event){
		event.stopPropagation();
		chrome.windows.getCurrent(function(resultWindow){
			if (currentTab.id!=resultWindow.id){
				chrome.windows.update(currentTab.windowId,{'focused':true});
			}
			chrome.tabs.update(currentTab.id,{'highlighted':true,'active':true});
		});
	}

	li.appendChild(textSpan);
	textSpan.appendChild(pinButton);
	textSpan.appendChild(closeButton);
	callback(li);
}

function decrementTabCount(tabLi){
	var ul = tabLi.parentNode;
	if (ul.tagName.toLowerCase()!='ul' || !ul.classList.contains("tabs")){
		throw "Not a tab li";
	}
	var li = ul.parentNode;
	if (li.tagName.toLowerCase()!='li' || !li.classList.contains("window")){
		throw "Not a tab li";
	}
	var tabCount = li.querySelector('span.tabCount');
	var num = parseInt(tabCount.textContent)-1;
	tabCount.textContent=num.toString();
	var windows = li.parentNode;
	if (windows.tagName.toLowerCase()!='ul' || windows.id!="windows"){
		throw "Not a tab li";
	}
	if (num===0){
		var index = li.querySelector("span.windowIndex");
		if (index==null){
			throw "Not a tab li";
		}
		index = parseInt(index.textContent);
		decrementWindowCount(li.parentNode,index);
		windows.removeChild(li);
	}
	totalHeight = 0;
	Array.prototype.slice.call(windows.childNodes).forEach(function(child){
		setHeights(child);
	});
}
//Decremeent every window with a lower number than it
function decrementWindowCount(windowList,minWindow){
	Array.prototype.slice.call(windowList.childNodes).forEach(function(child){
		if (child.tagName.toLowerCase()!='li' || !child.classList.contains("window")){
			return;
		}
		Array.prototype.slice.call(child.childNodes).forEach(function(child2){
			if (child2.tagName.toLowerCase()!='span' || !child2.classList.contains("windowIndex")){
				return;
			}
			if (parseInt(child2.textContent)>minWindow){
				child2.textContent=(parseInt(child2.textContent)-1).toString();
			}
		});
	});
}

function removeChildren(element){
	Array.prototype.slice.call(element.childNodes).forEach(function(child){
		element.removeChild(child);
	});
}

function createSearchableWindows(callback){
	var result = [];
	chrome.windows.getAll(function(windows){
		var tabs = [];
		windows.forEach(function(currentWindow,i){
			getTabs(currentWindow.id,i,function(li,ul){
				tabs = Array.prototype.slice.call(ul.childNodes);
				result.push(tabs);
				if (i==windows.length-1){
					callback(result);
				}
			});
		});
	});
}
function search(query,windows,callback){
	windows = windows.slice(); //Clone the JSON object so we don't modify the origional
	windows.forEach(function(tabs,i){
		matchedTabs = [];
		tabs.forEach(function(currentTab){
			if (currentTab.textContent.toLowerCase().indexOf(query.toLowerCase())>-1)
				matchedTabs.push(currentTab);
		});
		windows[i] = matchedTabs;
	});
	callback(windows);
}
function setHeights(tabs){
	var body = document.getElementsByTagName("body")[0];
	var html = document.getElementsByTagName("html")[0];
	totalHeight+=tabs.clientHeight;
	var height = 600+"px";
	if (totalHeight<600){
		height = totalHeight+"px";
	}
	html.style.height = height;
	body.style.height = height;
}
document.addEventListener('DOMContentLoaded', function() {
	var mainList = document.getElementById("windows");
	var filterInput = document.getElementById("search");
	getWindows(mainList,setHeights);
	filterInput.oninput = function(){
		createSearchableWindows(function(result){
			search(filterInput.value,result,function(windows){
				totalHeight = 0;
				getWindows(mainList, windows, setHeights);
			});
		});
	};
});<|endoftext|>


<commit_before>var $content;
var $publish;
var $url;

function publish(content, font) {
	if (content.trim() == "") {
		return;
	}

	$publish.classList.add('disabled');
	$publish.value = "Publishing...";
	$publish.disabled = true;

	var http = new XMLHttpRequest();
	var url = "https://write.as/api/";
	var params = "w=" + encodeURIComponent(content) + "&font=" + font;
	http.open("POST", url, true);

	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("User-Agent", "Write.as Chrome Extension v1.0");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");

	http.onreadystatechange = function() { //Call a function when the state changes.
		if (http.readyState == 4) {
			$publish.classList.remove('disabled');
			$publish.value = "Publish";
			$publish.disabled = false;

			if (http.status == 200) {
				$publish.style.display = 'none';

				data = http.responseText.split("\n");
				// Pull out data parts
				url = data[0];
				id = url.substr(url.lastIndexOf("/")+1);
				editToken = data[1];

				document.getElementById("publish-holder").style.display = 'none';
				document.getElementById("result-holder").style.display = 'inline';

				$url = document.getElementById("url");
				$url.value = url;
				var $urlLink = document.getElementById("url-link");
				$urlLink.href = url;

				console.log("writeas add " + id + " " + editToken);
			} else {
				alert("Failed to post. Please try again.");
			}
		}
	}
	http.send(params);
}

var H = {
	save: function($el, key) {
		localStorage.setItem(key, $el.value);
	},
	load: function($el, key) {
		$el.value = localStorage.getItem(key);
	},
};

document.addEventListener('DOMContentLoaded', function() {
	$content = document.getElementById("content");
	$publish = document.getElementById("publish");
	$url = document.getElementById("url");
	var fontRadios = document.postForm.font;

	chrome.tabs.executeScript({
	  code: "window.getSelection().toString();"
	}, function(selection) {
	  if (typeof selection !== 'undefined') {
	    $content.value = selection[0];
	  }
	  // load previous draft
	  if ($content.value == "") {
	    H.load($content, 'ext-draft');
	  }
	});

	// focus on the paste field
	$content.focus();

	// bind publish action
	$publish.addEventListener('click', function(e) {
		e.preventDefault();
		publish($content.value, fontRadios.value);
	});
	$content.addEventListener('keydown', function(e){
		if (e.ctrlKey && e.keyCode == 13) {
			e.preventDefault();
			publish($content.value, fontRadios.value);
		}
	});

	// bind URL select-all action
	$url.addEventListener('focus', function(e) {
		e.preventDefault();
		this.select();
	});

	// load font setting
	H.load(fontRadios, 'font');
	$content.className = fontRadios.value;
	// bind font changing action
	for(var i = 0; i < fontRadios.length; i++) {
		fontRadios[i].onclick = function() {
		    $content.className = this.value;
		    H.save(fontRadios, 'font');
		};
	}
});
<commit_msg>Clean up non-working code and logs<commit_after>var $content;
var $publish;
var $url;

function publish(content, font) {
	if (content.trim() == "") {
		return;
	}

	$publish.classList.add('disabled');
	$publish.value = "Publishing...";
	$publish.disabled = true;

	var http = new XMLHttpRequest();
	var url = "https://write.as/api/";
	var params = "w=" + encodeURIComponent(content) + "&font=" + font;
	http.open("POST", url, true);

	//Send the proper header information along with the request
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

	http.onreadystatechange = function() {
		if (http.readyState == 4) {
			$publish.classList.remove('disabled');
			$publish.value = "Publish";
			$publish.disabled = false;

			if (http.status == 200) {
				$publish.style.display = 'none';

				data = http.responseText.split("\n");
				// Pull out data parts
				url = data[0];
				id = url.substr(url.lastIndexOf("/")+1);
				editToken = data[1];

				document.getElementById("publish-holder").style.display = 'none';
				document.getElementById("result-holder").style.display = 'inline';

				$url = document.getElementById("url");
				$url.value = url;
				var $urlLink = document.getElementById("url-link");
				$urlLink.href = url;
			} else {
				alert("Failed to post. Please try again.");
			}
		}
	}
	http.send(params);
}

var H = {
	save: function($el, key) {
		localStorage.setItem(key, $el.value);
	},
	load: function($el, key) {
		$el.value = localStorage.getItem(key);
	},
};

document.addEventListener('DOMContentLoaded', function() {
	$content = document.getElementById("content");
	$publish = document.getElementById("publish");
	$url = document.getElementById("url");
	var fontRadios = document.postForm.font;

	chrome.tabs.executeScript({
	  code: "window.getSelection().toString();"
	}, function(selection) {
	  if (typeof selection !== 'undefined') {
	    $content.value = selection[0];
	  }
	  // load previous draft
	  if ($content.value == "") {
	    H.load($content, 'ext-draft');
	  }
	});

	// focus on the paste field
	$content.focus();

	// bind publish action
	$publish.addEventListener('click', function(e) {
		e.preventDefault();
		publish($content.value, fontRadios.value);
	});
	$content.addEventListener('keydown', function(e){
		if (e.ctrlKey && e.keyCode == 13) {
			e.preventDefault();
			publish($content.value, fontRadios.value);
		}
	});

	// bind URL select-all action
	$url.addEventListener('focus', function(e) {
		e.preventDefault();
		this.select();
	});

	// load font setting
	H.load(fontRadios, 'font');
	$content.className = fontRadios.value;
	// bind font changing action
	for(var i = 0; i < fontRadios.length; i++) {
		fontRadios[i].onclick = function() {
		    $content.className = this.value;
		    H.save(fontRadios, 'font');
		};
	}
});
<|endoftext|>


<commit_before>/**
 * Print the current url
 */
chrome.tabs.query({ active: true, lastFocusedWindow: true},
    function(array_of_Tabs) { // Since there can only be one active tab in one active window,
                              //  the array has only one element
      var tab = array_of_Tabs[0];
      var url = tab.url;
      console.log("new Current " + url);

  });

/**
 *  add event listener to a group of buttuns
 */
var cpfValue = 3;
function setCpfValue(newCpf)
{
  cpfValue = newCpf;
}

function addOption(Data)
{
    var opt = document.createElement("option");
    var select = document.getElementById("data_fild");
    opt.value = Data;
    opt.innerHTML = Data;
    select.appendChild(opt);
}

function httpGet()
{
  cpf = document.getElementById("cpf_value").value;
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request
  xmlHttp.send( null );
  var jsonGet = JSON.parse(xmlHttp.responseText);

  console.log(jsonGet);
  addOption(jsonGet[0].startTime);
  //return xmlHttp.responseText;
}

function httpGetRaw()
{
  cpf = document.getElementById("cpf_value").value;
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request
  xmlHttp.send( null );

  console.log(xmlHttp.responseText);
  //return xmlHttp.responseText;
}

document.addEventListener('DOMContentLoaded', function () {
  //console.log(document.querySelector('button'));
  //document.querySelector('button').addEventListener('click', httpGet(cpfValue));
  var requestButton = document.getElementById('RequestJson');
  var requestButtonRaw = document.getElementById('RequestJsonRaw');

  requestButton.addEventListener("click", function(){
      httpGet();
  });

  requestButtonRaw.addEventListener("click", function(){
      httpGetRaw();
  });

});

// https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf=3<commit_msg>Adding auto fill of date<commit_after>/**
 * Print the current url
 */
chrome.tabs.query({ active: true, lastFocusedWindow: true},
    function(array_of_Tabs) { // Since there can only be one active tab in one active window,
                              //  the array has only one element
      var tab = array_of_Tabs[0];
      var url = tab.url;
      console.log("new Current " + url);

  });

/**
 *  add event listener to a group of buttuns
 */
var cpfValue = 3;
function setCpfValue(newCpf)
{
  cpfValue = newCpf;
}

function addOption(Data)
{
    var opt = document.createElement("option");
    var select = document.getElementById("data_fild");

    opt.value = Data;
    opt.innerHTML = Data;
    select.appendChild(opt);
}

function httpGet()
{
  cpf = document.getElementById("cpf_value").value;
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request
  xmlHttp.send( null );
  var jsonGet = JSON.parse(xmlHttp.responseText);

  var select = document.getElementById("data_fild");
  while (select.length > 0)
    select.remove(select.length-1);

  console.log(jsonGet.length);

  for (var classTime = 0; classTime < jsonGet.length; classTime++)
    addOption(jsonGet[classTime].startTime);

  //return xmlHttp.responseText;
}

function httpGetRaw()
{
  cpf = document.getElementById("cpf_value").value;
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request
  xmlHttp.send( null );

  console.log(xmlHttp.responseText);

  var select = document.getElementById("data_fild");
  while (select.length > 0)
    select.remove(select.length-1);

  //return xmlHttp.responseText;
}

document.addEventListener('DOMContentLoaded', function () {
  //console.log(document.querySelector('button'));
  //document.querySelector('button').addEventListener('click', httpGet(cpfValue));
  var requestButton = document.getElementById('RequestJson');
  var requestButtonRaw = document.getElementById('RequestJsonRaw');

  requestButton.addEventListener("click", function(){
      httpGet();
  });

  requestButtonRaw.addEventListener("click", function(){
      httpGetRaw();
  });

});

// https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf=3<|endoftext|>


<commit_before>/**
 * Print the current url
 */
chrome.tabs.query({ active: true, lastFocusedWindow: true},
    function(array_of_Tabs) { // Since there can only be one active tab in one active window,
                              //  the array has only one element
      var tab = array_of_Tabs[0];
      var url = tab.url;
      console.log("new Current " + url);

  });

/**
 *  add event listener to a group of buttuns
 */
var cpfValue = 3;
function setCpfValue(newCpf)
{
  cpfValue = newCpf;
}
var chooseData = ' '
function setChooseData(newData)
{
  chooseData = newData;
}

function addOption(Data)
{
    var opt = document.createElement("option");
    var select = document.getElementById("data_fild");

    opt.value = Data;
    opt.innerHTML = Data;
    select.appendChild(opt);
}
var jsonGet = '';
function httpGet()
{
  cpf = document.getElementById("cpf_value").value;
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request
  xmlHttp.send( null );
  jsonGet = JSON.parse(xmlHttp.responseText);

  var select = document.getElementById("data_fild");
  while (select.length > 0)
    select.remove(select.length-1);

  console.log(jsonGet);

  for (var classTime = 0; classTime < jsonGet.length; classTime++){
      var classTime2 = ((classTime < 10)? "0":"") + classTime;
      addOption(classTime2 + '-' + timeConverter(jsonGet[classTime].startTime));
  }

  if( jsonGet.length == 0)
    addOption("CPF Nao Encontrado");

  //return xmlHttp.responseText;
}

function httpGetRaw()
{
  cpf = document.getElementById("cpf_value").value;
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request
  xmlHttp.send( null );

  console.log(xmlHttp.responseText);

  var select = document.getElementById("data_fild");
  while (select.length > 0)
    select.remove(select.length-1);

  //return xmlHttp.responseText;
}

document.addEventListener('DOMContentLoaded', function () {

  var requestButton = document.getElementById('RequestJson');
  var requestButtonRaw = document.getElementById('RequestJsonRaw');
  var dates = document.getElementById("data_fild");

  dates.addEventListener("change", function() {
    console.log("Selected Data:");
    console.log(dates.value);
    if(dates.value == 'CPF Nao encontrado') return;
    var subDates = dates.value.split("-");
    var indexClass = parseInt(subDates[0]);
    classList = jsonGet[indexClass].students;
    console.log(indexClass)
    console.log("-- List Of Students --")
    var listInHtml = document.getElementById('stdList');

    while (listInHtml.hasChildNodes())
      listInHtml.removeChild(listInHtml.firstChild);

    //listInHtml.innerHTML = '-- List Of Students --';
    for(var stList = 0 ; stList < classList.length ; stList++ )
    {
      console.log(classList[stList].nome);
      var node = document.createElement("LI");
      var textnode = document.createTextNode(classList[stList].nome);
      node.appendChild(textnode);
      listInHtml.appendChild(node);
    }

  });

  addOption("- -   Digite seu CPF   - -");
  requestButton.addEventListener("click", function(){
      var listInHtml = document.getElementById('stdList');
      while (listInHtml.hasChildNodes())
        listInHtml.removeChild(listInHtml.firstChild);

      httpGet();
  });

  requestButtonRaw.addEventListener("click", function(){
    var listInHtml = document.getElementById('stdList');
    while (listInHtml.hasChildNodes())
      listInHtml.removeChild(listInHtml.firstChild);

      httpGetRaw();
  });

});

function timeConverter(UNIX_timestamp){
  var a = new Date(UNIX_timestamp);
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var year = a.getFullYear();
  var month = months[a.getMonth()];
  var date = a.getDate();
  var date2 = ((date<10) ? "0" : "")+ date;
  var hour = a.getHours();
  var hour2 = ((hour<10) ? "0" : "")+ hour;
  var min = a.getMinutes();
  var min2 = ((min<10) ? "0" : "")+ min;
  var sec = a.getSeconds();
  var sec2 = ((sec<10) ? "0" : "")+ sec;
  var time = date2 + ' ' + month + ' ' + year + ' ' + hour2 + ':' + min2 + ':' + sec2 ;
  return time;
}

// https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf=3<commit_msg>Adding blank<commit_after>/**
 * Print the current url
 */
chrome.tabs.query({ active: true, lastFocusedWindow: true},
    function(array_of_Tabs) { // Since there can only be one active tab in one active window,
                              //  the array has only one element
      var tab = array_of_Tabs[0];
      var url = tab.url;
      console.log("new Current " + url);

  });

/**
 *  add event listener to a group of buttuns
 */
var cpfValue = 3;
function setCpfValue(newCpf)
{
  cpfValue = newCpf;
}
var chooseData = ' '
function setChooseData(newData)
{
  chooseData = newData;
}

function addOption(Data)
{
    var opt = document.createElement("option");
    var select = document.getElementById("data_fild");

    opt.value = Data;
    opt.innerHTML = Data;
    select.appendChild(opt);
}
var jsonGet = '';
function httpGet()
{
  cpf = document.getElementById("cpf_value").value;
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request
  xmlHttp.send( null );
  jsonGet = JSON.parse(xmlHttp.responseText);

  var select = document.getElementById("data_fild");
  while (select.length > 0)
    select.remove(select.length-1);

  console.log(jsonGet);
  if( jsonGet.length == 0)
    addOption("CPF Nao Encontrado");
  else
    addOption("Selecione a Data");

  for (var classTime = 0; classTime < jsonGet.length; classTime++){
      var classTime2 = ((classTime < 10)? "0":"") + classTime;
      addOption(classTime2 + '-' + timeConverter(jsonGet[classTime].startTime));
  }

  //return xmlHttp.responseText;
}

function httpGetRaw()
{
  cpf = document.getElementById("cpf_value").value;
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open( "GET", "https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf="+cpf, false ); // false for synchronous request
  xmlHttp.send( null );

  console.log(xmlHttp.responseText);

  var select = document.getElementById("data_fild");
  while (select.length > 0)
    select.remove(select.length-1);

  //return xmlHttp.responseText;
}

document.addEventListener('DOMContentLoaded', function () {

  var requestButton = document.getElementById('RequestJson');
  var requestButtonRaw = document.getElementById('RequestJsonRaw');
  var dates = document.getElementById("data_fild");

  dates.addEventListener("change", function() {
    console.log("Selected Data:");
    console.log(dates.value);
    var listInHtml = document.getElementById('stdList');

    if(dates.value == 'CPF Nao encontrado') return;
    if(dates.value == "Selecione a Data")
      {
        while (listInHtml.hasChildNodes())
          listInHtml.removeChild(listInHtml.firstChild);
        return;
      };
    var subDates = dates.value.split("-");
    var indexClass = parseInt(subDates[0]);
    classList = jsonGet[indexClass].students;
    console.log(indexClass)
    console.log("-- List Of Students --")

    while (listInHtml.hasChildNodes())
      listInHtml.removeChild(listInHtml.firstChild);

    //listInHtml.innerHTML = '-- List Of Students --';
    for(var stList = 0 ; stList < classList.length ; stList++ )
    {
      console.log(classList[stList].nome);
      var node = document.createElement("LI");
      var textnode = document.createTextNode(classList[stList].nome);
      node.appendChild(textnode);
      listInHtml.appendChild(node);
    }

  });

  addOption("- -   Digite seu CPF   - -");
  requestButton.addEventListener("click", function(){
      var listInHtml = document.getElementById('stdList');
      while (listInHtml.hasChildNodes())
        listInHtml.removeChild(listInHtml.firstChild);

      httpGet();
  });

  requestButtonRaw.addEventListener("click", function(){
    var listInHtml = document.getElementById('stdList');
    while (listInHtml.hasChildNodes())
      listInHtml.removeChild(listInHtml.firstChild);

      httpGetRaw();
  });

});

function timeConverter(UNIX_timestamp){
  var a = new Date(UNIX_timestamp);
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var year = a.getFullYear();
  var month = months[a.getMonth()];
  var date = a.getDate();
  var date2 = ((date<10) ? "0" : "")+ date;
  var hour = a.getHours();
  var hour2 = ((hour<10) ? "0" : "")+ hour;
  var min = a.getMinutes();
  var min2 = ((min<10) ? "0" : "")+ min;
  var sec = a.getSeconds();
  var sec2 = ((sec<10) ? "0" : "")+ sec;
  var time = date2 + ' ' + month + ' ' + year + ' ' + hour2 + ':' + min2 + ':' + sec2 ;
  return time;
}

// https://ess-20171-presence-server.herokuapp.com/lesson/listByCpf?cpf=3<|endoftext|>


<commit_before>angular.module('app', [
  'ui.router',
  'app.main',
  'app.auth',
  'app.dash',
  'app.roadmaps',
  'app.browse',
  'app.node.creation'
  ])
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
  $urlRouterProvider.otherwise('/');
  $stateProvider
    //state for the main home page that signed-in and non-signed in users see
    .state('home', {
      url: '/',
      views: {
        'header': {
          templateUrl: 'app/main/main.header.html',
          controller: 'MainController'
        },
         'welcome': {
          templateUrl: 'app/main/main.welcome.html',
          controller: 'MainController'
        },
         'featured': {
          templateUrl: 'app/main/main.welcome.html',
          controller: 'MainController'
        },
        'content': {
          templateUrl: 'app/main/main.content.html',
          controller: 'MainController',
        },
        'footer': {
          templateUrl: 'app/main/main.footer.html',
          controller: 'MainController'
        }
      }
    })
    //state for sign-in
    .state('signin', {
      views: {
        'content': {
          templateUrl: 'app/auth/signin.html',
          controller: 'AuthController'
        },
        'header': {
          templateUrl: 'app/main/main.header.html',
          controller: 'MainController'
        },
        'footer': {
          templateUrl: 'app/main/main.footer.html',
          controller: 'MainController'
        }
      }
    })
    //state for sign-up
    .state('signup', {
      views: {
        'content': {
          templateUrl: 'app/auth/signup.html',
          controller: 'AuthController'
        },
        'header': {
          templateUrl: 'app/main/main.registration.html',
          controller: 'MainController'
        },
        'footer': {
          templateUrl: 'app/main/main.footer.html',
          controller: 'MainController'
        }
      }
    })
    //state for dashboard
    .state('dashboard', {
      url: '/dashboard',
      views: {
        'content': {
          templateUrl: 'app/progress/dashboard.html',
          controller: 'DashboardController'
        },
        'header': {
          templateUrl: 'app/main/main.userheader.html',
          controller: 'MainController'
        },
        'footer': {
          templateUrl: 'app/main/main.footer.html',
          controller: 'MainController'
          }
        }
    })
  //state for roadmap
  .state('roadmapTemplate', {
    url: '/roadmaps',
    views: {
      'content': {
        templateUrl: 'app/roadmaps/roadmaps.content.html',
        controller: 'RoadMapsController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'RoadMapsController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'RoadMapsController'
      }
    }
  }).
  state('roadmapCreationForm',{
    url: '/roadmapCreationForm',
    views: {
      'content': {
        templateUrl: 'app/roadmaps/roadmaps.creationForm.html',
        controller: 'RoadMapsController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'RoadMapsController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'RoadMapsController'
      }
    }
  })
  //state for a Node Creation Form
  .state('nodeCreationForm', {
    url: '/node-creation',
    views: {
      'content': {
        templateUrl: 'app/roadmaps/node.creation.html',
        controller: 'NodeCreationController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'RoadMapsController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'RoadMapsController'
      }
    }
  })
  //sample state
  .state('nodeCreationForm', {
    url: '/node-creation',
    views: {
      'content': {
        templateUrl: 'app/roadmaps/node.creation.html',
        controller: 'RoadMapsController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'RoadMapsController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'RoadMapsController'
      }
    }
  })
  //sample state
  .state('example', {
    url: '/example',
    views: {
      'signup': {
        templateUrl: 'app/auth/signup.html',
        controller: 'AuthController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'RoadMapsController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'RoadMapsController'
      }
    }
  })
  .state('browse', { //maybe rename as explore?
    url: '/browse',
    views: {
      'content': {
        templateUrl: 'app/browse/browse.html',
        controller: 'BrowseController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'MainController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'MainController'
      }
    }
  });
});<commit_msg>(feat) Build controller to submit new nodes to server.<commit_after>angular.module('app', [
  'ui.router',
  'app.main',
  'app.auth',
  'app.dash',
  'app.roadmaps',
  'app.browse',
  'app.node.creation'
  ])
.config(function($stateProvider, $urlRouterProvider, $httpProvider) {
  $urlRouterProvider.otherwise('/');
  $stateProvider
    //state for the main home page that signed-in and non-signed in users see
    .state('home', {
      url: '/',
      views: {
        'header': {
          templateUrl: 'app/main/main.header.html',
          controller: 'MainController'
        },
         'welcome': {
          templateUrl: 'app/main/main.welcome.html',
          controller: 'MainController'
        },
         'featured': {
          templateUrl: 'app/main/main.welcome.html',
          controller: 'MainController'
        },
        'content': {
          templateUrl: 'app/main/main.content.html',
          controller: 'MainController',
        },
        'footer': {
          templateUrl: 'app/main/main.footer.html',
          controller: 'MainController'
        }
      }
    })
    //state for sign-in
    .state('signin', {
      views: {
        'content': {
          templateUrl: 'app/auth/signin.html',
          controller: 'AuthController'
        },
        'header': {
          templateUrl: 'app/main/main.header.html',
          controller: 'MainController'
        },
        'footer': {
          templateUrl: 'app/main/main.footer.html',
          controller: 'MainController'
        }
      }
    })
    //state for sign-up
    .state('signup', {
      views: {
        'content': {
          templateUrl: 'app/auth/signup.html',
          controller: 'AuthController'
        },
        'header': {
          templateUrl: 'app/main/main.registration.html',
          controller: 'MainController'
        },
        'footer': {
          templateUrl: 'app/main/main.footer.html',
          controller: 'MainController'
        }
      }
    })
    //state for dashboard
    .state('dashboard', {
      url: '/dashboard',
      views: {
        'content': {
          templateUrl: 'app/progress/dashboard.html',
          controller: 'DashboardController'
        },
        'header': {
          templateUrl: 'app/main/main.userheader.html',
          controller: 'MainController'
        },
        'footer': {
          templateUrl: 'app/main/main.footer.html',
          controller: 'MainController'
          }
        }
    })
  //state for roadmap
  .state('roadmapTemplate', {
    url: '/roadmaps',
    views: {
      'content': {
        templateUrl: 'app/roadmaps/roadmaps.content.html',
        controller: 'RoadMapsController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'RoadMapsController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'RoadMapsController'
      }
    }
  }).
  state('roadmapCreationForm',{
    url: '/roadmapCreationForm',
    views: {
      'content': {
        templateUrl: 'app/roadmaps/roadmaps.creationForm.html',
        controller: 'RoadMapsController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'RoadMapsController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'RoadMapsController'
      }
    }
  })
  //state for a Node Creation Form
  .state('nodeCreationForm', {
    url: '/node-creation',
    views: {
      'content': {
        templateUrl: 'app/roadmaps/node.creation.html',
        controller: 'NodeCreationController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'RoadMapsController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'RoadMapsController'
      }
    }
  })
  //sample state
  .state('example', {
    url: '/example',
    views: {
      'signup': {
        templateUrl: 'app/auth/signup.html',
        controller: 'AuthController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'RoadMapsController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'RoadMapsController'
      }
    }
  })
  .state('browse', { //maybe rename as explore?
    url: '/browse',
    views: {
      'content': {
        templateUrl: 'app/browse/browse.html',
        controller: 'BrowseController'
      },
      'header': {
        templateUrl: 'app/main/main.userheader.html',
        controller: 'MainController'
      },
      'footer': {
        templateUrl: 'app/main/main.footer.html',
        controller: 'MainController'
      }
    }
  });
});<|endoftext|>


<commit_before>let app = angular.module('Norfolk-Flood',[]);

// User Input Controller:
app.controller('userIncomeController', ['$scope','$http', 'dataService', function($scope,$http, dataService){

  $scope.simulatedData = dataService.getSimData(); //income, response
  $scope.realData = dataService.getRealData();
  $scope.rangeData = dataService.getIncomeRanges();
  $scope.incomeSubmitted = false;

  $scope.getIncomeImpact = function() {
    $scope.toCost = function (income, lossFactor) {
      return parseFloat(income).toFixed(0) * ( parseFloat(lossFactor) / 100 );
    };
    //Identify income range and calculate flood impact values
    $scope.incomeSubmitted = true;
    console.log($scope.incomeSubmitted);

    var incomeLevel = parseFloat($scope.incomeLevel);
    var incomeRange = [];

    if( incomeLevel > 999999 ) {
      incomeRange = [$scope.rangeData[8]];
    } else {
      incomeRange = $scope.rangeData.filter( function(range) {
        return incomeLevel >= range['min'] && incomeLevel <= range['maxUpTo'];
      });
    }
    console.log("lookie");
    console.log(incomeRange);
    console.log(incomeRange[0]['0m']);
    console.log(parseFloat( incomeRange[0]['0m'] ));
    $scope.outcomes = [
      {
        level: '0.00',
        levelName: 'NONE',
        cost: $scope.toCost( $scope.incomeLevel, incomeRange[0]['0m'] ),
        message: 'If the sea level stays the same, you are predicted to lose $' + $scope.toCost( $scope.incomeLevel, incomeRange[0]['0m'] )
      },
      {
        level: '0.50',
        levelName: 'LOW',
        cost: $scope.toCost( $scope.incomeLevel, incomeRange[0]['5m'] ),
        message: 'In the worst-case seal level rise scenario, you are predicted to lose $' + $scope.toCost( $scope.incomeLevel, incomeRange[0]['5m'] )
      },
      {
        level: '0.75',
        levelName: 'HIGH',
        cost: $scope.toCost( $scope.incomeLevel, incomeRange[0]['75m'] ),
        message: 'In the worst-case sea level rise scenario, you are predicted to lose $' + $scope.toCost( $scope.incomeLevel, incomeRange[0]['75m'] )
      }
    ];
  };

}]);

app.factory('dataService', ['$http',function($http){
  var simData = [];
  var realData = [];
  var rangeData = [];

  return{
    getIncomeRanges : function(){
      $http({
        method: 'GET',
        url: '/income'
      }).then(function(response){
        console.log("income ranges from server",response);
        angular.copy(response.data,rangeData);
      });
      return rangeData;
    },
    getSimData : function(){
      $http({
        method: 'GET',
        url: '/sim'
      }).then(function(response){
        console.log("simulated data from server",response);
        angular.copy(response.data,simData);
      });
      return simData;
    },
    getRealData : function(){
      $http({
        method: 'GET',
        url: '/real'
      }).then(function(response){
        console.log("real data from server",response);
        angular.copy(response.data,realData);
      });
      return realData;
    }
  };

}]);
<commit_msg>troubleshooting angular logic<commit_after>let app = angular.module('Norfolk-Flood',[]);

// User Input Controller:
app.controller('userIncomeController', ['$scope','$http', 'dataService', function($scope,$http, dataService){

  $scope.simulatedData = dataService.getSimData(); //income, response
  $scope.realData = dataService.getRealData();
  $scope.rangeData = dataService.getIncomeRanges();
  $scope.incomeSubmitted = false;

  $scope.getIncomeImpact = function() {
    $scope.toCost = function (income, lossFactor) {
      return (parseFloat(income) * ( parseFloat(lossFactor) / 100 )).toFixed(0);
    };
    //Identify income range and calculate flood impact values
    $scope.incomeSubmitted = true;
    console.log($scope.incomeSubmitted);

    var incomeLevel = parseFloat($scope.incomeLevel);
    var incomeRange = [];

    if( incomeLevel > 999999 ) {
      incomeRange = [$scope.rangeData[8]];
    } else {
      incomeRange = $scope.rangeData.filter( function(range) {
        return incomeLevel >= range['min'] && incomeLevel <= range['maxUpTo'];
      });
    }
    console.log("lookie");
    console.log(incomeRange);
    console.log(incomeRange[0]['0m']);
    console.log(parseFloat( incomeRange[0]['0m'] ));
    $scope.outcomes = [
      {
        level: '0.00',
        levelName: 'NONE',
        cost: $scope.toCost( $scope.incomeLevel, incomeRange[0]['0m'] ),
        message: 'If the sea level stays the same, you are predicted to lose $' + $scope.toCost( $scope.incomeLevel, incomeRange[0]['0m'] )
      },
      {
        level: '0.50',
        levelName: 'LOW',
        cost: $scope.toCost( $scope.incomeLevel, incomeRange[0]['5m'] ),
        message: 'In the worst-case seal level rise scenario, you are predicted to lose $' + $scope.toCost( $scope.incomeLevel, incomeRange[0]['5m'] )
      },
      {
        level: '0.75',
        levelName: 'HIGH',
        cost: $scope.toCost( $scope.incomeLevel, incomeRange[0]['75m'] ),
        message: 'In the worst-case sea level rise scenario, you are predicted to lose $' + $scope.toCost( $scope.incomeLevel, incomeRange[0]['75m'] )
      }
    ];
  };

}]);

app.factory('dataService', ['$http',function($http){
  var simData = [];
  var realData = [];
  var rangeData = [];

  return{
    getIncomeRanges : function(){
      $http({
        method: 'GET',
        url: '/income'
      }).then(function(response){
        console.log("income ranges from server",response);
        angular.copy(response.data,rangeData);
      });
      return rangeData;
    },
    getSimData : function(){
      $http({
        method: 'GET',
        url: '/sim'
      }).then(function(response){
        console.log("simulated data from server",response);
        angular.copy(response.data,simData);
      });
      return simData;
    },
    getRealData : function(){
      $http({
        method: 'GET',
        url: '/real'
      }).then(function(response){
        console.log("real data from server",response);
        angular.copy(response.data,realData);
      });
      return realData;
    }
  };

}]);
<|endoftext|>


<commit_before>
// when-scrolled module.
/*
angular.module('scroll', []).directive('whenScrolled', function() {
  return function(scope, elm, attr) {
    var raw = elm[0];

    elm.bind('scroll', function() {
      if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
        scope.$apply(attr.whenScrolled);
      }
    });
  };
});

*/

// Create application module.
var app = angular.module('roderick', []);

// Add a controller to it.
app.controller('DictCtrl', function($scope, $http) {
  if ($scope.entries == undefined) {
    $scope.entries = [];
  }
  if ($scope.counter == undefined) {
    $scope.counter = 1;
  }

  // A scope function to load the data.
  $scope.loadData = function () {
    $http.get('/words/' + $scope.counter + '.json').success(function(data) {
      $scope.entries = $scope.entries.concat(data)
      $scope.counter += 1;
      console.log($scope.counter);
    });
  };

  $scope.loadData();
});
app.directive('scroller', function () {
  return {
    restrict: 'A',
    link: function (scope, elem, attrs) {
      elem.bind('scroll', function () {
        console.log("I was scrolled");
      });
    }
  };
});
<commit_msg>scrolling!<commit_after>
// when-scrolled module.
/*
angular.module('scroll', []).directive('whenScrolled', function() {
  return function(scope, elm, attr) {
    var raw = elm[0];

    elm.bind('scroll', function() {
      if (raw.scrollTop + raw.offsetHeight >= raw.scrollHeight) {
        scope.$apply(attr.whenScrolled);
      }
    });
  };
});

*/

// Create application module.
var app = angular.module('roderick', []);

// Add a controller to it.
app.controller('DictCtrl', function($scope, $http) {
  if ($scope.entries == undefined) {
    $scope.entries = [];
  }
  if ($scope.counter == undefined) {
    $scope.counter = 1;
  }

  // A scope function to load the data.
  $scope.loadData = function () {
    $http.get('/words/' + $scope.counter + '.json').success(function(data) {
      $scope.entries = $scope.entries.concat(data)
      $scope.counter += 1;
      console.log($scope.counter);
    });
  };

  $scope.loadData();
});

app.directive('scroller', function () {
  return {
    restrict: 'A',
    link: function (scope, elem, attrs) {
      elem.bind('scroll', function () {
        rawElement = elem[0];
        if ((rawElement.scrollTop + rawElement.offsetHeight+5) >= rawElement.scrollHeight) {
          scope.$apply('loadData()');
        }
      });
    }
  };
});
<|endoftext|>


<commit_before>var AppRouter = Backbone.Router.extend({

    routes: {
		"": "homeRoute",
		"removed": "homeRoute",

		"admin/:slug": "mapAdminRoute",
		"admin/:slug/:view": "mapAdminRoute",
		"admin/:slug/:view/:x,:y": "mapAdminRoute",
		"admin/:slug/:view/:x,:y/:zoom": "mapAdminRoute",

		":slug": "mapRoute",
		":slug/:view": "mapRoute",
		":slug/:view/:x,:y": "mapRoute",
		":slug/:view/:x,:y/:zoom": "mapRoute",
    },

    initialize: function()
    {
		var self = this;

		this.firstLoad = true;
		this.pointCollections = {};
		this.timeBasedPointCollections = {};

		this.settingsVisible = false;
		this.graphVisible = false;
		this.dataLibraryVisible = false;
		this.chatVisible = false;

		this.vent = _.extend({}, Backbone.Events);
		this.vent.bind('mapViewReady', function() {
			self.initMapLayers();
		});

		var embed = this.getURLParameter('embed');
		if (embed == 1) {
			console.log('embed: ' + embed);
			this.renderAsEmbed();
		}
    },

    mapRoute: function(slug, view, x, y, zoom)
    {
		var mapView;
		if (view) {
			this.setupRoute = view == 'setup';
			if (!this.setupRoute) {
				mapView = view;
			} else {
				$('#app').empty();
			}
		}
		var center;
		if (x != undefined && y != undefined) {
			x = parseFloat(x);
			y = parseFloat(y);
			if (!isNaN(x) && !isNaN(y)) {
				center = [x, y];
			}
		}

    	console.log(slug, 'mapView:', mapView, 'center:', center, 'zoom:', zoom);
		this.loadAndInitMap(slug, mapView, center, zoom);
    },

    mapAdminRoute: function(slug, view, x, y, zoom)
    {
    	this.adminRoute = true;
    	this.mapRoute(slug, view, x, y, zoom);
    },

    genMapURI: function(view, opts)
    {
    	var uri = (this.adminRoute ? 'admin/' : '')
    		+ this.mapInfo.publicslug + (view ? '/' + view : '');
    	if (opts) {
	    	if (opts.x != undefined) {
		    	uri += '/%(x)s,%(y)s';
	    	}
	    	if (opts.zoom != undefined) {
	    		uri += '/%(zoom)s';
	    	}
    	}
    	return uri.format(opts);
    },

	mainRoute: function(admin, slug, view, query)
	{
		var mapView = '';
		if (view) {
			view = view.split('/')[1];
			this.setupRoute = view == 'setup';
			if (!this.setupRoute) {
				mapView = view;
			} else {
				$('#app').empty();
			}
		}
		this.adminRoute = admin;
		console.log('mainRoute', slug, mapView, query);
		this.loadAndInitMap(slug, mapView);
	},

	homeRoute: function()
	{

		if (this.firstLoad) {
			this.firstLoad = false;
			this.homepageView = new HomepageView();
	        $('#home').append(this.homepageView.render().el);
		} else {
			window.location.reload(true);
		}
	},

    initMapView: function(mapView, center, zoom)
    {
		var self = this;

		if (this.mapView) {
			this.mapView.remove();
			this.mapView = null;
		}

		switch (mapView) {
			case 'map':
				var viewClass = MapOLView;
				break;
			case 'globe':
				var viewClass = MapGLView;
				break;
		}

		var visibleMapArea = DEFAULT_MAP_AREA;
		if (this.mapInfo.initialArea.center.length) {
			visibleMapArea.center = this.mapInfo.initialArea.center;
		}
		if (this.mapInfo.initialArea.zoom != undefined) {
			visibleMapArea.zoom = this.mapInfo.initialArea.zoom;
		}
		if (center) {
			visibleMapArea.center = center;
		}
		if (zoom) {
			visibleMapArea.zoom = zoom;
		}

        this.mapView = new viewClass({
			vent: self.vent,
			visibleMapArea: visibleMapArea
		});
		this.mapView.uriViewName = mapView;

		var mapEl = this.mapView.render().el;
		$('#app').append(mapEl);
		this.mapView.start();

        var snap = $('

');
		$(mapEl).append(snap);

        this.dataInfoView = new DataInfoView({vent: this.vent});
		$(mapEl).append(this.dataInfoView.render().el);
    },

	isMapAdmin: function()
	{
		return this.adminRoute && this.mapInfo.admin;
	},

	render: function(mapView)
	{
		var self = this;

		window.document.title = this.mapInfo.title + ' – GeoSense';

 		this.headerView = new HeaderView({vent: this.vent, title: this.mapInfo.title});
        $('#app').append(this.headerView.render().el);

		this.sideBarView = new SideBarView({vent: this.vent, mapView: mapView});
        $('#app').append(this.sideBarView.render().el);

		//this.chatView = new ChatView({vent: this.vent});
        //$('#app').append(this.chatView.render().el);

		//this.graphView = new GraphView({vent: this.vent});
		//$('#app').append(this.graphView.render().el);

		$('body').css("overflow","hidden");

		// TODO: Detect embed
		if (window.location.href.indexOf('4D4R0IjQJYzGP0m') != -1) {
			$('body').addClass("embed");
		}

		//this.addCommentData();

		this.vent.trigger("setToggleStates", {mapView: mapView});

		if (this.isMapAdmin()) {
			this.setupView = new SetupView({vent: this.vent, mapInfo: this.mapInfo});
			$('#app').append(this.setupView.render().el);
			if (this.setupRoute) {
				$('#setupModal').modal('show');
			}
		}
	},

	renderAsEmbed: function()
	{
		var link = $("<link>");
		link.attr({
        	type: 'text/css',
        	rel: 'stylesheet',
        	href: '/styles/embed.css'
		});
		$("head").append( link );

		console.log("Rendering GeoSense map as embed...")
		$('.map-gl-view').addClass('full');
		$('.message').addClass('.embed');
	},

	loadAndInitMap: function(slug, mapView, center, zoom)
	{
		var self = this;
		$.ajax({
			type: 'GET',
			url: '/api/map/' + slug,
			success: function(data) {
				self.mapInfo = data;
				switch (mapView) {
					default:
						mapView = 'map';
						break;
					case 'map':
						break;
					case 'globe':
						break;
				}

				self.initMapView(mapView, center, zoom);

				if (!self.sideBarView) {
					self.render(mapView);
				}
			},
			error: function() {
				console.error('failed to load map', slug);
			}
		});
	},

	getURLParameter:function(name)
	{
	    return decodeURI(
	        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
	    );
	},

	initMapLayers: function()
	{
		if (this.mapInfo.layers) {
			for (var i = 0; i < this.mapInfo.layers.length; i++) {
				this.initMapLayer(this.mapInfo.layers[i].pointCollection._id)
			}
		}
	},

	initMapLayer: function(pointCollectionId)
	{
		var self = this;

		var layer = this.getMapLayer(pointCollectionId);
		console.log('initMapLayer '+pointCollectionId, layer);

		var scope = this;
		self.vent.trigger("setStateType", 'loading');

		layer.pointCollection.collectionId = layer.pointCollection.collectionid = pointCollectionId; // TODO: deprecated

		var mapArea = self.mapView.getVisibleMapArea();
		var collectionOptions = {
			pointCollectionId: pointCollectionId,
			mapId: app.mapInfo._id,
			mapLayer: layer
		};

		var collection = this.pointCollections[pointCollectionId] = new PointCollection(collectionOptions);
		self.addDataPanelViews(pointCollectionId);

		if (layer.pointCollection.status == DataStatus.COMPLETE) {
			this.fetchMapLayer(pointCollectionId);
		} else {
			self.vent.trigger("setStateType", 'loading', collection);
			app.pollForNewPointCollection(pointCollectionId, INITIAL_POLL_INTERVAL);
			//self.vent.trigger("setStateType", 'parsing');

		}

		$('.data-info').show();

		//Fetch time based point collections for graph
		/*if (1||data.timeBased) {
			collectionOptions.urlParams = {
				t: 'w'
			};
			var collection = this.timeBasedPointCollections[pointCollectionId] = new PointCollection(collectionOptions);
			collection.setVisibleMapArea(self.mapView.getVisibleMapArea());
			collection.fetch({success: function(collection) {
				self.graphView.addCollection(collection);
			}});
		}*/
	},

	pollForNewPointCollection: function(pointCollectionId, interval)
	{
		var self = this;

		if (interval) {
			setTimeout(function() {
				self.pollForNewPointCollection(pointCollectionId);
			}, interval);
			return;
		}

		console.log('pollForNewPointCollection: '+pointCollectionId);
		$.ajax({
			type: 'GET',
			url: '/api/pointcollection/' + pointCollectionId,
		    error: function() {
				console.error('Failed to fetch new collection, trying again after timeout...');
		    },
		    success: function(data) {
		    	self.updatePointCollectionAfterPolling(data);
		    }
		});
	},

	updatePointCollectionAfterPolling: function(data)
	{
		var pointCollectionId = data._id;
		var layer = this.getMapLayer(pointCollectionId);
		layer.pointCollection = data;

		if (data.status !== DataStatus.COMPLETE) {
			console.log('Collection '+pointCollectionId+' is busy, polling again after timeout...');
			this.pollForNewPointCollection(pointCollectionId, POLL_INTERVAL);
			//app.vent.trigger("setStateType", 'parsing', data);
			// TODO: update panel status
		} else {
			this.fetchMapLayer(pointCollectionId);
			this.vent.trigger("setStateType", 'complete', this.pointCollections[pointCollectionId]);
			//app.vent.trigger("setStateType", 'post');
		}
	},

	fetchMapLayer: function(pointCollectionId)
	{
		var self = this;
		var collection = this.pointCollections[pointCollectionId];
		var layer = this.getMapLayer(pointCollectionId);
		collection.setVisibleMapArea(this.mapView.getVisibleMapArea());
		collection.fetch({success: function(collection) {
			self.mapView.addCollection(collection);
			console.log('complete');
			self.vent.trigger("setStateType", 'complete', layer.pointCollection);
		}});
	},

	bindCollectionToMap: function(pointCollectionId)
	{
		var self = this;
		$.ajax({
			type: 'POST',
			url: '/api/bindmapcollection/' + this.mapInfo._id + '/' + pointCollectionId,
			success: function(data) {
				self.mapInfo = data;
				self.initMapLayer(pointCollectionId);
			},
			error: function() {
				console.error('failed to join map with collection');
			}
		});
	},

	addCommentData: function(options)
	{
		this.commentCollection = new CommentCollection({});
		this.mapView.addCommentCollection(this.commentCollection);
	},

	addTwitterData: function (options)
	{
		console.log('adding tweets');
	},

	getMapLayer: function(pointCollectionId)
	{
		for (var i = 0; i < this.mapInfo.layers.length; i++) {
			if (pointCollectionId == this.mapInfo.layers[i].pointCollection._id) {
				return this.mapInfo.layers[i];
			}
		}
	},

	addDataPanelViews:function(pointCollectionId)
	{
		var viewOpts = {
			vent: this.vent,
			collection: this.pointCollections[pointCollectionId],
			collectionId: pointCollectionId,
			mapLayer: this.getMapLayer(pointCollectionId)
		};

		var sideBarDataView = new DataInspectorView(viewOpts);
		$('#dataContainer .accordion').append(sideBarDataView.render().el);

		var dataLegendView = new DataLegendView(viewOpts);
		var el = dataLegendView.render().el;
		$('#data-info-view .accordion').append(el);
		$('.collapse', el).collapse('show');
	},

});

tpl.loadTemplates(['homepage', 'graph', 'setup', 'map-ol', 'map-gl', 'header',
	'sidebar','data-inspector', 'data-legend', 'chat', 'modal', 'add-data',
	'edit-data', 'data-library', 'data-info'],
    function () {
        app = new AppRouter();
        if (!Backbone.history.start({ pushState: true })) {
	    	$('#app').html('page not found');
        }
	});
<commit_msg>Cleaned out obsolete code<commit_after>var AppRouter = Backbone.Router.extend({

    routes: {
		"": "homeRoute",
		"removed": "homeRoute",

		"admin/:slug": "mapAdminRoute",
		"admin/:slug/:view": "mapAdminRoute",
		"admin/:slug/:view/:x,:y": "mapAdminRoute",
		"admin/:slug/:view/:x,:y/:zoom": "mapAdminRoute",

		":slug": "mapRoute",
		":slug/:view": "mapRoute",
		":slug/:view/:x,:y": "mapRoute",
		":slug/:view/:x,:y/:zoom": "mapRoute",
    },

    initialize: function()
    {
		var self = this;

		this.firstLoad = true;
		this.pointCollections = {};
		this.timeBasedPointCollections = {};

		this.settingsVisible = false;
		this.graphVisible = false;
		this.dataLibraryVisible = false;
		this.chatVisible = false;

		this.vent = _.extend({}, Backbone.Events);
		this.vent.bind('mapViewReady', function() {
			self.initMapLayers();
		});

		var embed = this.getURLParameter('embed');
		if (embed == 1) {
			console.log('embed: ' + embed);
			this.renderAsEmbed();
		}
    },

    mapRoute: function(slug, view, x, y, zoom)
    {
		var mapView;
		if (view) {
			this.setupRoute = view == 'setup';
			if (!this.setupRoute) {
				mapView = view;
			} else {
				$('#app').empty();
			}
		}
		var center;
		if (x != undefined && y != undefined) {
			x = parseFloat(x);
			y = parseFloat(y);
			if (!isNaN(x) && !isNaN(y)) {
				center = [x, y];
			}
		}

    	console.log(slug, 'mapView:', mapView, 'center:', center, 'zoom:', zoom);
		this.loadAndInitMap(slug, mapView, center, zoom);
    },

    mapAdminRoute: function(slug, view, x, y, zoom)
    {
    	this.adminRoute = true;
    	this.mapRoute(slug, view, x, y, zoom);
    },

	homeRoute: function()
	{

		if (this.firstLoad) {
			this.firstLoad = false;
			this.homepageView = new HomepageView();
	        $('#home').append(this.homepageView.render().el);
		} else {
			window.location.reload(true);
		}
	},

    genMapURI: function(view, opts)
    {
    	var uri = (this.adminRoute ? 'admin/' : '')
    		+ this.mapInfo.publicslug + (view ? '/' + view : '');
    	if (opts) {
	    	if (opts.x != undefined) {
		    	uri += '/%(x)s,%(y)s';
	    	}
	    	if (opts.zoom != undefined) {
	    		uri += '/%(zoom)s';
	    	}
    	}
    	return uri.format(opts);
    },

    initMapView: function(mapView, center, zoom)
    {
		var self = this;

		if (this.mapView) {
			this.mapView.remove();
			this.mapView = null;
		}

		switch (mapView) {
			case 'map':
				var viewClass = MapOLView;
				break;
			case 'globe':
				var viewClass = MapGLView;
				break;
		}

		var visibleMapArea = DEFAULT_MAP_AREA;
		if (this.mapInfo.initialArea.center.length) {
			visibleMapArea.center = this.mapInfo.initialArea.center;
		}
		if (this.mapInfo.initialArea.zoom != undefined) {
			visibleMapArea.zoom = this.mapInfo.initialArea.zoom;
		}
		if (center) {
			visibleMapArea.center = center;
		}
		if (zoom) {
			visibleMapArea.zoom = zoom;
		}

        this.mapView = new viewClass({
			vent: self.vent,
			visibleMapArea: visibleMapArea
		});
		this.mapView.uriViewName = mapView;

		var mapEl = this.mapView.render().el;
		$('#app').append(mapEl);
		this.mapView.start();

        var snap = $('

');
		$(mapEl).append(snap);

        this.dataInfoView = new DataInfoView({vent: this.vent});
		$(mapEl).append(this.dataInfoView.render().el);
    },

	isMapAdmin: function()
	{
		return this.adminRoute && this.mapInfo.admin;
	},

	render: function(mapView)
	{
		var self = this;

		window.document.title = this.mapInfo.title + ' – GeoSense';

 		this.headerView = new HeaderView({vent: this.vent, title: this.mapInfo.title});
        $('#app').append(this.headerView.render().el);

		this.sideBarView = new SideBarView({vent: this.vent, mapView: mapView});
        $('#app').append(this.sideBarView.render().el);

		//this.chatView = new ChatView({vent: this.vent});
        //$('#app').append(this.chatView.render().el);

		//this.graphView = new GraphView({vent: this.vent});
		//$('#app').append(this.graphView.render().el);

		$('body').css("overflow","hidden");

		// TODO: Detect embed
		if (window.location.href.indexOf('4D4R0IjQJYzGP0m') != -1) {
			$('body').addClass("embed");
		}

		//this.addCommentData();

		this.vent.trigger("setToggleStates", {mapView: mapView});

		if (this.isMapAdmin()) {
			this.setupView = new SetupView({vent: this.vent, mapInfo: this.mapInfo});
			$('#app').append(this.setupView.render().el);
			if (this.setupRoute) {
				$('#setupModal').modal('show');
			}
		}
	},

	renderAsEmbed: function()
	{
		var link = $("<link>");
		link.attr({
        	type: 'text/css',
        	rel: 'stylesheet',
        	href: '/styles/embed.css'
		});
		$("head").append( link );

		console.log("Rendering GeoSense map as embed...")
		$('.map-gl-view').addClass('full');
		$('.message').addClass('.embed');
	},

	loadAndInitMap: function(slug, mapView, center, zoom)
	{
		var self = this;
		$.ajax({
			type: 'GET',
			url: '/api/map/' + slug,
			success: function(data) {
				self.mapInfo = data;
				switch (mapView) {
					default:
						mapView = 'map';
						break;
					case 'map':
						break;
					case 'globe':
						break;
				}

				self.initMapView(mapView, center, zoom);

				if (!self.sideBarView) {
					self.render(mapView);
				}
			},
			error: function() {
				console.error('failed to load map', slug);
			}
		});
	},

	getURLParameter:function(name)
	{
	    return decodeURI(
	        (RegExp(name + '=' + '(.+?)(&|$)').exec(location.search)||[,null])[1]
	    );
	},

	initMapLayers: function()
	{
		if (this.mapInfo.layers) {
			for (var i = 0; i < this.mapInfo.layers.length; i++) {
				this.initMapLayer(this.mapInfo.layers[i].pointCollection._id)
			}
		}
	},

	initMapLayer: function(pointCollectionId)
	{
		var self = this;

		var layer = this.getMapLayer(pointCollectionId);
		console.log('initMapLayer '+pointCollectionId, layer);

		var scope = this;
		self.vent.trigger("setStateType", 'loading');

		layer.pointCollection.collectionId = layer.pointCollection.collectionid = pointCollectionId; // TODO: deprecated

		var mapArea = self.mapView.getVisibleMapArea();
		var collectionOptions = {
			pointCollectionId: pointCollectionId,
			mapId: app.mapInfo._id,
			mapLayer: layer
		};

		var collection = this.pointCollections[pointCollectionId] = new PointCollection(collectionOptions);
		self.addDataPanelViews(pointCollectionId);

		if (layer.pointCollection.status == DataStatus.COMPLETE) {
			this.fetchMapLayer(pointCollectionId);
		} else {
			self.vent.trigger("setStateType", 'loading', collection);
			app.pollForNewPointCollection(pointCollectionId, INITIAL_POLL_INTERVAL);
			//self.vent.trigger("setStateType", 'parsing');

		}

		$('.data-info').show();

		//Fetch time based point collections for graph
		/*if (1||data.timeBased) {
			collectionOptions.urlParams = {
				t: 'w'
			};
			var collection = this.timeBasedPointCollections[pointCollectionId] = new PointCollection(collectionOptions);
			collection.setVisibleMapArea(self.mapView.getVisibleMapArea());
			collection.fetch({success: function(collection) {
				self.graphView.addCollection(collection);
			}});
		}*/
	},

	pollForNewPointCollection: function(pointCollectionId, interval)
	{
		var self = this;

		if (interval) {
			setTimeout(function() {
				self.pollForNewPointCollection(pointCollectionId);
			}, interval);
			return;
		}

		console.log('pollForNewPointCollection: '+pointCollectionId);
		$.ajax({
			type: 'GET',
			url: '/api/pointcollection/' + pointCollectionId,
		    error: function() {
				console.error('Failed to fetch new collection, trying again after timeout...');
		    },
		    success: function(data) {
		    	self.updatePointCollectionAfterPolling(data);
		    }
		});
	},

	updatePointCollectionAfterPolling: function(data)
	{
		var pointCollectionId = data._id;
		var layer = this.getMapLayer(pointCollectionId);
		layer.pointCollection = data;

		if (data.status !== DataStatus.COMPLETE) {
			console.log('Collection '+pointCollectionId+' is busy, polling again after timeout...');
			this.pollForNewPointCollection(pointCollectionId, POLL_INTERVAL);
			//app.vent.trigger("setStateType", 'parsing', data);
			// TODO: update panel status
		} else {
			this.fetchMapLayer(pointCollectionId);
			this.vent.trigger("setStateType", 'complete', this.pointCollections[pointCollectionId]);
			//app.vent.trigger("setStateType", 'post');
		}
	},

	fetchMapLayer: function(pointCollectionId)
	{
		var self = this;
		var collection = this.pointCollections[pointCollectionId];
		var layer = this.getMapLayer(pointCollectionId);
		collection.setVisibleMapArea(this.mapView.getVisibleMapArea());
		collection.fetch({success: function(collection) {
			self.mapView.addCollection(collection);
			console.log('complete');
			self.vent.trigger("setStateType", 'complete', layer.pointCollection);
		}});
	},

	bindCollectionToMap: function(pointCollectionId)
	{
		var self = this;
		$.ajax({
			type: 'POST',
			url: '/api/bindmapcollection/' + this.mapInfo._id + '/' + pointCollectionId,
			success: function(data) {
				self.mapInfo = data;
				self.initMapLayer(pointCollectionId);
			},
			error: function() {
				console.error('failed to join map with collection');
			}
		});
	},

	addCommentData: function(options)
	{
		this.commentCollection = new CommentCollection({});
		this.mapView.addCommentCollection(this.commentCollection);
	},

	addTwitterData: function (options)
	{
		console.log('adding tweets');
	},

	getMapLayer: function(pointCollectionId)
	{
		for (var i = 0; i < this.mapInfo.layers.length; i++) {
			if (pointCollectionId == this.mapInfo.layers[i].pointCollection._id) {
				return this.mapInfo.layers[i];
			}
		}
	},

	addDataPanelViews:function(pointCollectionId)
	{
		var viewOpts = {
			vent: this.vent,
			collection: this.pointCollections[pointCollectionId],
			collectionId: pointCollectionId,
			mapLayer: this.getMapLayer(pointCollectionId)
		};

		var sideBarDataView = new DataInspectorView(viewOpts);
		$('#dataContainer .accordion').append(sideBarDataView.render().el);

		var dataLegendView = new DataLegendView(viewOpts);
		var el = dataLegendView.render().el;
		$('#data-info-view .accordion').append(el);
		$('.collapse', el).collapse('show');
	},

});

tpl.loadTemplates(['homepage', 'graph', 'setup', 'map-ol', 'map-gl', 'header',
	'sidebar','data-inspector', 'data-legend', 'chat', 'modal', 'add-data',
	'edit-data', 'data-library', 'data-info'],
    function () {
        app = new AppRouter();
        if (!Backbone.history.start({ pushState: true })) {
	    	$('#app').html('page not found');
        }
	});
<|endoftext|>


<commit_before>var http = require('http')

module.exports = {
    create:     function( callback ) { talk( 'POST', 'bins', callback ) },
    get:        function( bin, callback ) { talk( 'GET', 'bins/'+ bin, callback ) },
    requests:   function( bin, callback ) { talk( 'GET', 'bins/'+ bin +'/requests', callback ) },
    request:    function( bin, request, callback ) { talk( 'GET', 'bins/'+ bin +'/requests/'+ request, callback ) }
}

function talk( method, path, callback ) {
    var options = {
        host:   'requestb.in',
        path:   '/api/v1/'+ path,
        method: method
    }

    var req = http.request( options )

    req.on( 'response', function( res ) {
        var data = ''
        res.on( 'data', function( ch ) { data += ch })
        res.on( 'close', function() { callback( new Error('disconnected') ) })
        res.on( 'end', function() {
            data = data.toString('utf8').trim()
            if( res.statusCode >= 300 ) {
                var err = new Error('HTTP error')
                err.httpCode = res.statusCode
                err.request = options
                err.response = {
                    headers: res.headers,
                    body: data
                }
                callback( err )
            } else if( !data.match( /^(\{.*\}|\[.*\])$/ ) ) {
                var err = new Error('invalid response')
                err.request = options
                err.response = {
                    headers: res.headers,
                    body: data
                }
                callback( err )
            } else {
                data = JSON.parse( data )
                callback( null, data )
            }
        })
    })

    req.on( 'error', function( error ) {
        var err = new Error('request failed')
        err/details = error
        callback( err )
    })

    req.end()
}
<commit_msg>Added isPrivate parameter to .create<commit_after>var http = require('http'),
    querystring = require('querystring')

module.exports = {
    create:     function( isPrivate, callback ) {
        var props = {}
        if( typeof isPrivate === 'function' ) {
            var callback = isPrivate
        } else {
            props.private = isPrivate === true || isPrivate == 1 ? '1' : '0'
        }
        talk( 'POST', 'bins', props, callback )
    },
    get:        function( bin, callback ) { talk( 'GET', 'bins/'+ bin, callback ) },
    requests:   function( bin, callback ) { talk( 'GET', 'bins/'+ bin +'/requests', callback ) },
    request:    function( bin, request, callback ) { talk( 'GET', 'bins/'+ bin +'/requests/'+ request, callback ) }
}

function talk( method, path, props, callback ) {
    if( typeof props === 'function' ) {
        var callback = props
        var props = {}
    }

    var options = {
        host:   'requestb.in',
        path:   '/api/v1/'+ path,
        method: method
    }

    var query = null

    if( method == 'POST' && Object.keys( props ).length >= 1 ) {
        var query = querystring.stringify( props )
        options.headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Content-Length': query.length
        }
    }

    var req = http.request( options )

    req.on( 'response', function( res ) {
        var data = ''
        res.on( 'data', function( ch ) { data += ch })
        res.on( 'close', function() { callback( new Error('disconnected') ) })
        res.on( 'end', function() {
            data = data.toString('utf8').trim()
            if( res.statusCode >= 300 ) {
                var err = new Error('HTTP error')
                err.httpCode = res.statusCode
                err.request = options
                err.response = {
                    headers: res.headers,
                    body: data
                }
                callback( err )
            } else if( !data.match( /^(\{.*\}|\[.*\])$/ ) ) {
                var err = new Error('invalid response')
                err.request = options
                err.response = {
                    headers: res.headers,
                    body: data
                }
                callback( err )
            } else {
                data = JSON.parse( data )
                callback( null, data )
            }
        })
    })

    req.on( 'error', function( error ) {
        var err = new Error('request failed')
        err/details = error
        callback( err )
    })

    req.end( query )
}
<|endoftext|>


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

	$('#manual_backup_button').click(function() {
		$(this).attr('disabled', 'disabled');
		$('#ajax_loader').show();
		$('#backup_result').html('');

		callback = function(data) {
			$('#ajax_loader').hide();
			if ('success' == data.status) {
				$('#backup_result').html('Success! Refresh the page to see the new bundle.').removeClass('error').addClass('success');
			} else {
				$('#backup_result').html('Error! ' + data.message).removeClass('success').addClass('error');
			}
			$('#manual_backup_button').removeAttr("disabled");
		};

		var application_name = $(this).attr('data-application-name');
		$.post('/applications/' + application_name, callback, 'json');
	});

});<commit_msg>Refactor javascript<commit_after>$(document).ready(function() {

	$('#manual_backup_button').click(function() {
		var callback, applicationName;

		$(this).attr('disabled', 'disabled');
		$('#ajax_loader').show();
		$('#backup_result').html('');

		callback = function(data) {
			$('#ajax_loader').hide();
			if ('success' === data.status) {
				$('#backup_result').html('Success! Refresh the page to see the new bundle.').removeClass('error').addClass('success');
			} else {
				$('#backup_result').html('Error! ' + data.message).removeClass('success').addClass('error');
			}
			$('#manual_backup_button').removeAttr("disabled");
		};

		applicationName = $(this).attr('data-application-name');
		$.post('/applications/' + applicationName, callback, 'json');
	});

});<|endoftext|>


<commit_before>#!/usr/bin/node

var http = require('http');
http.globalAgent.maxSockets = 100000
var httpProxy = require('http-proxy');
var uuid = require('uuid');
var net = require('net');

//CONSTANTS
var UPSTREAM_LOGSERVER = process.argv[2];
var HTTP_SERVER = process.argv[3];
var HTTP_PORT = process.argv[4];
var PROXY_PORT = process.argv[5];
//#TODO: add support for behind proxy

//GLOBALs
var upstreamConnection;
var blacklist = {};
var sweeplist = [];
var greylist = {};
var connections = [];
var requests = [];
var disabledUrls = [];
var totalConnections = 0;
var headerTimeout = 120000;
var requestTimeout = 120000;

process.setMaxListeners(0);

//Incoming commands from upstream server
function commandDo(cmd) {
  cmd = cmd.toString().trim().toLowerCase();
  if (/^block.*/.test(cmd)) {
    cmd = cmd.slice(6).split("|")
    timeToBlock =  new Date().getTime() + parseInt(cmd[1]);
    sweeplist.push(cmd[0]);
    blacklist[cmd[0]] = timeToBlock;
  } else if (/^grey.*/.test(cmd)) {
    cmd = cmd.slice(5).split("|")
    timeToBlock =  new Date().getTime() + parseInt(cmd[1]);
    greylist[cmd[0]] = timeToBlock;
  } else if (/^rtimeout.*/.test(cmd)) {
    requestTimeout = parseInt(cmd.slice(9));
  } else if (/^htimeout.*/.test(cmd)) {
    headerTimeout = parseInt(cmd.slice(9));
  } else if (/^durl.*/.test(cmd)) {
    disabledUrls.push(cmd.slice(5));
  } else if (/^eurl.*/.test(cmd)) {
    disabledUrls.splice(disabledUrls.indexOf(cmd.slice(5)));
  } else if (/^unblock.*/.test(cmd)) {
    cmd = cmd.slice(8)
    delete blacklist[cmd];
  } else if (cmd == "flush") {
    return blacklist = {};
  } else if (cmd == "kill") {
    cmd = cmd.slice(5)
    //connections
  };
}

function buildRequestMessage(req) {
  message = {};
  message.time    = new Date().getTime();
  message.type    = "request";
  message.host    = req.socket.remoteAddress;
  message.url     = req.url;
  message.method  = req.method;
  message.headers = req.headers;
  message.uuid    = req.uuid;
  return JSON.stringify(message);
}

function buildConnectMessage(req) {
  message = {};
  message.type    = "connect";
  message.host    = req.remoteAddress;
  return JSON.stringify(message);
}

function buildEndMessage(req) {
  message = {};
  message.time    = new Date().getTime();
  message.type    = "end";
  message.host    = req.remoteAddress;
  message.uuid    = req.uuid;
  return JSON.stringify(message);
}

function checkBlacklist(addr) {
  if (addr in blacklist) {
    if (blacklist[addr] > new Date().getTime()) {
      return false;
    } else {
      delete blacklist[addr];
      return true;
    }
  } else {
    return true;
  }
}

function checkGreylist(addr,url) {
  if (addr in greylist) {
    if (greylist[addr] > new Date().getTime()) {
      return checkDisabledUrls(url)
    } else {
      delete greylist[addr];
      return true;
    }
  } else {
    return true;
  }
}

function checkDisabledUrls(url) {
  url = url.split("?")[0]
  if (disabledUrls.indexOf(url) > -1) {
    return false;
  } else { return true; }
}

//This connects to the aggregation server and accepts upstream commands.
setInterval(function() {
  if (!upstreamConnection || upstreamConnection == null) {
    upstreamConnection = net.connect({host: UPSTREAM_LOGSERVER, port: 5555})
    //connect to aggregator in "server" mode
    upstreamConnection.write('S');
    upstreamConnection.on('data', function(data) {
      commandDo(data);
    });
    //destroys upstream if the connection is dead
    upstreamConnection.on('error', function () {
      return upstreamConnection = null
    });
  };
},1000);

setInterval(function() {
  requests.forEach(function (req) {
    if ((req.startTime + requestTimeout) < new Date().getTime()) {
      requests.splice(requests.indexOf(req),1);
      req.socket.end();
    };
  });
},250);

setInterval(function() {
  connections.forEach(function (req) {
    if ((req.startTime + headerTimeout) < new Date().getTime()) {
      connections.splice(connections.indexOf(req),1);
      req.end();
    };
  });
},250);

//TODO: make this work properly
//Sweep newly blacklisted servers right away
//setInterval(function() {
//        console.log(requests.length);
//  if (sweeplist.length > 0 && requests.length > 0) {
//      count =  1;
//      requests.forEach(function (req) {
//        if (sweeplist.indexOf(req.socket.remoteAddress) > -1) {
//          count += 1
//          req.socket.end();
//          requests.splice(requests.indexOf(req),1);
//        } else {
//          console.log(req.socket.remoteAddress)
//        };
//      });
//      console.log('removed connections: ' + count);
//  } return sweeplist = [];
//} ,1000);

proxy = new httpProxy.RoutingProxy();
//proxyServer = httpProxy.createServer(function (req, res, proxy) {
proxyServer = http.createServer(function (req, res) {
  //this important bit helps against slowloris
  //req.setTimeout(12000);
  if (checkBlacklist(req.socket.remoteAddress) && checkGreylist(req.socket.remoteAddress,req.url)) {
    totalConnections += 1;
    proxy.proxyRequest(req, res, {
    host: HTTP_SERVER,
    port: HTTP_PORT
    });
    req.uuid = uuid.v4();
    //id = uuid.v4();
    try {
    upstreamConnection.write(buildRequestMessage(req) + "\n");
    } catch (e) {}
  } else {
    req.connection.write('disabled');
    req.connection.end();
  }
}).listen(PROXY_PORT);

proxyServer.on('request', function (req, res) {
  //remove good requests from garbage collection
  req.startTime = new Date().getTime();
  requests.push(req);
  connections.splice(connections.indexOf(req),1);
});

proxyServer.on('connection', function (req, c, h) {
  //mark the start time vs slow laris
  if (checkBlacklist(req.remoteAddress)) {
    req.startTime = new Date().getTime();
    connections.push(req);
    try {
      upstreamConnection.write(buildConnectMessage(req) + "\n");
    } catch (e) {}
  } else {
    req.end()
  }
});

proxy.on('end', function (req) {
  //upstreamConnection.write(req.id + "ENDDDDDDDD\n");
  requests.splice(requests.indexOf(req),1);
  try {
    upstreamConnection.write(buildEndMessage(req) + "\n");
  } catch (e) {}
});

proxy.on('error', function(proxy) {
  //totalConnections -= 1;
  try {
  upstreamConnection.write(buildEndMessage(req) + "\n");
  } catch (e) {}
  //c = connections.indexOf(proxy);
  //connections.splice(c, 1);
});

//proxy.on('end', function(proxy) {
//  totalConnections -= 1;
//  //c = connections.indexOf(proxy);
//  //connections.splice(c, 1);
//});
<commit_msg>seeeeeeems to work<commit_after>#!/usr/bin/node

var http = require('http');
http.globalAgent.maxSockets = 100000
var httpProxy = require('http-proxy');
var uuid = require('uuid');
var net = require('net');

//CONSTANTS
var UPSTREAM_LOGSERVER = process.argv[2];
var HTTP_SERVER = process.argv[3];
var HTTP_PORT = process.argv[4];
var PROXY_PORT = process.argv[5];
//#TODO: add support for behind proxy

//GLOBALs
var upstreamConnection;
var blacklist = {};
var sweeplist = [];
var greylist = {};
var connections = [];
var requests = [];
var disabledUrls = [];
var totalConnections = 0;
var headerTimeout = 120000;
var requestTimeout = 120000;

process.setMaxListeners(0);

//Incoming commands from upstream server
function commandDo(cmd) {
  cmd = cmd.toString().trim().toLowerCase();
  if (/^block.*/.test(cmd)) {
    cmd = cmd.slice(6).split("|")
    timeToBlock =  new Date().getTime() + parseInt(cmd[1]);
    sweeplist.push(cmd[0]);
    blacklist[cmd[0]] = timeToBlock;
  } else if (/^grey.*/.test(cmd)) {
    cmd = cmd.slice(5).split("|")
    timeToBlock =  new Date().getTime() + parseInt(cmd[1]);
    greylist[cmd[0]] = timeToBlock;
  } else if (/^rtimeout.*/.test(cmd)) {
    requestTimeout = parseInt(cmd.slice(9));
  } else if (/^htimeout.*/.test(cmd)) {
    headerTimeout = parseInt(cmd.slice(9));
  } else if (/^durl.*/.test(cmd)) {
    disabledUrls.push(cmd.slice(5));
  } else if (/^eurl.*/.test(cmd)) {
    disabledUrls.splice(disabledUrls.indexOf(cmd.slice(5)));
  } else if (/^unblock.*/.test(cmd)) {
    cmd = cmd.slice(8)
    delete blacklist[cmd];
  } else if (cmd == "flush") {
    return blacklist = {};
  } else if (cmd == "kill") {
    cmd = cmd.slice(5)
    //connections
  };
}

function buildRequestMessage(req) {
  message = {};
  message.time    = new Date().getTime();
  message.type    = "request";
  message.host    = req.socket.remoteAddress;
  message.url     = req.url;
  message.method  = req.method;
  message.headers = req.headers;
  message.uuid    = req.uuid;
  return JSON.stringify(message);
}

function buildConnectMessage(req) {
  message = {};
  message.type    = "connect";
  message.host    = req.remoteAddress;
  return JSON.stringify(message);
}

function buildEndMessage(req) {
  message = {};
  message.time    = new Date().getTime();
  message.type    = "end";
  message.host    = req.remoteAddress;
  message.uuid    = req.uuid;
  return JSON.stringify(message);
}

function checkBlacklist(addr) {
  if (addr in blacklist) {
    if (blacklist[addr] > new Date().getTime()) {
      return false;
    } else {
      delete blacklist[addr];
      return true;
    }
  } else {
    return true;
  }
}

function checkGreylist(addr,url) {
  if (addr in greylist) {
    if (greylist[addr] > new Date().getTime()) {
      return checkDisabledUrls(url)
    } else {
      delete greylist[addr];
      return true;
    }
  } else {
    return true;
  }
}

function checkDisabledUrls(url) {
  url = url.split("?")[0]
  if (disabledUrls.indexOf(url) > -1) {
    return false;
  } else { return true; }
}

//This connects to the aggregation server and accepts upstream commands.
setInterval(function() {
  if (!upstreamConnection || upstreamConnection == null) {
    upstreamConnection = net.connect({host: UPSTREAM_LOGSERVER, port: 5555})
    //connect to aggregator in "server" mode
    upstreamConnection.write('S');
    upstreamConnection.on('data', function(data) {
      commandDo(data);
    });
    //destroys upstream if the connection is dead
    upstreamConnection.on('error', function () {
      return upstreamConnection = null
    });
  };
},1000);

setInterval(function() {
  requests.forEach(function (req) {
    if ((req.startTime + requestTimeout) < new Date().getTime()) {
      requests.splice(requests.indexOf(req),1);
      req.socket.end();
    };
  });
},250);

setInterval(function() {
  connections.forEach(function (req) {
    if ((req.startTime + headerTimeout) < new Date().getTime()) {
      connections.splice(connections.indexOf(req),1);
      req.end();
    };
  });
},250);

//TODO: make this work properly
//Sweep newly blacklisted servers right away
setInterval(function() {
  if (sweeplist.length > 0 && requests.length > 0) {
      requests.forEach(function (req) {
        if (sweeplist.indexOf(req.socket.remoteAddress) > -1) {
          req.socket.end();
          requests.splice(requests.indexOf(req),1);
        };
      });
  } return sweeplist = [];
} ,1000);

proxy = new httpProxy.RoutingProxy();
//proxyServer = httpProxy.createServer(function (req, res, proxy) {
proxyServer = http.createServer(function (req, res) {
  //this important bit helps against slowloris
  //req.setTimeout(12000);
  if (checkBlacklist(req.socket.remoteAddress) && checkGreylist(req.socket.remoteAddress,req.url)) {
    totalConnections += 1;
    proxy.proxyRequest(req, res, {
    host: HTTP_SERVER,
    port: HTTP_PORT
    });
    req.uuid = uuid.v4();
    //id = uuid.v4();
    try {
    upstreamConnection.write(buildRequestMessage(req) + "\n");
    } catch (e) {}
  } else {
    req.connection.write('disabled');
    req.connection.end();
  }
}).listen(PROXY_PORT);

proxyServer.on('request', function (req, res) {
  //remove good requests from garbage collection
  req.startTime = new Date().getTime();
  requests.push(req);
  connections.splice(connections.indexOf(req),1);
});

proxyServer.on('connection', function (req, c, h) {
  //mark the start time vs slow laris
  if (checkBlacklist(req.remoteAddress)) {
    req.startTime = new Date().getTime();
    connections.push(req);
    try {
      upstreamConnection.write(buildConnectMessage(req) + "\n");
    } catch (e) {}
  } else {
    req.end()
  }
});

proxy.on('end', function (req) {
  //upstreamConnection.write(req.id + "ENDDDDDDDD\n");
  requests.splice(requests.indexOf(req),1);
  try {
    upstreamConnection.write(buildEndMessage(req) + "\n");
  } catch (e) {}
});

proxy.on('error', function(proxy) {
  //totalConnections -= 1;
  try {
  upstreamConnection.write(buildEndMessage(req) + "\n");
  } catch (e) {}
  //c = connections.indexOf(proxy);
  //connections.splice(c, 1);
});

//proxy.on('end', function(proxy) {
//  totalConnections -= 1;
//  //c = connections.indexOf(proxy);
//  //connections.splice(c, 1);
//});
<|endoftext|>