<commit_before>// Replacing $(document).ready()
function ready(fn) {
    if (document.readyState != 'loading') {
        onReady();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

// Adicionando função no ready
ready(onReady);

function onReady() {
    getPoetry();
    declarePoetry();
}

function randomNumber(totalelements) {
    return Math.floor(Math.random() * totalelements);
}
function setStorage(data) {
    localStorage.setItem('shuffle', JSON.stringify(data));
}
function getStorage() {
    return JSON.parse(localStorage.getItem('shuffle'));
}

function getIndex(storageData) {
    return storageData.shift() || 0;
}

let poetry; // global para ser usada no button :/
function setPoetry(data) {
    let storage = getStorage();

    poetry = data;

    if (!storage || !storage.length) {
        let total = data.length;
        let shuffle = [];

        for (let i = 0; i < total;) {
            let key = randomNumber(total);

            if (!shuffle[key]) {
                shuffle[key] = i;
                i++;
            }
        }

        storage = shuffle;
    }

    let index = getIndex(storage);
    exibirPoesia(data[index]);
    setStorage(storage);
}

async function getPoetry() {
    try {
        let response = await fetch('poesias.json');
        if (response.status === 200) {
            let data = await response.json();
            setPoetry(data);
        }
    } catch (error) {
        throw new Error(`Erro ao obter dados do JSON: ${error}`);
    }
}

function exibirPoesia(poesia) {
    document.getElementById("estrofe").innerText = '"' + poesia.estrofe + '"';
    document.getElementById("poeta").innerText = poesia.poeta;
    document.getElementById("poesia").innerText = poesia.poesia;
}

function declarePoetry() {
    document.querySelector('.declare-button').addEventListener('click', (evt) => {
        evt.preventDefault();
        let storage = getStorage();

        if (!storage || !storage.length) {
            window.location.reload();
        };

        let index = getIndex(storage);
        exibirPoesia(poetry[index]);
        setStorage(storage);
    });
}<commit_msg>Chamada da função errada no ready<commit_after>// Replacing $(document).ready()
function ready(fn) {
    if (document.readyState != 'loading') {
        fn();
    } else {
        document.addEventListener('DOMContentLoaded', fn);
    }
}

// Adicionando função no ready
ready(onReady);

function onReady() {
    getPoetry();
    declarePoetry();
}

function randomNumber(totalelements) {
    return Math.floor(Math.random() * totalelements);
}
function setStorage(data) {
    localStorage.setItem('shuffle', JSON.stringify(data));
}
function getStorage() {
    return JSON.parse(localStorage.getItem('shuffle'));
}

function getIndex(storageData) {
    return storageData.shift() || 0;
}

let poetry; // global para ser usada no button :/
function setPoetry(data) {
    let storage = getStorage();

    poetry = data;

    if (!storage || !storage.length) {
        let total = data.length;
        let shuffle = [];

        for (let i = 0; i < total;) {
            let key = randomNumber(total);

            if (!shuffle[key]) {
                shuffle[key] = i;
                i++;
            }
        }

        storage = shuffle;
    }

    let index = getIndex(storage);
    exibirPoesia(data[index]);
    setStorage(storage);
}

async function getPoetry() {
    try {
        let response = await fetch('poesias.json');
        if (response.status === 200) {
            let data = await response.json();
            setPoetry(data);
        }
    } catch (error) {
        throw new Error(`Erro ao obter dados do JSON: ${error}`);
    }
}

function exibirPoesia(poesia) {
    document.getElementById("estrofe").innerText = '"' + poesia.estrofe + '"';
    document.getElementById("poeta").innerText = poesia.poeta;
    document.getElementById("poesia").innerText = poesia.poesia;
}

function declarePoetry() {
    document.querySelector('.declare-button').addEventListener('click', (evt) => {
        evt.preventDefault();
        let storage = getStorage();

        if (!storage || !storage.length) {
            window.location.reload();
        };

        let index = getIndex(storage);
        exibirPoesia(poetry[index]);
        setStorage(storage);
    });
}<|endoftext|>


<commit_before>window.App = {};
App.refreshTime = 1000;
App.requestMaxValue = 0;
App.bandwidthMaxValue = 0;
App.oldStats = {};
App.newStats = {};

App.getStats = function(){
	$.getJSON("/stats", function(data){
		App.oldStats = App.newStats;
		App.newStats = data;
	})
}

App.calcHitRatio = function(){
	delta_client_req = App.newStats.client_req.value - App.oldStats.client_req.value;
	delta_cache_hit = App.newStats.cache_hit.value - App.oldStats.cache_hit.value;
	hitRatio = (delta_cache_hit*100)/delta_client_req;
	return Math.round(hitRatio);
}

App.calcAverageHitRatio = function(){
	hitRatio = App.newStats.cache_hit.value * 100 / App.oldStats.client_req.value;
	return Math.round(hitRatio);
}

App.updateHitRatioGauge = function(){
	App.hitRatioGauge.refresh(App.calcHitRatio());
}

App.updateRequestGauge = function() {
	requests_per_second = App.newStats.client_req.value - App.oldStats.client_req.value;
	if(requests_per_second > App.requestMaxValue){
		App.requestMaxValue = requests_per_second;
	}
	App.requestGauge.refresh(requests_per_second, App.requestMaxValue);
}

App.updateBandwidthGauge = function(){
	bandwidth = (App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) - (App.oldStats.s_hdrbytes.value + App.oldStats.s_bodybytes.value) / 1024 / 1024;
	if(bandwidth > App.bandwidthMaxValue){
		App.bandwidthMaxValue = bandwidth;
	}
	App.bandwidthGauge.refresh(bandwidth, App.bandwidthMaxValue);
}

App.updateData = function(){
	App.getStats();
	App.updateHitRatioGauge();
	App.updateRequestGauge();
	App.updateBandwidthGauge();
	App.builMetricsTable("cache", App.getCacheMetrics());
	App.builMetricsTable("traffic", App.getTrafficMetrics());
	App.builMetricsTable("backend", App.getBackendMetrics());
}

App.getCacheMetrics = function() {
	var hits_ratio = {
		label: "Hits Ratio",
		new_value: App.calcHitRatio(),
		average_value: App.calcAverageHitRatio()
	}
	var hits_qty = {
		label: "Hits Qty.",
		new_value: nFormatter(App.newStats.cache_hit.value - App.oldStats.cache_hit.value),
		average_value: nFormatter(App.newStats.cache_hit.value / App.newStats.uptime.value)
	}
	var miss_qty = {
		label: "Miss Qty.",
		new_value: nFormatter(App.newStats.cache_miss.value - App.oldStats.cache_miss.value),
		average_value: nFormatter(App.newStats.cache_miss.value / App.newStats.uptime.value)
	}
	var obj_cache = {
		label: "Objs. in Cache",
		new_value: nFormatter(App.newStats.n_object.value - App.oldStats.n_object.value),
		average_value: nFormatter(App.newStats.n_object.value)
	}
	return [hits_ratio, hits_qty, miss_qty, obj_cache]
}

App.getTrafficMetrics = function() {
	var client_conn = {
		label: "Connections",
		new_value: nFormatter(App.newStats.client_conn.value - App.oldStats.client_conn.value),
		average_value: nFormatter(App.newStats.client_conn.value / App.newStats.uptime.value)
	}
	var client_req = {
		label: "Requests",
		new_value: nFormatter(App.newStats.client_req.value - App.oldStats.client_req.value),
		average_value: nFormatter(App.newStats.client_req.value / App.newStats.uptime.value)
	}
	var req_per_conn = {
		label: "Req / Conn",
		new_value: nFormatter((App.newStats.client_req.value - App.oldStats.client_req.value) /(App.newStats.client_conn.value - App.oldStats.client_conn.value) ),
		average_value: nFormatter(App.newStats.client_req.value / App.newStats.client_conn.value)
	}

	var bandwith = {
		label: "Bandwidth",
		new_value: nFormatter((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) - (App.oldStats.s_hdrbytes.value + App.oldStats.s_bodybytes.value)),
		average_value: nFormatter((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) / App.newStats.uptime.value)
	}

	return [client_conn, client_req, req_per_conn, bandwith]

}

App.getBackendMetrics = function() {
	var backend_conn = {
		label: "Connections",
		new_value: nFormatter(App.newStats.backend_conn.value - App.oldStats.backend_conn.value),
		average_value: nFormatter(App.newStats.backend_conn.value / App.newStats.uptime.value)
	}
	var backend_fail = {
		label: "Fails",
		new_value: nFormatter(App.newStats.backend_fail.value - App.oldStats.backend_fail.value),
		average_value: nFormatter(App.newStats.backend_fail.value / App.newStats.uptime.value)
	}
	var backend_reuse = {
		label: "Reuse",
		new_value: nFormatter(App.newStats.backend_reuse.value - App.oldStats.backend_reuse.value),
		average_value: nFormatter(App.newStats.backend_reuse.value / App.newStats.uptime.value)
	}
	var backend_fetch = {
		label: "Fetch & Pass",
		new_value: nFormatter(App.newStats.s_pass.value + App.newStats.s_fetch.value - App.oldStats.s_fetch.value - App.oldStats.s_pass.value),
		average_value: nFormatter((App.newStats.s_pass.value + App.newStats.s_fetch.value) / App.newStats.uptime.value)
	}
	return [backend_conn, backend_fetch, backend_fail, backend_reuse]
}

App.builMetricsTable = function(table_id, values_object){
	var source   = $("#metrics-table-template").html();
	var context = { metric: values_object};
	var template = Handlebars.compile(source);
	var html = template(context);
	$("#"+table_id+"-metrics-table").html(html);
}

$(function(){
	App.hitRatioGauge = new JustGage({
	    id: "hit-ratio",
	    value: 0,
	 	levelColors: ["#f70000","#f9c800","#a8d600"],
	    min: 0,
	    max: 100,
	    title: " ",
		label: "%"
	  });

	App.requestGauge = new JustGage({
	    id: "request-gauge",
	    value: 0,
	    min: 0,
	    max: 100,
	    title: " ",
		label: "per second"
	  });

	App.bandwidthGauge = new JustGage({
	    id: "bandwidth-gauge",
	    value: 0,
	    min: 0,
	    max: 100,
	    title: " ",
		label: "Mbps"
	  });

	setInterval(App.updateData,App.refreshTime);

});

function nFormatter(num) {
     if (num >= 1000000000) {
        return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
     }
     if (num >= 1000000) {
        return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
     }
     if (num >= 1000) {
        return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
     }
     return Math.round(num);
}<commit_msg>first commit<commit_after>window.App = {};
App.refreshTime = 1000;
App.requestMaxValue = 0;
App.bandwidthMaxValue = 0;
App.oldStats = {};
App.newStats = {};

App.getStats = function(){
	$.getJSON("/stats", function(data){
		App.oldStats = App.newStats;
		App.newStats = data;
	})
}

App.calcHitRatio = function(){
	delta_client_req = App.newStats.client_req.value - App.oldStats.client_req.value;
	delta_cache_hit = App.newStats.cache_hit.value - App.oldStats.cache_hit.value;
	hitRatio = (delta_cache_hit*100)/delta_client_req;
	return Math.round(hitRatio);
}

App.calcAverageHitRatio = function(){
	hitRatio = App.newStats.cache_hit.value * 100 / App.oldStats.client_req.value;
	return Math.round(hitRatio);
}

App.updateHitRatioGauge = function(){
	App.hitRatioGauge.refresh(App.calcHitRatio());
}

App.updateRequestGauge = function() {
	requests_per_second = App.newStats.client_req.value - App.oldStats.client_req.value;
	if(requests_per_second > App.requestMaxValue){
		App.requestMaxValue = requests_per_second;
	}
	App.requestGauge.refresh(requests_per_second, App.requestMaxValue);
}

App.updateBandwidthGauge = function(){
	bandwidth = Math.round(((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) - (App.oldStats.s_hdrbytes.value + App.oldStats.s_bodybytes.value)) / 1024 / 1024);
	if(bandwidth > App.bandwidthMaxValue){
		App.bandwidthMaxValue = bandwidth;
	}
	App.bandwidthGauge.refresh(bandwidth, App.bandwidthMaxValue);
}

App.updateData = function(){
	App.getStats();
	App.updateHitRatioGauge();
	App.updateRequestGauge();
	App.updateBandwidthGauge();
	App.builMetricsTable("cache", App.getCacheMetrics());
	App.builMetricsTable("traffic", App.getTrafficMetrics());
	App.builMetricsTable("backend", App.getBackendMetrics());
}

App.getCacheMetrics = function() {
	var hits_ratio = {
		label: "Hits Ratio",
		new_value: App.calcHitRatio(),
		average_value: App.calcAverageHitRatio()
	}
	var hits_qty = {
		label: "Hits Qty.",
		new_value: nFormatter(App.newStats.cache_hit.value - App.oldStats.cache_hit.value),
		average_value: nFormatter(App.newStats.cache_hit.value / App.newStats.uptime.value)
	}
	var miss_qty = {
		label: "Miss Qty.",
		new_value: nFormatter(App.newStats.cache_miss.value - App.oldStats.cache_miss.value),
		average_value: nFormatter(App.newStats.cache_miss.value / App.newStats.uptime.value)
	}
	var obj_cache = {
		label: "Objs. in Cache",
		new_value: nFormatter(App.newStats.n_object.value - App.oldStats.n_object.value),
		average_value: nFormatter(App.newStats.n_object.value)
	}
	return [hits_ratio, hits_qty, miss_qty, obj_cache]
}

App.getTrafficMetrics = function() {
	var client_conn = {
		label: "Connections",
		new_value: nFormatter(App.newStats.client_conn.value - App.oldStats.client_conn.value),
		average_value: nFormatter(App.newStats.client_conn.value / App.newStats.uptime.value)
	}
	var client_req = {
		label: "Requests",
		new_value: nFormatter(App.newStats.client_req.value - App.oldStats.client_req.value),
		average_value: nFormatter(App.newStats.client_req.value / App.newStats.uptime.value)
	}
	var req_per_conn = {
		label: "Req / Conn",
		new_value: nFormatter((App.newStats.client_req.value - App.oldStats.client_req.value) /(App.newStats.client_conn.value - App.oldStats.client_conn.value) ),
		average_value: nFormatter(App.newStats.client_req.value / App.newStats.client_conn.value)
	}

	var bandwith = {
		label: "Bandwidth",
		new_value: nFormatter((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) - (App.oldStats.s_hdrbytes.value + App.oldStats.s_bodybytes.value)),
		average_value: nFormatter((App.newStats.s_hdrbytes.value + App.newStats.s_bodybytes.value) / App.newStats.uptime.value)
	}

	return [client_conn, client_req, req_per_conn, bandwith]

}

App.getBackendMetrics = function() {
	var backend_conn = {
		label: "Connections",
		new_value: nFormatter(App.newStats.backend_conn.value - App.oldStats.backend_conn.value),
		average_value: nFormatter(App.newStats.backend_conn.value / App.newStats.uptime.value)
	}
	var backend_fail = {
		label: "Fails",
		new_value: nFormatter(App.newStats.backend_fail.value - App.oldStats.backend_fail.value),
		average_value: nFormatter(App.newStats.backend_fail.value / App.newStats.uptime.value)
	}
	var backend_reuse = {
		label: "Reuse",
		new_value: nFormatter(App.newStats.backend_reuse.value - App.oldStats.backend_reuse.value),
		average_value: nFormatter(App.newStats.backend_reuse.value / App.newStats.uptime.value)
	}
	var backend_fetch = {
		label: "Fetch & Pass",
		new_value: nFormatter(App.newStats.s_pass.value + App.newStats.s_fetch.value - App.oldStats.s_fetch.value - App.oldStats.s_pass.value),
		average_value: nFormatter((App.newStats.s_pass.value + App.newStats.s_fetch.value) / App.newStats.uptime.value)
	}
	return [backend_conn, backend_fetch, backend_fail, backend_reuse]
}

App.builMetricsTable = function(table_id, values_object){
	var source   = $("#metrics-table-template").html();
	var context = { metric: values_object};
	var template = Handlebars.compile(source);
	var html = template(context);
	$("#"+table_id+"-metrics-table").html(html);
}

$(function(){
	App.hitRatioGauge = new JustGage({
	    id: "hit-ratio",
	    value: 0,
	 	levelColors: ["#f70000","#f9c800","#a8d600"],
	    min: 0,
	    max: 100,
	    title: " ",
		label: "%"
	  });

	App.requestGauge = new JustGage({
	    id: "request-gauge",
	    value: 0,
	    min: 0,
	    max: 100,
	    title: " ",
		label: "per second"
	  });

	App.bandwidthGauge = new JustGage({
	    id: "bandwidth-gauge",
	    value: 0,
	    min: 0,
	    max: 100,
	    title: " ",
		label: "Mbps"
	  });

	setInterval(App.updateData,App.refreshTime);

});

function nFormatter(num) {
     if (num >= 1000000000) {
        return (num / 1000000000).toFixed(1).replace(/\.0$/, '') + 'G';
     }
     if (num >= 1000000) {
        return (num / 1000000).toFixed(1).replace(/\.0$/, '') + 'M';
     }
     if (num >= 1000) {
        return (num / 1000).toFixed(1).replace(/\.0$/, '') + 'K';
     }
     return Math.round(num);
}<|endoftext|>


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

	// Upload a photo

	var uploadPhoto = $("#uploadPhotoBtn");

	function readURL(input) {
		if (input.files && input.files[0]) {
			var reader = new FileReader();

			reader.onload = function(event) {
				$("#userPhoto").attr("src", event.target.result);
			}

			reader.readAsDataURL(input.files[0]);
		}
	}

	uploadPhoto.on("change", function(event) {
		readURL(this);
	});

	//Filters - Grayscale

	var imageObj = new Image();

	var grayscaleBtn = document.getElementsByTagName("button")[0];
	var canvas = document.getElementById("imgCanvas");
	var originalPhoto = document.getElementById("userPhoto");
	var grayscaleRangeSlider = $("#grayscaleRange");
	var brightenRangeSlider = $("#brightenRange");
	var blurRangeSlider = $("#blurRange");
	var resetBtn = $("#resetBtn");
	var ctx = canvas.getContext("2d");

	var moveTop = document.getElementById("moveTop");
	var moveRight = document.getElementById("moveRight");
	var moveLeft = document.getElementById("moveLeft");
	var moveBottom = document.getElementById("moveBottom");

	var zoomIn = document.getElementById("zoom-in");
	var zoomOut = document.getElementById("zoom-out");

	var rotateControl = document.querySelector(".rotation-circle");

	var x = 0;
	var y = 0;
	var deg = 1;

	function drawImage(imageObj) {

		var grayscaleVal = grayscaleRangeSlider.val() * 0.01;

		ctx.drawImage(imageObj, x, y); //namaluj mi nowy obraz na jakimś x i jakimś y

		var imageData = ctx.getImageData(x, y, imageObj.width, imageObj.height);
		//pobierz pozycję i wymiary z kontekstu
		var data = imageData.data;
		//zapisz te dane do zmiennej data, imageData.data przechowuje wartości poszczególnych pikseli (0-255)

		for (var i = 0; i < data.length; i += 4) {
			var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
			// red
			data[i] = brightness / grayscaleVal;
			// green
			data[i + 1] = brightness / grayscaleVal;
			// blue
			data[i + 2] = brightness / grayscaleVal;
		}
		// overwrite original image
		ctx.putImageData(imageData, x, y); //przetworzone dane umieść z powrotem na danej pozycji x i y

	}

	grayscaleRangeSlider.on("input", function(event) {

		var imgList = $("#imgContainer").find("img");

		if (imgList.length == 1) {
			canvas.parentNode.insertBefore(originalPhoto.cloneNode(true), canvas);
		}

		$("#form1").find("img").css("display", "none");

		drawImage(document.getElementById("userPhoto"));
	});

	resetBtn.on("click", function(event) {
		ctx.drawImage(originalPhoto, 0, 0);
	});

	//przycinanie obrazu

	// window.onload(function() {

	// 	ctx.beginPath();
	// 	ctx.rect(canvas.width / 2, canvas.height / 2, 187, 251);
	// 	ctx.clip();
	// 	ctx.scale(2, 2);
	// 	ctx.drawImage(userPhoto);

	// });

	//Zoom-in, Zoom-out

	zoomIn.addEventListener("click", function(event) {
		ctx.scale(0.99, 0.99);
		ctx.drawImage(originalPhoto, 0, 0);
	}, false);

	zoomOut.addEventListener("click", function(event) {
		ctx.scale(1.01, 1.01);
		ctx.drawImage(originalPhoto, 0, 0);
	}, false);

	//Move

	moveTop.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		y -= 2;
	}, false);

	moveRight.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		x -= 2;
	}, false);

	moveLeft.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		x += 2;
	}, false);

	moveBottom.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		y += 2;
	}, false);

	//Rotation

	rotateControl.addEventListener("click", function(event) {
		if (deg == 1) {
			deg -= 16;
		} else {
			deg -= 15;
		}
		ctx.save();
		ctx.translate(93.5, 125.5);
		ctx.rotate(deg * Math.PI / 180);
		ctx.translate(-93.5, -125.5);
		ctx.drawImage(originalPhoto, 0, 0);
		ctx.restore();
	}, false);

});<commit_msg>Rewrite the code to Vanilla JS.<commit_after>$(document).ready(function() {

	// Upload a photo

	var uploadPhoto = document.getElementById("uploadPhotoBtn");
	var userPhoto = document.getElementById("userPhoto");
	var imageObj = new Image();

	var grayscaleBtn = document.getElementsByTagName("button")[0];
	var canvas = document.getElementById("imgCanvas");
	var originalPhoto = document.getElementById("userPhoto");
	var grayscaleRangeSlider = document.getElementById("grayscaleRange");
	var brightenRangeSlider = document.getElementById("brightenRange");
	var blurRangeSlider = document.getElementById("blurRange");
	var resetBtn = document.getElementById("resetBtn");
	var ctx = canvas.getContext("2d");

	var moveTop = document.getElementById("moveTop");
	var moveRight = document.getElementById("moveRight");
	var moveLeft = document.getElementById("moveLeft");
	var moveBottom = document.getElementById("moveBottom");

	var zoomIn = document.getElementById("zoom-in");
	var zoomOut = document.getElementById("zoom-out");

	var rotateControl = document.querySelector(".rotation-circle");

	var x = 0;
	var y = 0;
	var deg = 1;

	function readURL(input) {
		if (input.files && input.files[0]) {
			var reader = new FileReader();

			reader.onload = function(event) {
				userPhoto.setAttribute("src", event.target.result);
			}

			reader.readAsDataURL(input.files[0]);
		}
	}

	uploadPhoto.addEventListener("change", function(event) {
		readURL(this);
	}, false);

	//Filters - Grayscale

	function drawImage(imageObj) {

		var grayscaleVal = grayscaleRangeSlider.value * 0.01;

		ctx.drawImage(imageObj, x, y); //namaluj mi nowy obraz na jakimś x i jakimś y

		var imageData = ctx.getImageData(x, y, imageObj.width, imageObj.height);
		//pobierz pozycję i wymiary z kontekstu
		var data = imageData.data;
		//zapisz te dane do zmiennej data, imageData.data przechowuje wartości poszczególnych pikseli (0-255)

		for (var i = 0; i < data.length; i += 4) {
			var brightness = 0.34 * data[i] + 0.5 * data[i + 1] + 0.16 * data[i + 2];
			// red
			data[i] = brightness / grayscaleVal;
			// green
			data[i + 1] = brightness / grayscaleVal;
			// blue
			data[i + 2] = brightness / grayscaleVal;
		}
		// overwrite original image
		ctx.putImageData(imageData, x, y); //przetworzone dane umieść z powrotem na danej pozycji x i y

	}

	grayscaleRangeSlider.addEventListener("input", function(event) {

		var imgContainer = document.querySelector("#imgContainer");
		var imgList = imgContainer.getElementsByTagName("img");
		var form1 = document.querySelector("#form1");
		var imgHide = form1.getElementsByTagName("img")[0];

		if (imgList.length == 1) {
			canvas.parentNode.insertBefore(originalPhoto.cloneNode(true), canvas);
		}

		imgHide.style.display = "none";
		drawImage(userPhoto);

	}, false);

	resetBtn.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, 0, 0);
	}, false);

	//przycinanie obrazu

	// window.onload(function() {

	// 	ctx.beginPath();
	// 	ctx.rect(canvas.width / 2, canvas.height / 2, 187, 251);
	// 	ctx.clip();
	// 	ctx.scale(2, 2);
	// 	ctx.drawImage(userPhoto);

	// });

	//Zoom-in, Zoom-out

	zoomIn.addEventListener("click", function(event) {
		ctx.scale(0.99, 0.99);
		ctx.drawImage(originalPhoto, 0, 0);
	}, false);

	zoomOut.addEventListener("click", function(event) {
		ctx.scale(1.01, 1.01);
		ctx.drawImage(originalPhoto, 0, 0);
	}, false);

	//Move

	moveTop.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		y -= 2;
	}, false);

	moveRight.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		x -= 2;
	}, false);

	moveLeft.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		x += 2;
	}, false);

	moveBottom.addEventListener("click", function(event) {
		ctx.drawImage(originalPhoto, x, y);
		y += 2;
	}, false);

	//Rotation

	rotateControl.addEventListener("click", function(event) {
		if (deg == 1) {
			deg -= 16;
		} else {
			deg -= 15;
		}
		ctx.save();
		ctx.translate(93.5, 125.5);
		ctx.rotate(deg * Math.PI / 180);
		ctx.translate(-93.5, -125.5);
		ctx.drawImage(originalPhoto, 0, 0);
		ctx.restore();
	}, false);

});<|endoftext|>


<commit_before>(function($)
{
  var router = new $.mobile.Router( [
    {"#page-authorize": {handler: "pageAuthorize",
        events: "s", // do when we show the page
        argsre: true
    } },
    {"#home": {handler: "home",
  		  events: "s", // do when we show the page
  		  argsre: true
		} },

    {"#listing": {handler: "listing",
  	    events: "s", // do when we create the page
  	    argsre: true
    } },
    {"#registering-ruleset": {handler: "registeringRuleset",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#confirming-deletion": {handler: "confirmingDeletion",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#updating-url": {handler: "updatingUrl",
    		events: "s", // do when we show the page
    		argsre: true
		} },
    {"#page-picologging": {handler: "picologging",
		    events: "bs", // do when we show the page
		    argsre: true
    } },
    {"#page-installed-rulesets": {handler: "installed_rulesets",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#install-ruleset": {handler: "install_ruleset",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#confirm-uninstall-ruleset": {handler: "uninstall_ruleset",
				events: "bs", // do when we show the page
				argsre: true

    } }
    ],
      {
        pageAuthorize: function(type, match, ui, page) {
          console.log("manage fuse: authorize page");
          $.mobile.loading("hide");
        },

        home: function(type, match, ui, page) {
          console.log("home Handler");
          $.mobile.loading("hide");
        },

        listing: function(type, match, ui, page) {
          console.log("listing Handler");
          $("#manage-list" ).empty();

          Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
            console.log("attempting rough listview");
            //    var keys = rids_json.sort(sortBy("rid_index"));
            $.each(rids_json, paint_item);
            console.log("refreshing manage-list listview.");
            $('#manage-list').listview('refresh');
          });

        },

        registeringRuleset: function(type, match, ui, page) {

          console.log("registering Ruleset Handler");
          var frm = "#formRegisterNewRuleset";
            $(frm)[0].reset(); // clear the fields in the form
          $('#regester-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "registering ruleset...",
              textVisible: true
            });
            var registering_form_data = process_form(frm);
            console.log(">>>>>>>>> RID to register", registering_form_data);
            var appURL = registering_form_data.appURL;

            if(typeof appURL !== "undefined") {
              Devtools.RegisterRuleset(appURL, function(directives) {
                console.log("registered ", appURL, directives);
                $.mobile.changePage("#listing", {
                 transition: 'slide'
               });
              });
            }
          });

        },

        confirmingDeletion: function(type, match, ui, page) {
          console.log("confirming Deletion Handler");
        },

        updatingUrl: function(type, match, ui, page) {
          console.log("updating Url Handler");
            var frm = "#form-update-url";
            $(frm)[0].reset(); // clear the fields in the form
          var rid = router.getParams(match[1])["rid"]; //not sure if this will still work
          console.log("RID to update URL of: ", rid);

          var frmLabel = "Update " + rid + "'s URL:";
          $(".urlLabel").append(frmLabel);

          $('#update-url-confirm-button').off('tap').on('tap', function(event)
          {
            $.mobile.loading("show", {
              text: "Updating URL...",
              textVisible: true
            });
            var update_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", update_form_data);
            var url = update_form_data.url;

            if(typeof url !== "undefined") {
                Devtools.updateUrl(rid, url, function(directives){
                  console.log("updating the function is running", rid, directives);
                  $.mobile.changePage("#listing", {
                    transition: 'slide'
                   });
                });

            }
          });
        },

        picologging: function(type, match, ui, page) {
          console.log("pico logging page");
          $.mobile.loading("hide");

          function populate_logpage() {
            Pico.logging.status(CloudOS.defaultECI, function(json){
              console.log("Logging status: ", json);
              if(json) {
               $("#logstatus").val("on").slider("refresh");
               $("#loglist" ).empty();
               Pico.logging.getLogs(CloudOS.defaultECI, function(logdata){
                 console.log("Retrieved logs");
                 $.each(logdata, function(i, logobj) {
                  var eid_re = RegExp("\\s+" + logobj.eid);
                  logobj.log_items = logobj.log_items.map(function(i){ return i.replace(eid_re, '');
                  });
                  $("#loglist" ).append(
                   snippets.logitem_template(logobj)
                   ).collapsibleset().collapsibleset( "refresh" );
                  $("#loglist").listview("refresh");
                 });
               });

              } else {
               $("#logstatus").val("off").slider("refresh");
              }
            });
          }

          populate_logpage();

        	    // triggers
              $("#logstatus").unbind("change").change(function(){
                var newstatus = $("#logstatus").val();
                if(newstatus === "on") {
                  Pico.logging.reset(CloudOS.defaultECI, {});
                  populate_logpage();
                } else {
                  Pico.logging.inactive(CloudOS.defaultECI, {});
                  $("#loglist" ).empty();
                }
              });
              $( "#logrefresh" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                populate_logpage();
              });
              $( "#logclear" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                Pico.logging.flush(CloudOS.defaultECI, {});
              });

          },

        installed_rulesets: function(type, match, ui, page) {
          console.log("ruleset installation page");
          $.mobile.loading("hide");

          function populate_installed_rulesets() {
            $("#installed-rulesets" ).empty();
            Devtools.showInstalledRulesets(function(ruleset_list){
             console.log("Retrieved installed rulesets");
             $.each(ruleset_list, function(k, ruleset) {
               ruleset["rid"] = k;
      			    ruleset["OK"] = k !== "a169x625.prod"; // don't allow deletion of CloudOS; this could be more robust
      			    $("#installed-rulesets" ).append(
                 snippets.installed_ruleset_template(ruleset)
                 ).collapsibleset().collapsibleset( "refresh" );
      			    $("#installed-rulesets").listview("refresh");
             });
           });
          };

          populate_installed_rulesets();

          },

        uninstall_ruleset: function(type, match, ui, page) {
           console.log("Showing uninstall ruleset page");
           $.mobile.loading("hide");
           var rid = router.getParams(match[1])["rid"];
           console.log("RID to uninstall: ", rid);
           $("#remove-ruleset" ).empty();
           $("#remove-ruleset").append(snippets.confirm_ruleset_remove({"rid": rid}));
           $("#remove-ruleset").listview().listview("refresh");
           $('#remove-ruleset-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Uninstalling ruleset...",
              textVisible: true
            });
            console.log("Uninstalling RID ", rid);
            if(typeof rid !== "undefined") {
              Devtools.uninstallRulesets(rid, function(directives) {
                console.log("uninstalled ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
           });
      	},

      	install_ruleset: function(type, match, ui, page) {
         console.log("Showing install ruleset page");
         $.mobile.loading("hide");
         var frm = "#form-install-ruleset";
      	    $(frm)[0].reset(); // clear the fields in the form
            $('#install-ruleset-confirm-button').off('tap').on('tap', function(event)
	    {
		$.mobile.loading("show", {
		    text: "Installing ruleset...",
		    textVisible: true
		});
		var install_form_data = process_form(frm);
		console.log(">>>>>>>>> RIDs to install", install_form_data);
		var rid = install_form_data.rid;

		if( typeof rid !== "undefined"
		 && rid.match(/^[A-Za-z][\w\d]+\.[\w\d]+$/) // valid RID
		  ) {
		      Devtools.installRulesets(rid, function(directives) {
			  console.log("installed ", rid, directives);
			  $.mobile.changePage("#page-installed-rulesets", {
			      transition: 'slide'
			  });
		      });
		  } else {
		      console.log("Invalid rid ", rid);
		  }
            });
        }

      },

      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route:", type, ui, page );
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });

      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
          list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
          logitem_template: Handlebars.compile($("#logitem-template").html() || ""),
          installed_ruleset_template: Handlebars.compile($("#installed-ruleset-template").html() || ""),
	        confirm_ruleset_remove: Handlebars.compile($("#confirm-ruleset-remove-template").html() || "")
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

      function onPageLoad() {// Document.Ready
      	console.log("document ready");
        CloudOS.retrieveSession();
  	    // only put static stuff here...
  	    plant_authorize_button();

  	    $('.logout').off("tap").on("tap", function(event)
        {
  	      CloudOS.removeSession(true); // true for hard reset (log out of login server too)
  	      $.mobile.changePage('#page-authorize', {
            transition: 'slide'
  	      }); // this will go to the authorization page.
        });

        Handlebars.registerHelper('ifDivider', function(v1, options) {
         if(v1.match(/-----\*\*\*----/)) {
          return options.fn(this);
         }
          return options.inverse(this);
         });

        console.log("Choose page to show");

        try {
          var authd = CloudOS.authenticatedSession();
          if(authd) {
            console.log("Authorized");
            document.location.hash = "#home";
          } else {
            console.log("Asking for authorization");
            document.location.hash = "#page-authorize";
          }
        } catch (exception) {

        } finally {
          $.mobile.initializePage();
          $.mobile.loading("hide");
        }

      }

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
      $(document).bind("mobileinit", onMobileInit);
      $(document).ready(onPageLoad);
  })(jQuery);

  function clear_error_msg(frm) {// we dont have #error-msg ---------------
       $("#error-msg", frm).html("").hide();
  }
  function sortBy(prop){

    return function(a,b){

    //if a and b match regex /\w+\d+xd+\.\w+/
    // split on .
      // split on x
        //compare
      if( a[prop] < b[prop]){
        return 1;
      }else if( a[prop] > b[prop] ){
        return -1;
      }
      return 0;
    };
  };

  function paint_item(id, rids) {
    var status = "no status"; // place holder for description
    //console.log("rid: "+ rids.rid);

    $('#manage-list').append(
      snippets.list_rulesets_template(
        {"rid": rids["rid"],
        "uri": rids["uri"]}
      )
    );
  };

  var sortByName = function (a, b) {
  	if (a.name > b.name) {
  	    return 1;
  	}
  	if (a.name < b.name) {
  	    return -1;
  	}
  	// a must be equal to b
  	return 0;
  };

    // process an array of objects from a form to be a proper object
  var process_form_results = function(raw_results) {
  	var results = {};
  	$.each(raw_results, function(i, v) {
  		var nym = v.name,
   	  val = v.value;
  		if (results[nym] && results[nym] instanceof Array) {
  		  results[nym].push(val);
  		} else if (results[nym]) {
  		  results[nym] = [results[nym], val];
  		} else {
  		  results[nym] = val;
  		}
  	});
  	return results;
  };

  var process_form = function(frm) {
	 var results = process_form_results($(frm).serializeArray());
	 return results;
  };

<commit_msg>Go somewhere useful<commit_after>(function($)
{
  var router = new $.mobile.Router( [
    {"#page-authorize": {handler: "pageAuthorize",
        events: "s", // do when we show the page
        argsre: true
    } },
    {"#home": {handler: "home",
  		  events: "s", // do when we show the page
  		  argsre: true
		} },

    {"#listing": {handler: "listing",
  	    events: "s", // do when we create the page
  	    argsre: true
    } },
    {"#registering-ruleset": {handler: "registeringRuleset",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#confirming-deletion": {handler: "confirmingDeletion",
  			events: "s", // do when we show the page
  			argsre: true
    } },
    {"#updating-url": {handler: "updatingUrl",
    		events: "s", // do when we show the page
    		argsre: true
		} },
    {"#page-picologging": {handler: "picologging",
		    events: "bs", // do when we show the page
		    argsre: true
    } },
    {"#page-installed-rulesets": {handler: "installed_rulesets",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#install-ruleset": {handler: "install_ruleset",
		    events: "bs", // do when we show the page
		    argsre: true
		} },
    {"#confirm-uninstall-ruleset": {handler: "uninstall_ruleset",
				events: "bs", // do when we show the page
				argsre: true

    } }
    ],
      {
        pageAuthorize: function(type, match, ui, page) {
          console.log("manage fuse: authorize page");
          $.mobile.loading("hide");
        },

        home: function(type, match, ui, page) {
          console.log("home Handler");
          $.mobile.loading("hide");
        },

        listing: function(type, match, ui, page) {
          console.log("listing Handler");
          $("#manage-list" ).empty();

          Devtools.getRulesets(function(rids_json){ //the callback/function is where we need to have all of our code
            console.log("attempting rough listview");
            //    var keys = rids_json.sort(sortBy("rid_index"));
            $.each(rids_json, paint_item);
            console.log("refreshing manage-list listview.");
            $('#manage-list').listview('refresh');
          });

        },

        registeringRuleset: function(type, match, ui, page) {

          console.log("registering Ruleset Handler");
          var frm = "#formRegisterNewRuleset";
            $(frm)[0].reset(); // clear the fields in the form
          $('#regester-ruleset-confirm-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "registering ruleset...",
              textVisible: true
            });
            var registering_form_data = process_form(frm);
            console.log(">>>>>>>>> RID to register", registering_form_data);
            var appURL = registering_form_data.appURL;

            if(typeof appURL !== "undefined") {
              Devtools.RegisterRuleset(appURL, function(directives) {
                console.log("registered ", appURL, directives);
                $.mobile.changePage("#listing", {
                 transition: 'slide'
               });
              });
            }
          });

        },

        confirmingDeletion: function(type, match, ui, page) {
          console.log("confirming Deletion Handler");
        },

        updatingUrl: function(type, match, ui, page) {
          console.log("updating Url Handler");
            var frm = "#form-update-url";
            $(frm)[0].reset(); // clear the fields in the form
          var rid = router.getParams(match[1])["rid"]; //not sure if this will still work
          console.log("RID to update URL of: ", rid);

          var frmLabel = "Update " + rid + "'s URL:";
          $(".urlLabel").append(frmLabel);

          $('#update-url-confirm-button').off('tap').on('tap', function(event)
          {
            $.mobile.loading("show", {
              text: "Updating URL...",
              textVisible: true
            });
            var update_form_data = process_form(frm);
            console.log(">>>>>>>>> RIDs to install", update_form_data);
            var url = update_form_data.url;

            if(typeof url !== "undefined") {
                Devtools.updateUrl(rid, url, function(directives){
                  console.log("updating the function is running", rid, directives);
                  $.mobile.changePage("#listing", {
                    transition: 'slide'
                   });
                });

            }
          });
        },

        picologging: function(type, match, ui, page) {
          console.log("pico logging page");
          $.mobile.loading("hide");

          function populate_logpage() {
            Pico.logging.status(CloudOS.defaultECI, function(json){
              console.log("Logging status: ", json);
              if(json) {
               $("#logstatus").val("on").slider("refresh");
               $("#loglist" ).empty();
               Pico.logging.getLogs(CloudOS.defaultECI, function(logdata){
                 console.log("Retrieved logs");
                 $.each(logdata, function(i, logobj) {
                  var eid_re = RegExp("\\s+" + logobj.eid);
                  logobj.log_items = logobj.log_items.map(function(i){ return i.replace(eid_re, '');
                  });
                  $("#loglist" ).append(
                   snippets.logitem_template(logobj)
                   ).collapsibleset().collapsibleset( "refresh" );
                  $("#loglist").listview("refresh");
                 });
               });

              } else {
               $("#logstatus").val("off").slider("refresh");
              }
            });
          }

          populate_logpage();

        	    // triggers
              $("#logstatus").unbind("change").change(function(){
                var newstatus = $("#logstatus").val();
                if(newstatus === "on") {
                  Pico.logging.reset(CloudOS.defaultECI, {});
                  populate_logpage();
                } else {
                  Pico.logging.inactive(CloudOS.defaultECI, {});
                  $("#loglist" ).empty();
                }
              });
              $( "#logrefresh" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                populate_logpage();
              });
              $( "#logclear" ).unbind("click").click(function(event, ui) {
                $("#loglist" ).empty();
                Pico.logging.flush(CloudOS.defaultECI, {});
              });

          },

        installed_rulesets: function(type, match, ui, page) {
          console.log("ruleset installation page");
          $.mobile.loading("hide");

          function populate_installed_rulesets() {
            $("#installed-rulesets" ).empty();
            Devtools.showInstalledRulesets(function(ruleset_list){
             console.log("Retrieved installed rulesets");
             $.each(ruleset_list, function(k, ruleset) {
               ruleset["rid"] = k;
      			    ruleset["OK"] = k !== "a169x625.prod"; // don't allow deletion of CloudOS; this could be more robust
      			    $("#installed-rulesets" ).append(
                 snippets.installed_ruleset_template(ruleset)
                 ).collapsibleset().collapsibleset( "refresh" );
      			    $("#installed-rulesets").listview("refresh");
             });
           });
          };

          populate_installed_rulesets();

          },

        uninstall_ruleset: function(type, match, ui, page) {
           console.log("Showing uninstall ruleset page");
           $.mobile.loading("hide");
           var rid = router.getParams(match[1])["rid"];
           console.log("RID to uninstall: ", rid);
           $("#remove-ruleset" ).empty();
           $("#remove-ruleset").append(snippets.confirm_ruleset_remove({"rid": rid}));
           $("#remove-ruleset").listview().listview("refresh");
           $('#remove-ruleset-button').off('tap').on('tap', function(event)
           {
            $.mobile.loading("show", {
              text: "Uninstalling ruleset...",
              textVisible: true
            });
            console.log("Uninstalling RID ", rid);
            if(typeof rid !== "undefined") {
              Devtools.uninstallRulesets(rid, function(directives) {
                console.log("uninstalled ", rid, directives);
                $.mobile.changePage("#page-installed-rulesets", {
                 transition: 'slide'
               });
              });
            }
           });
      	},

      	install_ruleset: function(type, match, ui, page) {
         console.log("Showing install ruleset page");
         $.mobile.loading("hide");
         var frm = "#form-install-ruleset";
      	    $(frm)[0].reset(); // clear the fields in the form
            $('#install-ruleset-confirm-button').off('tap').on('tap', function(event)
	    {
		$.mobile.loading("show", {
		    text: "Installing ruleset...",
		    textVisible: true
		});
		var install_form_data = process_form(frm);
		console.log(">>>>>>>>> RIDs to install", install_form_data);
		var rid = install_form_data.rid;

		if( typeof rid !== "undefined"
		 && rid.match(/^[A-Za-z][\w\d]+\.[\w\d]+$/) // valid RID
		  ) {
		      Devtools.installRulesets(rid, function(directives) {
			  console.log("installed ", rid, directives);
			  $.mobile.changePage("#page-installed-rulesets", {
			      transition: 'slide'
			  });
		      });
		  } else {
		      console.log("Invalid rid ", rid);
		      $.mobile.loading("hide");
		      $.mobile.changePage("#page-installed-rulesets", {
			  transition: 'slide'
		      });
		  }
            });
        }

      },

      {
        defaultHandler: function(type, ui, page) {
          console.log("Default handler called due to unknown route:", type, ui, page );
        },
        defaultHandlerEvents: "s",
        defaultArgsRe: true

      });

      // Handlebar templates compiled at load time to create functions
      // templates are included to index.html from Templates directory.
      window['snippets'] = {
          list_rulesets_template: Handlebars.compile($("#list-rulesets-template").html() || ""),
          logitem_template: Handlebars.compile($("#logitem-template").html() || ""),
          installed_ruleset_template: Handlebars.compile($("#installed-ruleset-template").html() || ""),
	        confirm_ruleset_remove: Handlebars.compile($("#confirm-ruleset-remove-template").html() || "")
      };

      function plant_authorize_button()
      {
        //Oauth through kynetx
        console.log("plant authorize button");
        var OAuth_kynetx_URL = CloudOS.getOAuthURL();
        $('#authorize-link').attr('href', OAuth_kynetx_URL);
        var OAuth_kynetx_newuser_URL = CloudOS.getOAuthNewAccountURL();
        $('#create-link').attr('href', OAuth_kynetx_newuser_URL);
      }

      function onMobileInit() {
       console.log("mobile init");
       $.mobile.autoInitialize = false;
     }

      function onPageLoad() {// Document.Ready
      	console.log("document ready");
        CloudOS.retrieveSession();
  	    // only put static stuff here...
  	    plant_authorize_button();

  	    $('.logout').off("tap").on("tap", function(event)
        {
  	      CloudOS.removeSession(true); // true for hard reset (log out of login server too)
  	      $.mobile.changePage('#page-authorize', {
            transition: 'slide'
  	      }); // this will go to the authorization page.
        });

        Handlebars.registerHelper('ifDivider', function(v1, options) {
         if(v1.match(/-----\*\*\*----/)) {
          return options.fn(this);
         }
          return options.inverse(this);
         });

        console.log("Choose page to show");

        try {
          var authd = CloudOS.authenticatedSession();
          if(authd) {
            console.log("Authorized");
            document.location.hash = "#home";
          } else {
            console.log("Asking for authorization");
            document.location.hash = "#page-authorize";
          }
        } catch (exception) {

        } finally {
          $.mobile.initializePage();
          $.mobile.loading("hide");
        }

      }

    /////////////////////////////////////////////////////////////////////
    // this is the actual code that runs and sets everything off
    // pull the session out of the cookie.
      $(document).bind("mobileinit", onMobileInit);
      $(document).ready(onPageLoad);
  })(jQuery);

  function clear_error_msg(frm) {// we dont have #error-msg ---------------
       $("#error-msg", frm).html("").hide();
  }
  function sortBy(prop){

    return function(a,b){

    //if a and b match regex /\w+\d+xd+\.\w+/
    // split on .
      // split on x
        //compare
      if( a[prop] < b[prop]){
        return 1;
      }else if( a[prop] > b[prop] ){
        return -1;
      }
      return 0;
    };
  };

  function paint_item(id, rids) {
    var status = "no status"; // place holder for description
    //console.log("rid: "+ rids.rid);

    $('#manage-list').append(
      snippets.list_rulesets_template(
        {"rid": rids["rid"],
        "uri": rids["uri"]}
      )
    );
  };

  var sortByName = function (a, b) {
  	if (a.name > b.name) {
  	    return 1;
  	}
  	if (a.name < b.name) {
  	    return -1;
  	}
  	// a must be equal to b
  	return 0;
  };

    // process an array of objects from a form to be a proper object
  var process_form_results = function(raw_results) {
  	var results = {};
  	$.each(raw_results, function(i, v) {
  		var nym = v.name,
   	  val = v.value;
  		if (results[nym] && results[nym] instanceof Array) {
  		  results[nym].push(val);
  		} else if (results[nym]) {
  		  results[nym] = [results[nym], val];
  		} else {
  		  results[nym] = val;
  		}
  	});
  	return results;
  };

  var process_form = function(frm) {
	 var results = process_form_results($(frm).serializeArray());
	 return results;
  };

<|endoftext|>


<commit_before>"use strict";

var baseDataUrl = 'http://labs.atsid.com/hubhacks2/data/';

requirejs.config({
    'baseUrl': 'js/lib',
    'paths': {
        'app': '../app',
        'jquery': 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min',
        'jqueryui': 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min'
    },
    'config': {
        'app/main': {
            census_url: 'http://api.census.gov/data/2013/acs5?get=B19013_001E,B01003_001E&for=tract:*&in=state:25+county:*',
            colors: ['#D8A97B', '#BC9E78', '#9F9275', '#828571', '#65796D', '#4F5C4B'],
            color_labels: ['<$20,000', '$20,000 - $60,000', '$60,000 - $80,000', '$80,000 - $100,000', '$100,000 - $150,000', '>$150,000']
        },
        'app/map': {
            //starting zoom and map centering options
            map: {
                center: { lat: 42.3601, lng: -71.0589 },
                zoom: 12
            },
            element: '#map-canvas'
        },
        'app/renderers/census_renderer': {
            //http://www.colourlovers.com/palette/84571/echo
            colors: ['#D8A97B', '#BC9E78', '#9F9275', '#828571', '#65796D', '#4F5C4B'],
            //this is pretty arbitrary, but ramps up to capture a little more granularity in the more common < 100k bins
            income_bins: [20000, 60000, 80000, 100000, 150000, 500000]
        },
        'app/features': {
            //these are the geojson opts used for maps api loadGeoJson
            opts: { idPropertyName: 'GEOID' }
        },
        //field codes documented here: http://www2.census.gov/geo/tiger/TIGER_DP/2013ACS/Metadata/County_and_Place_Metadata_2013.txt
        'app/fields': {
            INCOME: {
                key: 'B19013_001E'
            },
            POP: {
                key: 'B01003_001E'
            },
            SQ_MILE: {
                calc: function (feature) {
                    return (feature.getProperty('ALAND') * (3.86102e-7)).toFixed(3);
                }
            },
            DENSITY: {
                calc: function (feature) {
                    return Math.round(feature.getProperty('POP') / feature.getProperty('SQ_MILE'));
                }
            }
        },
        'app/stats': {
            keys: ['B19013_001E', 'B01003_001E']
        },
        'app/layers': {
            linterUrl: 'http://geojsonlint.com/validate',
            validate: false,
            tables: {
                'license_liquor' : {
                    type: 'geojson',
                    field: 'address',
                    url: baseDataUrl + 'liquor.geojson',
                    template: 2,
                    style: 2
                },
                'license_food': {
                    type: 'geojson',
                    field: 'address',
                    url: baseDataUrl + 'food.geojson',
                    template: 1,
                    style: 1
                },
                'license_entertainment': {
                    type: 'geojson',
                    field: 'address',
                    url: baseDataUrl + 'entertainment.geojson',
                    template: 3,
                    style: 3
                },
                'census_geography': {
                    type: 'geojson',
                    url: baseDataUrl + 'cb_2013_25_tract_500k.geojson'
                }
            }
        }
    }
});

requirejs(['app/main'], function (app) {
    app.initialize();
});
<commit_msg>auto-config data location based on local or remote<commit_after>"use strict";

var baseDataUrl = window.location.hostname === 'localhost' ? 'data/' : 'http://labs.atsid.com/hubhacks2/data/';

requirejs.config({
    'baseUrl': 'js/lib',
    'paths': {
        'app': '../app',
        'jquery': 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min',
        'jqueryui': 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min'
    },
    'config': {
        'app/main': {
            census_url: 'http://api.census.gov/data/2013/acs5?get=B19013_001E,B01003_001E&for=tract:*&in=state:25+county:*',
            colors: ['#D8A97B', '#BC9E78', '#9F9275', '#828571', '#65796D', '#4F5C4B'],
            color_labels: ['<$20,000', '$20,000 - $60,000', '$60,000 - $80,000', '$80,000 - $100,000', '$100,000 - $150,000', '>$150,000']
        },
        'app/map': {
            //starting zoom and map centering options
            map: {
                center: { lat: 42.3601, lng: -71.0589 },
                zoom: 12
            },
            element: '#map-canvas'
        },
        'app/renderers/census_renderer': {
            //http://www.colourlovers.com/palette/84571/echo
            colors: ['#D8A97B', '#BC9E78', '#9F9275', '#828571', '#65796D', '#4F5C4B'],
            //this is pretty arbitrary, but ramps up to capture a little more granularity in the more common < 100k bins
            income_bins: [20000, 60000, 80000, 100000, 150000, 500000]
        },
        'app/features': {
            //these are the geojson opts used for maps api loadGeoJson
            opts: { idPropertyName: 'GEOID' }
        },
        //field codes documented here: http://www2.census.gov/geo/tiger/TIGER_DP/2013ACS/Metadata/County_and_Place_Metadata_2013.txt
        'app/fields': {
            INCOME: {
                key: 'B19013_001E'
            },
            POP: {
                key: 'B01003_001E'
            },
            SQ_MILE: {
                calc: function (feature) {
                    return (feature.getProperty('ALAND') * (3.86102e-7)).toFixed(3);
                }
            },
            DENSITY: {
                calc: function (feature) {
                    return Math.round(feature.getProperty('POP') / feature.getProperty('SQ_MILE'));
                }
            }
        },
        'app/stats': {
            keys: ['B19013_001E', 'B01003_001E']
        },
        'app/layers': {
            linterUrl: 'http://geojsonlint.com/validate',
            validate: false,
            tables: {
                'license_liquor' : {
                    type: 'geojson',
                    field: 'address',
                    url: baseDataUrl + 'liquor.geojson',
                    template: 2,
                    style: 2
                },
                'license_food': {
                    type: 'geojson',
                    field: 'address',
                    url: baseDataUrl + 'food.geojson',
                    template: 1,
                    style: 1
                },
                'license_entertainment': {
                    type: 'geojson',
                    field: 'address',
                    url: baseDataUrl + 'entertainment.geojson',
                    template: 3,
                    style: 3
                },
                'census_geography': {
                    type: 'geojson',
                    url: baseDataUrl + 'cb_2013_25_tract_500k.geojson'
                }
            }
        }
    }
});

requirejs(['app/main'], function (app) {
    app.initialize();
});
<|endoftext|>


<commit_before>var MenuItem = Backbone.Model.extend({
    defaults: {
	id: '',
	name: '',
	img: '',
	calories: 0,
	rating: 0,
	description: ''
    }
});

var MenuItemsCollection = Backbone.Collection.extend({
    model: MenuItem
});

var item1 = new MenuItem({
    id: 'chicken-pomegranate-salad',
    name: 'Chicken Pomegranate Salad',
    image: 'chicken-pomegranate-salad.jpg',
    calories: 430,
    rating: 4.1,
    description: 'A simple, sweet and delicious salad of chicken, pomegranates, spinach, and spiced candied walnuts. Served with a side of citrus vinaigrette.',
    source: 'https://www.pexels.com/photo/salad-pomegranate-chicken-spinach-5916/',
    photographer: 'Karolina Grabowska.STAFFAGE'
});

var item2 = new MenuItem({
    id: 'strawberry-pudding',
    name: 'Strawberry Pudding',
    image: 'strawberry-pudding.jpg',
    calories: 280,
    rating: 5,
    description: 'A sweet and tasty pudding filled with strawyberries, blueberries, and raspberries.',
    source: 'https://www.pexels.com/photo/restaurant-dessert-pudding-strawberries-3674/',
    photographer: ''
});

var item3 = new MenuItem({
    id: 'ham-goat-cheese-croissant',
    name: 'Ham and Goat Cheese Croissant',
    image: 'ham-goat-cheese-croissant.jpg',
    calories: 670,
    rating: 3.9,
    description: 'A savory slice of ham topped with a wedge of goat cheese, all on a buttery, flaky croissant.',
    source: 'https://www.pexels.com/photo/croissant-bakery-plate-food-7390/',
    photographer: ''
});

var MenuItems = new MenuItemsCollection();
MenuItems.add(item1);
MenuItems.add(item2);
MenuItems.add(item3);

var MenuItemsView = Backbone.View.extend({

    el: '#table-body',

    initialize: function() {
	this.render();
	selectedItemView.render();
    },

    render: function() {
	this.$el.html('');

	MenuItems.each(function(model) {
	    var menuItem = new MenuItemView({
		model: model
	    });

	    this.$el.append(menuItem.render().el);
	}.bind(this));

	return this;
    }

});

var MenuItemView = Backbone.View.extend({

    tagName: 'tr',

    events: {
	'click .select-item': 'selectItem'
    },

    selectItem: function(e) {
	e.preventDefault();
	selectedItem.set('selected', true);
	selectedItem.set('item', this.model);
	selectedItemView.render();
    },

    template: _.template($('#menuItem-template').html(), {variable: 'menuItem'}),

    render: function() {
	this.$el.html(this.template(this.model.attributes));
	return this;
    }

});

var SelectedItem = Backbone.Model.extend({
    defaults: {
	selected: false,
	item: ''
    }
});

var selectedItem = new SelectedItem();

var SelectedItemView = Backbone.View.extend({
    model: selectedItem,

    el: '#selected-item',

    initialize: function() {
	this.model = selectedItem;
	this.render();
    },

    render: function() {
	var content;
	if (this.model.get('selected')) {
	    content = "You are going to eat: " + this.model.get('item').get('name');
	} else {
	    content = "Aren't you hungry? You have not picked anything to eat yet.";
	}

	this.$el.html(content);

	return this;
    }
});

var ItemDetails = Backbone.View.extend({
    el: '#details',

    events: {
	'click .close': 'hide'
    },

    template: _.template($('#itemDetails-template').html(), {variable: 'menuItem'}),

    hide: function() {
	this.$el.html('');
	foodRouter.navigate('');
    },

    render: function(id) {
	this.$el.html(this.template(MenuItems.get(id).attributes));
	return this;
    }
});

var selectedItemView = new SelectedItemView();
var itemDetails = new ItemDetails();
var app = new MenuItemsView();

var FoodRouter = Backbone.Router.extend({
    routes: {
	"": "home",
	"item/:id": "item"
    },

    home: function(){
    },

    item: function(id) {
	itemDetails.render(id);
    }
});

var foodRouter = new FoodRouter();

Backbone.history.start();
<commit_msg>clear details if loading home route<commit_after>var MenuItem = Backbone.Model.extend({
    defaults: {
	id: '',
	name: '',
	img: '',
	calories: 0,
	rating: 0,
	description: ''
    }
});

var MenuItemsCollection = Backbone.Collection.extend({
    model: MenuItem
});

var item1 = new MenuItem({
    id: 'chicken-pomegranate-salad',
    name: 'Chicken Pomegranate Salad',
    image: 'chicken-pomegranate-salad.jpg',
    calories: 430,
    rating: 4.1,
    description: 'A simple, sweet and delicious salad of chicken, pomegranates, spinach, and spiced candied walnuts. Served with a side of citrus vinaigrette.',
    source: 'https://www.pexels.com/photo/salad-pomegranate-chicken-spinach-5916/',
    photographer: 'Karolina Grabowska.STAFFAGE'
});

var item2 = new MenuItem({
    id: 'strawberry-pudding',
    name: 'Strawberry Pudding',
    image: 'strawberry-pudding.jpg',
    calories: 280,
    rating: 5,
    description: 'A sweet and tasty pudding filled with strawyberries, blueberries, and raspberries.',
    source: 'https://www.pexels.com/photo/restaurant-dessert-pudding-strawberries-3674/',
    photographer: ''
});

var item3 = new MenuItem({
    id: 'ham-goat-cheese-croissant',
    name: 'Ham and Goat Cheese Croissant',
    image: 'ham-goat-cheese-croissant.jpg',
    calories: 670,
    rating: 3.9,
    description: 'A savory slice of ham topped with a wedge of goat cheese, all on a buttery, flaky croissant.',
    source: 'https://www.pexels.com/photo/croissant-bakery-plate-food-7390/',
    photographer: ''
});

var MenuItems = new MenuItemsCollection();
MenuItems.add(item1);
MenuItems.add(item2);
MenuItems.add(item3);

var MenuItemsView = Backbone.View.extend({

    el: '#table-body',

    initialize: function() {
	this.render();
	selectedItemView.render();
    },

    render: function() {
	this.$el.html('');

	MenuItems.each(function(model) {
	    var menuItem = new MenuItemView({
		model: model
	    });

	    this.$el.append(menuItem.render().el);
	}.bind(this));

	return this;
    }

});

var MenuItemView = Backbone.View.extend({

    tagName: 'tr',

    events: {
	'click .select-item': 'selectItem'
    },

    selectItem: function(e) {
	e.preventDefault();
	selectedItem.set('selected', true);
	selectedItem.set('item', this.model);
	selectedItemView.render();
    },

    template: _.template($('#menuItem-template').html(), {variable: 'menuItem'}),

    render: function() {
	this.$el.html(this.template(this.model.attributes));
	return this;
    }

});

var SelectedItem = Backbone.Model.extend({
    defaults: {
	selected: false,
	item: ''
    }
});

var selectedItem = new SelectedItem();

var SelectedItemView = Backbone.View.extend({
    model: selectedItem,

    el: '#selected-item',

    initialize: function() {
	this.model = selectedItem;
	this.render();
    },

    render: function() {
	var content;
	if (this.model.get('selected')) {
	    content = "You are going to eat: " + this.model.get('item').get('name');
	} else {
	    content = "Aren't you hungry? You have not picked anything to eat yet.";
	}

	this.$el.html(content);

	return this;
    }
});

var ItemDetails = Backbone.View.extend({
    el: '#details',

    events: {
	'click .close': 'hide'
    },

    template: _.template($('#itemDetails-template').html(), {variable: 'menuItem'}),

    hide: function() {
	this.$el.html('');
	foodRouter.navigate('');
    },

    render: function(id) {
	this.$el.html(this.template(MenuItems.get(id).attributes));
	return this;
    },

    clear: function() {
	this.$el.html('');
    }
});

var selectedItemView = new SelectedItemView();
var itemDetails = new ItemDetails();
var app = new MenuItemsView();

var FoodRouter = Backbone.Router.extend({
    routes: {
	"": "home",
	"item/:id": "item"
    },

    home: function(){
	itemDetails.clear();
    },

    item: function(id) {
	itemDetails.render(id);
    }
});

var foodRouter = new FoodRouter();

Backbone.history.start();
<|endoftext|>


<commit_before>var map, infowindow;
localStorage.placeData = localStorage.placeData ? localStorage.placeData : "";

function initMap() {
    var customMapType = new google.maps.StyledMapType([
        {
            "featureType": "administrative",
            "elementType": "all",
            "stylers": [{
                "visibility": "on"
			}]
		}, {
            "featureType": "poi",
            "elementType": "all",
            "stylers": [{
                "visibility": "off"
			}]
		}, {
            "featureType": "road",
            "elementType": "all",
            "stylers": [{
                "color": "#bfbfbf"
			}]
		}, {
            "featureType": "landscape",
            "elementType": "all",
            "stylers": [{
                "color": "#ebebeb"
			}]
		}, {
            "featureType": "water",
            "elementType": "all",
            "stylers": [{
                "visibility": "simplified"
			}, {
                "color": "#006699"
			}]
		}, {
            "featureType": "road",
            "elementType": "labels",
            "stylers": [{
                "visibility": "off"
			}]
  }]);
    var customMapTypeId = 'custom_style';

    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 48.76034594263708,
            lng: 8.609468946875056
        },
        zoom: 5,
        zoomControl: false,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: false,
    });
    map.mapTypes.set(customMapTypeId, customMapType);
    map.setMapTypeId(customMapTypeId);
    infowindow = new google.maps.InfoWindow();

    function placeMapper(place) {
        //Here goes the stuff for the Infowindow
        var infowindowContent = "
" + place.Library + "

" + place.Quantity + "
" + '
<button type="button" class="btn btn-outline-info btn-outline">Browse the manuscripts</button>
';
        //Here goes the stuff for the Datatable
        var row = $("
" + "" + place.Nation + "	" + "" + place.City + "	" + "" + place.Library + "	" + "" + place.lat + "	" + "" + place.lng + "	" + "" + place.Quantity + "	" + "" + 'Browse the manuscripts' + "	" + "
");
        var clickToggle = function () {
            map.setCenter({
                lat: place.lat,
                lng: place.lng
            });
            map.setZoom(12);
            infowindow.setContent(infowindowContent);
            infowindow.open(map, marker);
            row.parent().find('tr').removeClass('bolderText');
            row.addClass('bolderText');

            //Smootly scroll up to the map when a row is clicked
            $('html, body').animate({
                scrollTop: $("#dmmmap").offset().top
            }, 500);

        }
        $("#datatablex").find('tbody').append(row);

        var marker = new google.maps.Marker({
            position: {
                lat: place.lat,
                lng: place.lng
            },
            map: map,
            title: place.Library
        });
        row.click(clickToggle);
        marker.addListener('click', clickToggle);
    }

    $(document).ready(function () {
        $.get('js/data.json', function (tabledata) {
            if (tabledata instanceof Array) {
                tabledata = tabledata.concat(JSON.parse("[" + localStorage.placeData.slice(0, -1) + "]") || []);
            } else {
                console.log("AJAX error");
                tabledata = JSON.parse("[" + localStorage.placeData.slice(0, -1) + "]") || [];
            }
            tabledata.map(placeMapper);
            //Datatable options go here!
            $('#datatablex').DataTable({
                "responsive": true,
                "processing": true,
                "columnDefs": [
                    {
                        "targets": [3],
                        "visible": false,
                        "searchable": false
            },
                    {
                        "targets": [4],
                        "visible": false,
                        "searchable": false
            },
                    {
                        responsivePriority: 1,
                        targets: 2
                    },
                    {
                        responsivePriority: 2,
                        targets: -1
                    }
        ]

            });
        });
        $('a[data-toggle="pill"]').on('click', function () {
            $('html,body').animate({
                scrollTop: $('#dmmtable').offset().top
            }, 500);
        });
    });
}

//FUTURE: Autofill?<commit_msg>No longer displaying link to libraries in table.<commit_after>var map, infowindow;
localStorage.placeData = localStorage.placeData ? localStorage.placeData : "";

function initMap() {
    var customMapType = new google.maps.StyledMapType([
        {
            "featureType": "administrative",
            "elementType": "all",
            "stylers": [{
                "visibility": "on"
			}]
		}, {
            "featureType": "poi",
            "elementType": "all",
            "stylers": [{
                "visibility": "off"
			}]
		}, {
            "featureType": "road",
            "elementType": "all",
            "stylers": [{
                "color": "#bfbfbf"
			}]
		}, {
            "featureType": "landscape",
            "elementType": "all",
            "stylers": [{
                "color": "#ebebeb"
			}]
		}, {
            "featureType": "water",
            "elementType": "all",
            "stylers": [{
                "visibility": "simplified"
			}, {
                "color": "#006699"
			}]
		}, {
            "featureType": "road",
            "elementType": "labels",
            "stylers": [{
                "visibility": "off"
			}]
  }]);
    var customMapTypeId = 'custom_style';

    map = new google.maps.Map(document.getElementById('map'), {
        center: {
            lat: 48.76034594263708,
            lng: 8.609468946875056
        },
        zoom: 5,
        zoomControl: false,
        mapTypeControl: false,
        scaleControl: false,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: false,
    });
    map.mapTypes.set(customMapTypeId, customMapType);
    map.setMapTypeId(customMapTypeId);
    infowindow = new google.maps.InfoWindow();

    function placeMapper(place) {
        //Here goes the stuff for the Infowindow
        var infowindowContent = "
" + place.Library + "

" + place.Quantity + "
" + '
<button type="button" class="btn btn-outline-info btn-outline">Browse the manuscripts</button>
';
        //Here goes the stuff for the Datatable
        var row = $("
" + "" + place.Nation + "	" + "" + place.City + "	" + "" + place.Library + "	" + "" + place.lat + "	" + "" + place.lng + "	" + "" + place.Quantity + "	" + "" + 'Browse the manuscripts' + "	" + "
");
        var clickToggle = function () {
            map.setCenter({
                lat: place.lat,
                lng: place.lng
            });
            map.setZoom(12);
            infowindow.setContent(infowindowContent);
            infowindow.open(map, marker);
            row.parent().find('tr').removeClass('bolderText');
            row.addClass('bolderText');

            //Smootly scroll up to the map when a row is clicked
            $('html, body').animate({
                scrollTop: $("#dmmmap").offset().top
            }, 500);

        }
        $("#datatablex").find('tbody').append(row);

        var marker = new google.maps.Marker({
            position: {
                lat: place.lat,
                lng: place.lng
            },
            map: map,
            title: place.Library
        });
        row.click(clickToggle);
        marker.addListener('click', clickToggle);
    }

    $(document).ready(function () {
        $.get('js/data.json', function (tabledata) {
            if (tabledata instanceof Array) {
                tabledata = tabledata.concat(JSON.parse("[" + localStorage.placeData.slice(0, -1) + "]") || []);
            } else {
                console.log("AJAX error");
                tabledata = JSON.parse("[" + localStorage.placeData.slice(0, -1) + "]") || [];
            }
            tabledata.map(placeMapper);
            //Datatable options go here!
            $('#datatablex').DataTable({
                "responsive": true,
                "processing": true,
                "columnDefs": [
                    {
                        "targets": [3],
                        "visible": false,
                        "searchable": false
            },
                    {
                        "targets": [4],
                        "visible": false,
                        "searchable": false
            },
                     {
                        "targets": [6],
                        "visible": false,
                        "searchable": false
            },
                    {
                        responsivePriority: 1,
                        targets: 2
                    },
                    {
                        responsivePriority: 2,
                        targets: -1
                    }
        ]

            });
        });
        $('a[data-toggle="pill"]').on('click', function () {
            $('html,body').animate({
                scrollTop: $('#dmmtable').offset().top
            }, 500);
        });
    });
}

//FUTURE: Autofill?<|endoftext|>


<commit_before>function appMain() {

  $('#welcomeScreen').click(function() {
  $('#menu').hide();
  $('#welcomeScreen').slideUp('slow', function(){
  $('#welcomeScreen').hide();
});
$('#mainView').show();
console.log("Welcome Screen swiped up")
}).children().find(".bss-prev, .bss-next").click(function(e) {
  return false;
});
console.log("ready!");

  $('#welcomeScreen').on("swipeup",function(){
    $('#menu').hide();
    $('#welcomeScreen').slideUp('slow', function(){
      $('#welcomeScreen').hide();
    });
    $('#mainView').show();
    console.log("Welcome Screen swiped up")
  });

//==========================================//
//==========================================//

  $('#btnMenu').click(function () {

    if ($('#menu').is(':visible')) {
      $('#menu').hide('slow');
      $('#optionRow').fadeOut('fast');
      $('#menuQuestion').fadeOut('fast');
    }
    else{
      $('#menu').show('slow');
      setTimeout(function(){
        $('#optionRow').fadeIn('slow');
        $('#menuQuestion').fadeIn('slow');
      },150);
      $('#btnMenu').hide();
    };
  });

//==========================================//
//addsSwipeDown function to menu
//==========================================//

  $('#menu').on("swipedown",function(){
    $('#menu').hide('slow');
    $('#optionRow').fadeOut('fast');
    $('#menuQuestion').fadeOut('fast');
    setTimeout(function(){
      $('#btnMenu').show('slow');
    },200);
  });
}

$(document).ready(appMain);
<commit_msg>Add timer to reload page when idle<commit_after>var idleTime = 0;

function appMain() {

  $('#welcomeScreen').click(function() {
  $('#menu').hide();
  $('#welcomeScreen').slideUp('slow', function(){
  $('#welcomeScreen').hide();
});
$('#mainView').show();
console.log("Welcome Screen swiped up")
}).children().find(".bss-prev, .bss-next").click(function(e) {
  return false;
});
console.log("ready!");

  $('#welcomeScreen').on("swipeup",function(){
    $('#menu').hide();
    $('#welcomeScreen').slideUp('slow', function(){
      $('#welcomeScreen').hide();
    });
    $('#mainView').show();
    console.log("Welcome Screen swiped up")
  });

//==========================================//
//==========================================//

  $('#btnMenu').click(function () {

    if ($('#menu').is(':visible')) {
      $('#menu').hide('slow');
      $('#optionRow').fadeOut('fast');
      $('#menuQuestion').fadeOut('fast');
    }
    else{
      $('#menu').show('slow');
      setTimeout(function(){
        $('#optionRow').fadeIn('slow');
        $('#menuQuestion').fadeIn('slow');
      },150);
      $('#btnMenu').hide();
    };
  });

//==========================================//
//addsSwipeDown function to menu
//==========================================//

  $('#menu').on("swipedown",function(){
    $('#menu').hide('slow');
    $('#optionRow').fadeOut('fast');
    $('#menuQuestion').fadeOut('fast');
    setTimeout(function(){
      $('#btnMenu').show('slow');
    },200);
  });
}

//=======================================//
//IdleTimer
//======================================//
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        idleTime = 0;
    });
    $(this).keypress(function (e) {
        idleTime = 0;
    });

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 2) { // 20 minutes
        window.location.reload();
    }
}

$(document).ready(appMain);
<|endoftext|>


<commit_before>var map;

function main() {

  var options = {
    center: [38.555, -85.771],
    zoom: 11,
    zoomControl: false,  // dont add the zoom overlay (it is added by default)
    loaderControl: false //dont show tiles loader
  };

  cartodb.createVis('map', 'http://cityresearch.cartodb.com/api/v2/viz/5c39067a-b3aa-11e4-a01f-0e9d821ea90d/viz.json', options)
        .done(function(vis, layers) {
      // there are two layers, base layer and points layer

      // add the tooltip show when hover on the point
      vis.addOverlay({
        type: 'tooltip',
        position: 'top|center',
        template: '
{{name_to_display}}
'
      });

    });

}

window.onload = main;
<commit_msg>Update app.js<commit_after>var map;

function main() {

  var options = {
    center: [38.055, -85.771],
    zoom: 11,
    zoomControl: false,  // dont add the zoom overlay (it is added by default)
    loaderControl: false //dont show tiles loader
  };

  cartodb.createVis('map', 'http://cityresearch.cartodb.com/api/v2/viz/5c39067a-b3aa-11e4-a01f-0e9d821ea90d/viz.json', options)
        .done(function(vis, layers) {
      // there are two layers, base layer and points layer

      // add the tooltip show when hover on the point
      vis.addOverlay({
        type: 'tooltip',
        position: 'top|center',
        template: '
{{name_to_display}}
'
      });

    });

}

window.onload = main;
<|endoftext|>