<commit_before>/**
 * ownCloud - ocsms
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Loic Blot <loic.blot@unix-experience.fr>
 * @copyright Loic Blot 2014-2015
 */

// Some global vars to improve performances
var selectedConversation = null;
var curPhoneNumber = null;
var curContactName = '';
var lastMsgDate = 0;
var unreadCountCurrentConv = 0;
var unreadCountAllConv = 0;
var unreadCountNotifStep = 12;
var lastUnreadCountAllConv = 0;
var originalTitle = document.title;

$.urlParam = function(name){
	var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results == null) {
		return null;
	}
	else {
		return results[1] || 0;
	}
};

var refreshConversation = function() {
	// if no conversation selected, then don't fetch page
	if (curPhoneNumber == null) {
		if ($('#app-content-header').is(':visible')) {
			$('#app-content-header').hide();
		}
		return;
	}
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{
			'phoneNumber': curPhoneNumber,
			"lastDate": lastMsgDate
		},
		function(jsondata, status) {
			var fmt = formatConversation(jsondata);
			conversationBuf = fmt[1];
			if (conversationBuf != '') {
				$('.msg-endtag').before(conversationBuf);
				$('#app-content').scrollTop(1E10);
				// This will blink the tab because there is new messages
				if (document.hasFocus() == false) {
					unreadCountCurrentConv += fmt[0];
					document.title = originalTitle + " (" + unreadCountCurrentConv + ")";
					desktopNotify(unreadCountCurrentConv + " unread message(s) in conversation with " + curContactName);
				}
			}

			setMessageCountInfo(jsondata);

			if ($('#app-content-header').is(':hidden')) {
				$('#app-content-header').show();
			}
		}
	);
};

var checkNewMessages = function() {
	unreadCountAllConv = 0;
	$.getJSON(OC.generateUrl('/apps/ocsms/get/new_messages'),
		{ 'lastDate': lastMsgDate },
		function(jsondata, status) {
			var peerListBuf = '';
			var bufferedContacts = [];

			$.each(jsondata['phonelist'], function(id, val) {
				var fn, peerLabel, idxVal;
				idxVal = id.replace(/\//g,' ');
				idxVal2 = idxVal.replace('/ /g','');
				if (typeof jsondata['contacts'][id] == 'undefined') {
					fn = '';
					peerLabel = idxVal;
				}
				else {
					fn = jsondata['contacts'][id];
					peerLabel = fn;
				}

				if ($.inArray(peerLabel, bufferedContacts) == -1) {
					$("div[mailbox-avatar='" + peerLabel + "']").remove();
					$("a[mailbox-label='" + peerLabel + "']").remove();
					peerListBuf = '

' + peerLabel + ' (' + val + ')
';
					$('#app-mailbox-peers ul').prepend(peerListBuf);
					bufferedContacts.push(peerLabel);

					// Re-set conversation because we reload the element
					if (idxVal == curPhoneNumber) {
						changeSelectedConversation($("a[mailbox-navigation='" + idxVal + "']"));
					}

					unreadCountAllConv += parseInt(val);

					// Now bind the events when we click on the phone number
					$("a[mailbox-navigation='" + idxVal + "']").on('click', function (event) {
						var phoneNumber = $(this).attr('mailbox-navigation');
						OC.Util.History.pushState('phonenumber=' + phoneNumber);

						// phoneNumber must exist
						if (phoneNumber != null) {
							fetchConversation(phoneNumber);
								unreadCountAllConv += val;changeSelectedConversation($(this));
						}
						event.preventDefault();
					});
				}
			});

			/*
			* Decrement notification step counter, but stop it a zero
			* Stop at zero permit to notify instanly the user when
			* there is new messages in all conversations
			*/

			if (unreadCountNotifStep > 0) {
				unreadCountNotifStep--;
			}

			if (unreadCountAllConv > 0) {
				/*
				* We notify user every two minutes for all messages
				* or if unreadCount changes
				*/
				if (unreadCountNotifStep == 0 || lastUnreadCountAllConv != unreadCountAllConv) {
					desktopNotify(unreadCountAllConv + " unread message(s) for all conversations");
					unreadCountNotifStep = 12;
					lastUnreadCountAllConv = unreadCountAllConv;
				}
			}
		}
	);
};

function setMessageCountInfo(jsondata) {
	if (typeof jsondata['msgCount'] != 'undefined') {
		if (jsondata['msgCount'] == 1) {
			$('#ocsms-phone-msg-nb').html(jsondata['msgCount'] + ' message');
		}
		else {
			$('#ocsms-phone-msg-nb').html(jsondata['msgCount'] + ' messages');
		}
	}
	else {
		$('#ocsms-phone-msg-nb').html('');
	}
}

function fetchConversation(phoneNumber) {
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{
			'phoneNumber': phoneNumber
		},
		function(jsondata, status) {
			var phoneNumberLabel = phoneNumber;

			if (typeof jsondata['phoneNumbers'] != 'undefined') {
				var len = jsondata["phoneNumbers"].length;
				var ctLen = 0;
				phoneNumberLabel = '';

				$.each(jsondata["phoneNumbers"], function(id, val) {
					phoneNumberLabel += val;
					ctLen++;
					if (ctLen != len) {
						phoneNumberLabel += ",";
					}
					phoneNumberLabel += " ";
				});
			}

			conversationBuf = formatConversation(jsondata)[1];
			conversationBuf += '

';
			if (typeof jsondata['contactName'] == 'undefined' || jsondata['contactName'] == '') {
				$('#ocsms-phone-label').html(phoneNumberLabel);
				curContactName = phoneNumberLabel;
				$('#ocsms-phone-opt-number').html('');
			}
			else {
				$('#ocsms-phone-label').html(jsondata['contactName']);
				curContactName = jsondata['contactName'];
				$('#ocsms-phone-opt-number').html(phoneNumberLabel);
			}

			setMessageCountInfo(jsondata);

			if ($('#app-content-header').is(':hidden')) {
				$('#app-content-header').show();
			}

			$('#app-content-wrapper').html(conversationBuf);
			$('#app-content').scrollTop(1E10);

			curPhoneNumber = phoneNumber;
		}
	);
}

// Return (int) msgCount, (str) htmlConversation
function formatConversation(jsondata) {
	// Improve jQuery performance
	var buf = "";
	// Improve JS performance
	var msgClass = '';

	var msgCount = 0;
	var formatedDate = '';
	var formatedHour = '00';
	var formatedMin = '00';
	var months = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.',
		'Oct.', 'Nov.', 'Dec.'];

	$.each(jsondata["conversation"], function(id, vals) {
		if (vals["type"] == 1) {
			msgClass = "msg-recv";
		}
		else if (vals["type"] == 2) {
			msgClass = "msg-sent";
		}
		else {
			msgClass = '';
		}

		// Store the greater msg date for refresher
		// Note: we divide by 100 because number compare too large integers
		if ((id/100) > (lastMsgDate/100)) {
			lastMsgDate = id;
		}

		// Multiplicate ID to permit date to use it properly
		msgDate = new Date(id*1);

		formatedHour = msgDate.getHours();
		if (formatedHour < 10) {
			formatedHour = '0' + formatedHour;
		}

		formatedMin = msgDate.getMinutes();
		if (formatedMin < 10) {
			formatedMin = '0' + formatedMin;
		}
		formatedDate = msgDate.getDate() + " " + months[msgDate.getMonth()] + " " +
			formatedHour + ":" + formatedMin;

		buf += '

' +
			vals["msg"] + '

' +
			formatedDate + '

';
		msgCount++;

	});

	return [msgCount,buf];
}

function changeSelectedConversation(item) {
	if (selectedConversation != null) {
		selectedConversation.parent().removeClass('selected');
	}
	selectedConversation = item;
	selectedConversation.parent().addClass('selected');
	selectedConversation.css("font-weight", "normal");
	selectedConversation.html(selectedConversation.attr("mailbox-label"));
}

function fetchInitialPeerList(jsondata) {
	// Use a buffer for better jQuery performance
	var peerListBuf = "";

	var bufferedContacts = [];

	$.each(jsondata['phonelist'], function(id, val) {
		var fn, peerLabel, idxVal;
		idxVal = id.replace(/\//g,' ');
		idxVal2 = idxVal.replace('/ /g','');
		if (typeof jsondata['contacts'][id] == 'undefined') {
			fn = '';
			peerLabel = idxVal;
		}
		else {
			fn = jsondata['contacts'][id];
			peerLabel = fn;
		}
		if ($.inArray(peerLabel, bufferedContacts) == -1) {
			peerListBuf += '

' + peerLabel + '
';
			bufferedContacts.push(peerLabel);
		}
	});

	lastMsgDate = jsondata["lastRead"];

	// Only modify peerList if there is peers
	if (peerListBuf != '') {
		$('#app-mailbox-peers ul').html(peerListBuf);
	}
}

function initDesktopNotifies() {
	if (!("Notification" in window)) {
		return;
	}

	Notification.requestPermission(function (permission) {
		if(!('permission' in Notification)) {
			Notification.permission = permission;
		}
	});
}

function desktopNotify(msg) {
	if (!("Notification" in window)) {
		return;
	}
	else if (Notification.permission === "granted") {
		new Notification("ownCloud SMS - " + msg);
	}
	else if (Notification.permission !== 'denied') {
		Notification.requestPermission(function (permission) {
			if(!('permission' in Notification)) {
				Notification.permission = permission;
			}
			if (permission === "granted") {
				new Notification("ownCloud SMS - " + msg);
			}
		});
	}
}

(function ($, OC) {
	$(document).ready(function () {
		// Register real title
		originalTitle = document.title;

		// Now bind the events when we click on the phone number
		$.getJSON(OC.generateUrl('/apps/ocsms/get/peerlist'), function(jsondata, status) {
			fetchInitialPeerList(jsondata);

			// Now bind the events when we click on the phone number
			$('#app-mailbox-peers').find('a[mailbox-navigation]').on('click', function (event) {
				var phoneNumber = $(this).attr('mailbox-navigation');
				OC.Util.History.pushState('phonenumber=' + phoneNumber);

				// phoneNumber must exist
				if (phoneNumber != null) {
					fetchConversation(phoneNumber);
					changeSelectedConversation($(this));
				}
				event.preventDefault();
			});

			var pnParam = $.urlParam('phonenumber');
			if (pnParam != null) {
				var urlPhoneNumber = decodeURIComponent(pnParam);
				if (urlPhoneNumber != null) {
					fetchConversation(urlPhoneNumber);

					var pObject = $("a[mailbox-navigation='" + urlPhoneNumber + "']");
					if (pObject != null) {
						changeSelectedConversation(pObject);
					}
				}
			}
			// Don't show message headers if no conversation selected
			else {
				if ($('#app-content-header').is(':visible')) {
					$('#app-content-header').hide();
				}
			}

		});
		initDesktopNotifies();
		setInterval(refreshConversation, 10000);
		setInterval(checkNewMessages, 10000);
	});

	// reset count and title
	window.onfocus = function () {
		unreadCountCurrentConv = 0;
		document.title = originalTitle;
	};
})(jQuery, OC);
<commit_msg>Fix updating avatar menu element when new message is coming<commit_after>/**
 * ownCloud - ocsms
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Loic Blot <loic.blot@unix-experience.fr>
 * @copyright Loic Blot 2014-2015
 */

// Some global vars to improve performances
var selectedConversation = null;
var curPhoneNumber = null;
var curContactName = '';
var lastMsgDate = 0;
var unreadCountCurrentConv = 0;
var unreadCountAllConv = 0;
var unreadCountNotifStep = 12;
var lastUnreadCountAllConv = 0;
var originalTitle = document.title;

$.urlParam = function(name){
	var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results == null) {
		return null;
	}
	else {
		return results[1] || 0;
	}
};

var refreshConversation = function() {
	// if no conversation selected, then don't fetch page
	if (curPhoneNumber == null) {
		if ($('#app-content-header').is(':visible')) {
			$('#app-content-header').hide();
		}
		return;
	}
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{
			'phoneNumber': curPhoneNumber,
			"lastDate": lastMsgDate
		},
		function(jsondata, status) {
			var fmt = formatConversation(jsondata);
			conversationBuf = fmt[1];
			if (conversationBuf != '') {
				$('.msg-endtag').before(conversationBuf);
				$('#app-content').scrollTop(1E10);
				// This will blink the tab because there is new messages
				if (document.hasFocus() == false) {
					unreadCountCurrentConv += fmt[0];
					document.title = originalTitle + " (" + unreadCountCurrentConv + ")";
					desktopNotify(unreadCountCurrentConv + " unread message(s) in conversation with " + curContactName);
				}
			}

			setMessageCountInfo(jsondata);

			if ($('#app-content-header').is(':hidden')) {
				$('#app-content-header').show();
			}
		}
	);
};

var checkNewMessages = function() {
	unreadCountAllConv = 0;
	$.getJSON(OC.generateUrl('/apps/ocsms/get/new_messages'),
		{ 'lastDate': lastMsgDate },
		function(jsondata, status) {
			var peerListBuf = '';
			var bufferedContacts = [];

			$.each(jsondata['phonelist'], function(id, val) {
				var fn, peerLabel, idxVal;
				idxVal = id.replace(/\//g,' ');
				idxVal2 = idxVal.replace('/ /g','');
				if (typeof jsondata['contacts'][id] == 'undefined') {
					fn = '';
					peerLabel = idxVal;
				}
				else {
					fn = jsondata['contacts'][id];
					peerLabel = fn;
				}

				if ($.inArray(peerLabel, bufferedContacts) == -1) {
					$("li[peer-label='" + peerLabel + "']").remove();
					peerListBuf = '

' + peerLabel + ' (' + val + ')
';
					$('#app-mailbox-peers ul').prepend(peerListBuf);
					bufferedContacts.push(peerLabel);

					// Re-set conversation because we reload the element
					if (idxVal == curPhoneNumber) {
						changeSelectedConversation($("a[mailbox-navigation='" + idxVal + "']"));
					}

					unreadCountAllConv += parseInt(val);

					// Now bind the events when we click on the phone number
					$("a[mailbox-navigation='" + idxVal + "']").on('click', function (event) {
						var phoneNumber = $(this).attr('mailbox-navigation');
						OC.Util.History.pushState('phonenumber=' + phoneNumber);

						// phoneNumber must exist
						if (phoneNumber != null) {
							fetchConversation(phoneNumber);
								unreadCountAllConv += val;changeSelectedConversation($(this));
						}
						event.preventDefault();
					});
				}
			});

			/*
			* Decrement notification step counter, but stop it a zero
			* Stop at zero permit to notify instanly the user when
			* there is new messages in all conversations
			*/

			if (unreadCountNotifStep > 0) {
				unreadCountNotifStep--;
			}

			if (unreadCountAllConv > 0) {
				/*
				* We notify user every two minutes for all messages
				* or if unreadCount changes
				*/
				if (unreadCountNotifStep == 0 || lastUnreadCountAllConv != unreadCountAllConv) {
					desktopNotify(unreadCountAllConv + " unread message(s) for all conversations");
					unreadCountNotifStep = 12;
					lastUnreadCountAllConv = unreadCountAllConv;
				}
			}
		}
	);
};

function setMessageCountInfo(jsondata) {
	if (typeof jsondata['msgCount'] != 'undefined') {
		if (jsondata['msgCount'] == 1) {
			$('#ocsms-phone-msg-nb').html(jsondata['msgCount'] + ' message');
		}
		else {
			$('#ocsms-phone-msg-nb').html(jsondata['msgCount'] + ' messages');
		}
	}
	else {
		$('#ocsms-phone-msg-nb').html('');
	}
}

function fetchConversation(phoneNumber) {
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{
			'phoneNumber': phoneNumber
		},
		function(jsondata, status) {
			var phoneNumberLabel = phoneNumber;

			if (typeof jsondata['phoneNumbers'] != 'undefined') {
				var len = jsondata["phoneNumbers"].length;
				var ctLen = 0;
				phoneNumberLabel = '';

				$.each(jsondata["phoneNumbers"], function(id, val) {
					phoneNumberLabel += val;
					ctLen++;
					if (ctLen != len) {
						phoneNumberLabel += ",";
					}
					phoneNumberLabel += " ";
				});
			}

			conversationBuf = formatConversation(jsondata)[1];
			conversationBuf += '

';
			if (typeof jsondata['contactName'] == 'undefined' || jsondata['contactName'] == '') {
				$('#ocsms-phone-label').html(phoneNumberLabel);
				curContactName = phoneNumberLabel;
				$('#ocsms-phone-opt-number').html('');
			}
			else {
				$('#ocsms-phone-label').html(jsondata['contactName']);
				curContactName = jsondata['contactName'];
				$('#ocsms-phone-opt-number').html(phoneNumberLabel);
			}

			setMessageCountInfo(jsondata);

			if ($('#app-content-header').is(':hidden')) {
				$('#app-content-header').show();
			}

			$('#app-content-wrapper').html(conversationBuf);
			$('#app-content').scrollTop(1E10);

			curPhoneNumber = phoneNumber;
		}
	);
}

// Return (int) msgCount, (str) htmlConversation
function formatConversation(jsondata) {
	// Improve jQuery performance
	var buf = "";
	// Improve JS performance
	var msgClass = '';

	var msgCount = 0;
	var formatedDate = '';
	var formatedHour = '00';
	var formatedMin = '00';
	var months = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.',
		'Oct.', 'Nov.', 'Dec.'];

	$.each(jsondata["conversation"], function(id, vals) {
		if (vals["type"] == 1) {
			msgClass = "msg-recv";
		}
		else if (vals["type"] == 2) {
			msgClass = "msg-sent";
		}
		else {
			msgClass = '';
		}

		// Store the greater msg date for refresher
		// Note: we divide by 100 because number compare too large integers
		if ((id/100) > (lastMsgDate/100)) {
			lastMsgDate = id;
		}

		// Multiplicate ID to permit date to use it properly
		msgDate = new Date(id*1);

		formatedHour = msgDate.getHours();
		if (formatedHour < 10) {
			formatedHour = '0' + formatedHour;
		}

		formatedMin = msgDate.getMinutes();
		if (formatedMin < 10) {
			formatedMin = '0' + formatedMin;
		}
		formatedDate = msgDate.getDate() + " " + months[msgDate.getMonth()] + " " +
			formatedHour + ":" + formatedMin;

		buf += '

' +
			vals["msg"] + '

' +
			formatedDate + '

';
		msgCount++;

	});

	return [msgCount,buf];
}

function changeSelectedConversation(item) {
	if (selectedConversation != null) {
		selectedConversation.parent().removeClass('selected');
	}
	selectedConversation = item;
	selectedConversation.parent().addClass('selected');
	selectedConversation.css("font-weight", "normal");
	selectedConversation.html(selectedConversation.attr("mailbox-label"));
}

function fetchInitialPeerList(jsondata) {
	// Use a buffer for better jQuery performance
	var peerListBuf = "";

	var bufferedContacts = [];

	$.each(jsondata['phonelist'], function(id, val) {
		var fn, peerLabel, idxVal;
		idxVal = id.replace(/\//g,' ');
		idxVal2 = idxVal.replace('/ /g','');
		if (typeof jsondata['contacts'][id] == 'undefined') {
			fn = '';
			peerLabel = idxVal;
		}
		else {
			fn = jsondata['contacts'][id];
			peerLabel = fn;
		}
		if ($.inArray(peerLabel, bufferedContacts) == -1) {
			peerListBuf += '

' + peerLabel + '
';
			bufferedContacts.push(peerLabel);
		}
	});

	lastMsgDate = jsondata["lastRead"];

	// Only modify peerList if there is peers
	if (peerListBuf != '') {
		$('#app-mailbox-peers ul').html(peerListBuf);
	}
}

function initDesktopNotifies() {
	if (!("Notification" in window)) {
		return;
	}

	Notification.requestPermission(function (permission) {
		if(!('permission' in Notification)) {
			Notification.permission = permission;
		}
	});
}

function desktopNotify(msg) {
	if (!("Notification" in window)) {
		return;
	}
	else if (Notification.permission === "granted") {
		new Notification("ownCloud SMS - " + msg);
	}
	else if (Notification.permission !== 'denied') {
		Notification.requestPermission(function (permission) {
			if(!('permission' in Notification)) {
				Notification.permission = permission;
			}
			if (permission === "granted") {
				new Notification("ownCloud SMS - " + msg);
			}
		});
	}
}

(function ($, OC) {
	$(document).ready(function () {
		// Register real title
		originalTitle = document.title;

		// Now bind the events when we click on the phone number
		$.getJSON(OC.generateUrl('/apps/ocsms/get/peerlist'), function(jsondata, status) {
			fetchInitialPeerList(jsondata);

			// Now bind the events when we click on the phone number
			$('#app-mailbox-peers').find('a[mailbox-navigation]').on('click', function (event) {
				var phoneNumber = $(this).attr('mailbox-navigation');
				OC.Util.History.pushState('phonenumber=' + phoneNumber);

				// phoneNumber must exist
				if (phoneNumber != null) {
					fetchConversation(phoneNumber);
					changeSelectedConversation($(this));
				}
				event.preventDefault();
			});

			var pnParam = $.urlParam('phonenumber');
			if (pnParam != null) {
				var urlPhoneNumber = decodeURIComponent(pnParam);
				if (urlPhoneNumber != null) {
					fetchConversation(urlPhoneNumber);

					var pObject = $("a[mailbox-navigation='" + urlPhoneNumber + "']");
					if (pObject != null) {
						changeSelectedConversation(pObject);
					}
				}
			}
			// Don't show message headers if no conversation selected
			else {
				if ($('#app-content-header').is(':visible')) {
					$('#app-content-header').hide();
				}
			}

		});
		initDesktopNotifies();
		setInterval(refreshConversation, 10000);
		setInterval(checkNewMessages, 10000);
	});

	// reset count and title
	window.onfocus = function () {
		unreadCountCurrentConv = 0;
		document.title = originalTitle;
	};
})(jQuery, OC);
<|endoftext|>


<commit_before>
function recebe() {
  var img = JSON.parse(sessionStorage.getItem('img'));
  $("#lbl_triagem").html(JSON.parse(sessionStorage.getItem('nome-modulo')));
  $('.tit-image').css( {
    "background": "url("+img+") no-repeat",
    "background-size": "140px",
    "background-position": "15% -1%"
  });
}

/*Funçao que atualiza a hora*/
setInterval(function() {
  var hora = new Date();
  document.getElementById('hora').innerHTML = hora.toLocaleTimeString();

  if (screen.width > 650) {
    if ($("#lateral").css("margin-left") == "-390px") {
      $("#lateral").css("margin-left", "0px");
    }

    if ($("#config").css("visibility") == "hidden") {
      $("#config").css("visibility", "visible");
    }

    $('.tit-image').css( {
      "background-size": "140px",
    });
  } else {
    $('.tit-image').css( {
      "background-size": "70px",
    });
  }

  if (screen.width <= 711 && screen.width > 650 ) {
    $(".config").css("width", "44%");
  }
}, 100);

/* Função que mostra o menú lateral */
var ok = false;
function mostrarMenu() {

  var nav = document.getElementById('lateral');
  nav.style.transition = "1s margin-left";

  if (!ok) {
    nav.style.marginLeft = "0px";
    ok = true;
  } else {
    nav.style.marginLeft = "-390px";
    ok = false;
  }
}

/*Funçao que mostra os submodulos*/
var okMostrar = false;
function mostrar(){
  var submodulo = document.getElementById('submodulo_1');

  if (!okMostrar){
    submodulo.style.position   = "relative";
    submodulo.style.visibility = "visible";
    okMostrar = true;
  } else {
    submodulo.style.position   = "absolute";
    submodulo.style.visibility = "hidden";
    okMostrar = false;
  }
}

/*Funçao que mostra os as opções de salvar editar e imprimir*/
var okConfig = false;
function mostrarConfig(){
  var config = document.getElementById('config');

  if (!okConfig) {
    config.style.visibility = "visible";
    okConfig = true;
  } else {
    config.style.visibility = "hidden";
    okConfig = false;
  }
}

/*Função que mostra os conteudos das abas*/
function mostrarAbas(nomeAba, url, num) {
  if (!$("#abas"+num ).is( ":visible")) {
    $('#abas').append("

"+nomeAba+"

");
    $('#content').append("

");
    $('#conteudo'+num).append("");
    window.open (url, 'frame'+num);
    abas(num);
    if (screen.width <= 650) {
      $("#lateral").css("margin-left", "-390px");
    }
  }
}

/*Função que implementa as abas*/
function abas(num) {
  $("#content div:nth-child(1)").show();
  $(".abas li:first div").addClass("selecionada");

  /*Coloca o icone de fechar nas abas*/
  $('#abas'+num).append("");

  /*Adiciona o hover nos nomes das abas*/
  $(".aba").hover(
    function(){$(this).addClass("ativa");},
    function(){$(this).removeClass("ativa");}
  );

  /*permite a seleção das abas*/
  $(".aba").click(function() {
    $(".aba").removeClass("selecionada");
    $(this).addClass("selecionada");
    var indice = $(this).parent().index();
    indice++;
    $("#content div").hide();
    $("#content div:nth-child("+indice+")").show();
  });

  /*Fecha a aba*/
  $(".aba > img").click(function() {
    var aba = $(this).parent().parent();
    var indice = aba.index() + 1;
    aba.remove();
    $("#content div:nth-child("+indice.toString()+")").remove();
    // $(".aba").removeClass("selecionada");
    // $("#content div").hide();
    if(indice > 1) {
        var id = indice - 1;
        $("#content div:nth-child("+id.toString()+")").show();
        $(".abas li:nth-child("+id+") .aba").addClass("selecionada");
    }else{
        $("#content div:nth-child("+indice.toString()+")").show();
        $(".abas li:nth-child("+indice+") .aba").addClass("selecionada");
    }
  });
}

function enviar(val) {
  var img;
  var name;
  switch(val) {
    case 1:
        img  = $("#img-triagem").attr('src');
        name = $("#name-tri").html();
        break;
    case 2:
        img = $("#img-recepcao").attr('src');
        name = $("#name-recep").html();
        break;
    case 3:
        img = $("#img-admin").attr('src');
        name = $("#name-admin").html();
        break;
    default:
        img = $("#img-portaria").attr('src');
        name = $("#name-portaria").html();
  }

  var image = JSON.stringify(img);
  var txt   = JSON.stringify(name);
  sessionStorage.setItem('img', image );
  sessionStorage.setItem('nome-modulo', txt );
}
<commit_msg>FrontEnd: Ajustado o tamanho do iframe.<commit_after>
function recebe() {
  var img = JSON.parse(sessionStorage.getItem('img'));
  $("#lbl_triagem").html(JSON.parse(sessionStorage.getItem('nome-modulo')));
  $('.tit-image').css( {
    "background": "url("+img+") no-repeat",
    "background-size": "140px",
    "background-position": "15% -1%"
  });
}

/*Funçao que atualiza a hora*/
setInterval(function() {
  var hora = new Date();
  document.getElementById('hora').innerHTML = hora.toLocaleTimeString();

  if (screen.width > 650) {
    if ($("#lateral").css("margin-left") == "-390px") {
      $("#lateral").css("margin-left", "0px");
    }

    if ($("#config").css("visibility") == "hidden") {
      $("#config").css("visibility", "visible");
    }

    $('.tit-image').css( {
      "background-size": "140px",
    });
  } else {
    $('.tit-image').css( {
      "background-size": "70px",
    });
  }

  if (screen.width <= 711 && screen.width > 650 ) {
    $(".config").css("width", "44%");
  }
}, 100);

/* Função que mostra o menú lateral */
var ok = false;
function mostrarMenu() {

  var nav = document.getElementById('lateral');
  nav.style.transition = "1s margin-left";

  if (!ok) {
    nav.style.marginLeft = "0px";
    ok = true;
  } else {
    nav.style.marginLeft = "-390px";
    ok = false;
  }
}

/*Funçao que mostra os submodulos*/
var okMostrar = false;
function mostrar(){
  var submodulo = document.getElementById('submodulo_1');

  if (!okMostrar){
    submodulo.style.position   = "relative";
    submodulo.style.visibility = "visible";
    okMostrar = true;
  } else {
    submodulo.style.position   = "absolute";
    submodulo.style.visibility = "hidden";
    okMostrar = false;
  }
}

/*Funçao que mostra os as opções de salvar editar e imprimir*/
var okConfig = false;
function mostrarConfig(){
  var config = document.getElementById('config');

  if (!okConfig) {
    config.style.visibility = "visible";
    okConfig = true;
  } else {
    config.style.visibility = "hidden";
    okConfig = false;
  }
}

/*Função que mostra os conteudos das abas*/
function mostrarAbas(nomeAba, url, num) {
  if (!$("#abas"+num ).is( ":visible")) {
    $('#abas').append("

"+nomeAba+"

");
    $('#content').append("

");
    $('#conteudo'+num).append("");
    window.open (url, 'frame'+num);
    abas(num);
    if (screen.width <= 650) {
      $("#lateral").css("margin-left", "-390px");
    }
  }
}

/*Função que implementa as abas*/
function abas(num) {
  $("#content div:nth-child(1)").show();
  $(".abas li:first div").addClass("selecionada");

  /*Coloca o icone de fechar nas abas*/
  $('#abas'+num).append("");

  /*Adiciona o hover nos nomes das abas*/
  $(".aba").hover(
    function(){$(this).addClass("ativa");},
    function(){$(this).removeClass("ativa");}
  );

  /*permite a seleção das abas*/
  $(".aba").click(function() {
    $(".aba").removeClass("selecionada");
    $(this).addClass("selecionada");
    var indice = $(this).parent().index();
    indice++;
    $("#content div").hide();
    $("#content div:nth-child("+indice+")").show();
  });

  /*Fecha a aba*/
  $(".aba > img").click(function() {
    var aba = $(this).parent().parent();
    var indice = aba.index() + 1;
    aba.remove();
    $("#content div:nth-child("+indice.toString()+")").remove();
    // $(".aba").removeClass("selecionada");
    // $("#content div").hide();
    if(indice > 1) {
        var id = indice - 1;
        $("#content div:nth-child("+id.toString()+")").show();
        $(".abas li:nth-child("+id+") .aba").addClass("selecionada");
    }else{
        $("#content div:nth-child("+indice.toString()+")").show();
        $(".abas li:nth-child("+indice+") .aba").addClass("selecionada");
    }
  });
}

function enviar(val) {
  var img;
  var name;
  switch(val) {
    case 1:
        img  = $("#img-triagem").attr('src');
        name = $("#name-tri").html();
        break;
    case 2:
        img = $("#img-recepcao").attr('src');
        name = $("#name-recep").html();
        break;
    case 3:
        img = $("#img-admin").attr('src');
        name = $("#name-admin").html();
        break;
    default:
        img = $("#img-portaria").attr('src');
        name = $("#name-portaria").html();
  }

  var image = JSON.stringify(img);
  var txt   = JSON.stringify(name);
  sessionStorage.setItem('img', image );
  sessionStorage.setItem('nome-modulo', txt );
}
<|endoftext|>


<commit_before>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var width = 1280;
        var height = 720;
        var levelSize = 45;
        var leftright = "none";
        var updown = "none";
        var levelCount = 3;
        var lookupDir = {
            u: [1,2,3],
            ur: [3,4,5,6],
            r: [6,7,8],
            dr: [8,9,10,11],
            d: [11,12,13],
            dl: [13,14,15,16],
            l: [16,17,18],
            ul: [18,19,0,1]
        };
        var lookupOff = {
            0: [-2,-3],
            1: [-1,-3],
            2: [0,-3],
            3: [1,-3],
            4: [2,-3],
            5: [3,-2],
            6: [3,-1],
            7: [3,0],
            8: [3,1],
            9: [3,2],
            10: [2,3],
            11: [1,3],
            12: [0,3],
            13: [-1,3],
            14: [-2,3],
            15: [-3,2],
            16: [-3,1],
            17: [-3,0],
            18: [-3,-1],
            19: [-3,-2]
        };

        document.getElementById("paintbtn").onclick = paint;

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();

        }

        function createNext(updown, leftright, prevX, prevY){
            var rand4 = Math.floor((Math.random() * 4) );
            var rand3 = Math.floor((Math.random() * 3) );
            var dir = -1;
            var multiX = -1;
            var multiY = -1;
            switch(updown){
                case "up":
                    switch(leftright){
                        case "left":
                            dir = lookupDir.ul[rand4];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("18, 19, 0, 1");
                            break;
                        case "right":
                            dir = lookupDir.ur[rand4];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("3, 4, 5, 6");
                            break;
                        default:
                            dir = lookupDir.u[rand3];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                        //alert("1, 2 ,3");
                    }
                    break;
                case "down":
                    switch(leftright){
                        case "left":
                            dir = lookupDir.dl[rand4];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("13, 14, 15, 16");
                            break;
                        case "right":
                            dir = lookupDir.dr[rand4];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("8, 9, 10, 11");
                            break;
                        default:
                        dir = lookupDir.d[rand3];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                        //alert("11, 12, 13");
                    }
                    break;
                default:
                    switch(leftright){
                        case "left":
                            dir = lookupDir.l[rand3];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("16, 17, 18");
                            break;
                        case "right":
                            dir = lookupDir.r[rand3];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("6, 7, 8");
                            break;
                        default:
                        //alert("none");
                    }
            }
            var newX = prevX + multiX*(levelSize/3);
            var newY = prevY + multiY*(levelSize/3);
            return [newX, newY];
        }

        function drawLevel(x, y){
            c.rect(x,y,levelSize,levelSize);
            for(var i = 0; i< 3; i++){
                for(var j = 0; j< 3; j++){
                    c.rect((x) + i*(levelSize/3), (y) + j*(levelSize/3), (levelSize/3), (levelSize/3));
                    c.stroke();
                }
            }
        }

        //paint the map
        function paint() {
            reset();

            var lvlselect = document.getElementById("levelcount");
            var dir1 = document.getElementsByName("leftright");
            var dir2 = document.getElementsByName("updown");

            for(var i = 0, length = dir1.length; i < length; i++){
                if (dir1[i].checked) {
                    // do whatever you want with the checked radio
                    leftright = dir1[i].value;
                    // only one radio can be logically checked, don't check the rest
                    break;
                }
            }

            for(var i = 0, length = dir2.length; i < length; i++){
                if (dir2[i].checked) {
                    // do whatever you want with the checked radio
                    updown = dir2[i].value;
                    // only one radio can be logically checked, don't check the rest
                    break;
                }
            }

            levelCount = lvlselect.options[lvlselect.selectedIndex].value;

            alert(updown+","+ leftright+","+ levelCount);

            var current = 0;
            var prevX = width/2;
            var prevY = height/2;
            drawLevel(prevX, prevY);
            current++;
            while(current < levelCount){
                var newCords = createNext(updown, leftright, prevX, prevY);
                var newX = newCords[0];
                var newY = newCords[1];
                drawLevel(newX, newY);
                prevX = newX;
                prevY = newY;
                current++;
            }
        }
    }
})(window, document, undefined);
<commit_msg>Update script.js<commit_after>(function(window, document, undefined) {
    window.onload = init;
    function init() {
        //get the canvas
        var canvas = document.getElementById("mapcanvas");
        var c = canvas.getContext("2d");
        var width = 1280;
        var height = 720;
        var levelSize = 45;
        var leftright = "none";
        var updown = "none";
        var levelCount = 3;
        var lookupDir = {
            u: [1,2,3],
            ur: [3,4,5,6],
            r: [6,7,8],
            dr: [8,9,10,11],
            d: [11,12,13],
            dl: [13,14,15,16],
            l: [16,17,18],
            ul: [18,19,0,1]
        };
        var lookupOff = {
            0: [-2,-3],
            1: [-1,-3],
            2: [0,-3],
            3: [1,-3],
            4: [2,-3],
            5: [3,-2],
            6: [3,-1],
            7: [3,0],
            8: [3,1],
            9: [3,2],
            10: [2,3],
            11: [1,3],
            12: [0,3],
            13: [-1,3],
            14: [-2,3],
            15: [-3,2],
            16: [-3,1],
            17: [-3,0],
            18: [-3,-1],
            19: [-3,-2]
        };

        document.getElementById("paintbtn").onclick = paint;

        function reset(){
            c.clearRect ( 0 , 0 , canvas.width, canvas.height );
            c.beginPath();

        }

        function createNext(updown, leftright, prevX, prevY){
            var rand4 = Math.floor((Math.random() * 4) );
            var rand3 = Math.floor((Math.random() * 3) );
            var dir = -1;
            var multiX = -1;
            var multiY = -1;
            switch(updown){
                case "up":
                    switch(leftright){
                        case "left":
                            dir = lookupDir.ul[rand4];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("18, 19, 0, 1");
                            break;
                        case "right":
                            dir = lookupDir.ur[rand4];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("3, 4, 5, 6");
                            break;
                        default:
                            dir = lookupDir.u[rand3];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                        //alert("1, 2 ,3");
                    }
                    break;
                case "down":
                    switch(leftright){
                        case "left":
                            dir = lookupDir.dl[rand4];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("13, 14, 15, 16");
                            break;
                        case "right":
                            dir = lookupDir.dr[rand4];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("8, 9, 10, 11");
                            break;
                        default:
                        dir = lookupDir.d[rand3];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                        //alert("11, 12, 13");
                    }
                    break;
                default:
                    switch(leftright){
                        case "left":
                            dir = lookupDir.l[rand3];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("16, 17, 18");
                            break;
                        case "right":
                            dir = lookupDir.r[rand3];
                            multiX = lookupOff[dir][0];
                            multiY = lookupOff[dir][1];
                            //alert("6, 7, 8");
                            break;
                        default:
                        //alert("none");
                    }
            }
            var newX = prevX + multiX*(levelSize/3);
            var newY = prevY + multiY*(levelSize/3);
            return [newX, newY];
        }

        function drawLevel(x, y){
            c.rect(x,y,levelSize,levelSize);
            for(var i = 0; i< 3; i++){
                for(var j = 0; j< 3; j++){
                    c.rect((x) + i*(levelSize/3), (y) + j*(levelSize/3), (levelSize/3), (levelSize/3));
                    c.stroke();
                }
            }
        }

        //paint the map
        function paint() {
            reset();

            var lvlselect = document.getElementById("levelcount");
            var dir1 = document.getElementsByName("leftright");
            var dir2 = document.getElementsByName("updown");

            for(var i = 0, length = dir1.length; i < length; i++){
                if (dir1[i].checked) {
                    // do whatever you want with the checked radio
                    leftright = dir1[i].value;
                    // only one radio can be logically checked, don't check the rest
                    break;
                }
            }

            for(var i = 0, length = dir2.length; i < length; i++){
                if (dir2[i].checked) {
                    // do whatever you want with the checked radio
                    updown = dir2[i].value;
                    // only one radio can be logically checked, don't check the rest
                    break;
                }
            }

            levelCount = lvlselect.options[lvlselect.selectedIndex].value;

            //alert(updown+","+ leftright+","+ levelCount);

            var current = 0;
            var prevX = width/2;
            var prevY = height/2;
            drawLevel(prevX, prevY);
            current++;
            while(current < levelCount){
                var newCords = createNext(updown, leftright, prevX, prevY);
                var newX = newCords[0];
                var newY = newCords[1];
                drawLevel(newX, newY);
                prevX = newX;
                prevY = newY;
                current++;
            }
        }
    }
})(window, document, undefined);
<|endoftext|>


<commit_before>/* globals dom file KellyColorPicker palettes */

// Initialize
const canvas = document.querySelector('#canvas');
canvas.setAttribute('width', document.body.clientWidth + 'px');
canvas.setAttribute('height', document.body.clientHeight + 'px');
const colorpaletteselect = document.querySelector('.colorpalette');
palettes.forEach((p,i) => {
  let opt = document.createElement('option');
  opt.setAttribute('value', i);
  opt.innerText = p.name;
  colorpaletteselect.append(opt);
});
colorpaletteselect.addEventListener('change', setPalette);
// Color picker
const colorpicker = new KellyColorPicker(
  {
    place : document.querySelector('.popup-colour'),
    input : '.js-colour',
    size : 200,
    color : '#ffffff',
    method : 'square',
    input_color : false, // or inputColor (sice v1.15)
    input_format : 'mixed', // or inputFormat (since v1.15)
    alpha : 1,
    alpha_slider : false, // or alphaSlider (since v1.15)
    colorSaver : false,
    resizeWith : true, // auto redraw canvas on resize window
    popupClass: 'popup-colour',
    userEvents : {
      // change : function(self) {
      //   // set background color for 'input' to current color of color picker
      //   if(self.getCurColorHsv().v < 0.5){
      //   self.getInput().style.color = "#FFF";
      // } else {
      //   self.getInput().style.color = "#000";
      // }
      // self.getInput().style.background = self.getCurColorHex();
    // }
  }
  });
setPalette({target: colorpaletteselect});

const mouse = {};

function setPalette(evt){
  let palette = palettes[parseInt(evt.target.value)];
  let wells = document.querySelectorAll('.js-miniwell');
  for (let i = 0; i < 5; i++){
    colorButton(wells[i], '#' + palette.colors[i]);
  }
}

class Pen{
  constructor(){
    this.drawing = false;
  }
  start(evt){
    if (!evt.button){
      // button 0 is the main button, we're not interested in others
      return;
    }
    let {x,y} = getXY(evt);
    startPath(x,y);
    this.drawing = true;
  }

  move(evt){
    if (!this.drawing) return;
    let {x,y} = getXY(evt);
    if (inBounds(x,y)){
        appendToPath(x,y);
    }
  }

  stop(evt){
    if (!this.drawing) return;
    let {x,y} = getXY(evt);
    // FIXME: draw a dot if we haven't moved
    if (currentPath){
      dom.simplifyPath(currentPath);
      currentPath = null;
    }
    this.drawing = false;
  }

}

class Pan{
  constructor(){

  }
  starte(evt){

  }
  move(evt){

  }
  stop(evt){

  }

}

class Rotate{

}

class ZoomIn{

}

class ZoomOut{

}

let tools = {
  pen: new Pen(canvas),
  pan: new Pan(canvas),
  rotate: new Rotate(canvas),
  zoomin: new ZoomIn(canvas),
  zoomout: new ZoomOut(canvas)
}

let currentTool = tools.pen;
let currentStrokeWidth = 1;
let currentDoOnionskin = true;

function selectTool(button){
  let name = button.getAttribute('title').toLowerCase();
  document.querySelector('.js-tool.active').classList.remove('active');
  button.classList.add('active');
  switch(name){
    case 'pen': currentTool = tools.pen; break;
    case 'pan': currentTool = tools.pan; break;
    case 'rotate': currentTool = tools.rotate; break;
    case 'zoom in':  currentTool = tools.zoomin; break;
    case 'zoom out': currentTool = tools.zoomout; break;
    default: console.error('unrecognized tool name: %s', name);
  }
}

let currentColor = '#000000';
let currentFrameDelay = 30; // milliseconds

function setFrameRate(input){
  currentFrameDelay = Math.floor(1000 / Number(input.value));
}

function colorPopup(input){
  let popup = document.querySelector('.popup-colour');
  let colorwell = document.querySelector('.colourwell');
  if (popup.style.display === 'none'){
    colorpicker.setColor(input.value);
    popup.style.display = 'block';
  }else{
    let color = colorpicker.getCurColorHex();
    colorButton(colorwell, color);
    colorButton(input, color);
    currentColor = color;
    popup.style.display = 'none';
  }
}

function colorButton(button, color){
  button.value = color;
  button.style.backgroundColor = color;
  if (hexToValue(color) < 0.5){
    button.style.color = '#FFF';
  }else{
    button.style.color = '#000';
  }
}

function hexToValue(hex){
  return colorpicker.rgbToHsv(colorpicker.hexToRgb(hex)).v;
}

function selectColor(input){
  let popup = document.querySelector('.popup-colour');
  let colorwell = document.querySelector('.colourwell');
  if (popup.style.display === 'block'){
    let color = colorpicker.getCurColorHex();
    colorButton(colorwell, color);
    colorButton(input, color);
    currentColor = color;
    popup.style.display = 'none';
  }else{
    colorButton(colorwell, input.value);
    currentColor = input.value;
  }
}

var drawing = false;
var WIDTH = document.body.clientWidth;
var HEIGHT = document.body.clientHeight;

// Prevent control clicks from passing through to svg
function swallowClicks(evt){
  evt.stopPropagation();
}
document.querySelector('.buttonbar.animation').addEventListener('mousedown', swallowClicks);
document.querySelector('.buttonbar.tools').addEventListener('mousedown', swallowClicks);
document.querySelector('.buttonbar.animation').addEventListener('touchstart', swallowClicks);
document.querySelector('.buttonbar.tools').addEventListener('touchstart', swallowClicks);

function inBounds(x,y){
  return !(x < 0 || x > WIDTH || y < 0 || y > HEIGHT);
}

function getXY(evt){
   if (evt.cancelable) {
      evt.preventDefault();
    }

    const rect = this.canvas.getBoundingClientRect();
    const position = evt.changedTouches && evt.changedTouches[0] || evt;
    let x = position.offsetX;
    let y = position.offsetY;

    if (typeof x === 'undefined') {
      x = position.clientX - rect.left;
    }
    if (typeof y === 'undefined') {
      y = position.clientY - rect.top;
    }
    return {x,y};
}

const toolStart = evt => currentTool.start(evt);
const toolMove = evt => currentTool.move(evt);
const toolStop = evt => currentTool.stop(evt);
const toolCancel = evt => currentTool.cancel();
const escCancel = evt => {
  if (evt.code && evt.code === 'Escape'){
    currentTool.cancel();
  }
}

document.body.addEventListener('mousedown', toolStart);
document.body.addEventListener('touchstart', toolStart);
document.body.addEventListener('mousemove', toolMove);
document.body.addEventListener('touchmove', toolMove);
document.body.addEventListener('touchend', toolStop);
document.body.addEventListener('mouseup', toolStop);
document.body.addEventListener('touchcancel', toolCancel);
document.body.addEventListener('keydown', escCancel);

function currentFrame(){
  return document.querySelector('.frame.selected');
}

function playingFrame(){
  return document.querySelector('.frame.play-frame');
}

var currentPath = null;

function startPath(x,y){

  currentPath = currentFrame().appendChild(dom.svg('path', {
      d: 'M ' + x + ',' + y,
      stroke: currentColor,
      'stroke-width': currentStrokeWidth
  }));
  file.onChange();
}

function appendToPath(x,y){
  var path = document.querySelector('.selected path:last-child');
  var d = path.getAttribute('d');
  path.setAttribute('d', `${d} L${x} ${y}`);
}

/***************************************
*
*  MANAGE FRAMES
*
***************************************/

function isOnionskinOn(){
  return currentDoOnionskin;
}

function currentOnionskinFrame(){
  return document.querySelector('.frame.onionskin');
}

function updateOnionskin(){
  if (!isOnionskinOn()) return;
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  dom.addClass(currentFrame().previousElementSibling, 'onionskin');
}

function addFrame(){
  dom.insertAfter(dom.svg('g', {'class': 'frame selected'}), currentFrame());
  currentFrame().classList.remove('selected');
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function cloneFrame(){
  dom.insertAfter(currentFrame().cloneNode(true), currentFrame());
  currentFrame().classList.remove('selected');
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function deleteFrame(){
  var frameToDelete = currentFrame();
  if (frameToDelete.nextElementSibling){
      incrementFrame();
  }else if (frameToDelete.previousElementSibling){
      decrementFrame();
  }
  if (frameToDelete.parentNode.children.length > 1){
    dom.remove(frameToDelete);
  }else{
    dom.clear(frameToDelete); // don't delete the last frame, just its children
  }
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function clear(){
  dom.clear(currentFrame());
}

function toggleOnionskin(){
  if (isOnionskinOn()){
      dom.addClass(currentFrame().previousElementSibling, 'onionskin');
  }else{
      dom.removeClass(currentOnionskinFrame(), 'onionskin');
  }
}

function incrementFrame(){
  var curr = currentFrame();
  if (curr.nextElementSibling){
      curr.classList.remove('selected');
      curr.nextElementSibling.classList.add('selected');
  }
  updateOnionskin();
  updateFrameCount();
}

function decrementFrame(){
  var curr = currentFrame();
  if (curr.previousElementSibling){
      curr.classList.remove('selected');
      curr.previousElementSibling.classList.add('selected');
  }
  updateOnionskin();
  updateFrameCount();
}

function gotoFirstFrame(){
  currentFrame().classList.remove('selected');
  document.querySelector('.frame').classList.add('selected');
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  updateFrameCount();
}

function gotoLastFrame(){
  currentFrame().classList.remove('selected');
  document.querySelector('.frame:last-child').classList.add('selected');
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  dom.addClass(currentFrame().previousElementSibling, 'onionskin');
  updateFrameCount();
}

var _lastFrameTime = 0;
var _frameDelay = 0;

function play(){
  document.body.classList.add('playing');
  // turn play button into stop button
  // disable all other controls
  // temporarily turn off onionskin (remember state)
  // start at beginning of document (remember state)
  document.querySelector('.frame').classList.add('play-frame');
  // add SVG SMIL animation
  // Unless looping, call stop() when animation is finished
  // How much of this can I do by adding "playing" class to body?
  setTimeout(function(){
      _frameDelay = currentFrameDelay;
      _lastFrameTime = Date.now();
      requestAnimationFrame(playNextFrame);
  }, 500);
}

function stop(){
  // remove SMIL animation
  // re-enable all controls
  // return to the frame we were on
  // re-enable onionskin if needed
  // turn stop button into play button
  dom.removeClass(playingFrame(), 'play-frame');
  document.body.classList.remove('playing');
}

function playNextFrame(){
  var time = Date.now();
  if ((time - _lastFrameTime) < _frameDelay){
      requestAnimationFrame(playNextFrame);
      return;
  }
  var currFrame = playingFrame();
  _lastFrameTime = time;
  if (currFrame.nextElementSibling){
      currFrame.classList.remove('play-frame');
      currFrame.nextElementSibling.classList.add('play-frame');
      requestAnimationFrame(playNextFrame);
  }else{
      stop();
  }
}

function updateFrameCount(){
  try{
      var frames = currentFrame().parentElement.children.length;
      var index = dom.indexOf(currentFrame());
      document.querySelector('.framecount').textContent = 'Frame ' + (index+1) + ' of ' + frames;
  }catch(e){
      // wait for the file to load, probably
  }
}

function undoLine(){
  dom.remove(currentFrame().lastElementChild);
  file.onChange();
}

function keydownHandler(evt){
  if ((evt.key || evt.keyIdentifier) === 'Control'){
      document.body.classList.add('usefiles');
  }
}

function keyupHandler(evt){
  if ((evt.key || evt.keyIdentifier) === 'Control'){
      document.body.classList.remove('usefiles');
  }
}

window.app = {
  updateFrameCount: updateFrameCount,
  play: play
};

// document.querySelector('#canvas-undo').addEventListener('click', undoLine, false);
// document.querySelector('#canvas-onionskin').addEventListener('change', toggleOnionskin, false);
document.addEventListener('keydown', keydownHandler, false);
document.addEventListener('keyup', keyupHandler, false);

<commit_msg>🍳🦀 Checkpoint ./js/script.js:739936/771<commit_after>/* globals dom file KellyColorPicker palettes */

// Initialize
const canvas = document.querySelector('#canvas');
canvas.setAttribute('width', document.body.clientWidth + 'px');
canvas.setAttribute('height', document.body.clientHeight + 'px');
const colorpaletteselect = document.querySelector('.colorpalette');
palettes.forEach((p,i) => {
  let opt = document.createElement('option');
  opt.setAttribute('value', i);
  opt.innerText = p.name;
  colorpaletteselect.append(opt);
});
colorpaletteselect.addEventListener('change', setPalette);
// Color picker
const colorpicker = new KellyColorPicker(
  {
    place : document.querySelector('.popup-colour'),
    input : '.js-colour',
    size : 200,
    color : '#ffffff',
    method : 'square',
    input_color : false, // or inputColor (sice v1.15)
    input_format : 'mixed', // or inputFormat (since v1.15)
    alpha : 1,
    alpha_slider : false, // or alphaSlider (since v1.15)
    colorSaver : false,
    resizeWith : true, // auto redraw canvas on resize window
    popupClass: 'popup-colour',
    userEvents : {
      // change : function(self) {
      //   // set background color for 'input' to current color of color picker
      //   if(self.getCurColorHsv().v < 0.5){
      //   self.getInput().style.color = "#FFF";
      // } else {
      //   self.getInput().style.color = "#000";
      // }
      // self.getInput().style.background = self.getCurColorHex();
    // }
  }
  });
setPalette({target: colorpaletteselect});

const mouse = {};

function setPalette(evt){
  let palette = palettes[parseInt(evt.target.value)];
  let wells = document.querySelectorAll('.js-miniwell');
  for (let i = 0; i < 5; i++){
    colorButton(wells[i], '#' + palette.colors[i]);
  }
}

class Pen{
  constructor(){
    this.drawing = false;
  }
  start(evt){
    if (!evt.button){
      // button 0 is the main button, we're not interested in others
      return;
    }
    let {x,y} = getXY(evt);
    startPath(x,y);
    this.drawing = true;
  }

  move(evt){
    if (!this.drawing) return;
    let {x,y} = getXY(evt);
    if (inBounds(x,y)){
        appendToPath(x,y);
    }
  }

  stop(evt){
    if (!this.drawing) return;
    let {x,y} = getXY(evt);
    // FIXME: draw a dot if we haven't moved
    if (currentPath){
      dom.simplifyPath(currentPath);
      currentPath = null;
    }
    this.drawing = false;
  }

  cancel(){
    // remove the path in progress
  }

}

class Pan{
  constructor(){
    this.dragging = false;
  }

  start(evt){
    if (!evt.button){
      // button 0 is the main button, we're not interested in others
      return;
    }
    let {x,y} = getXY(evt);
    this.matrix = currentFrame().get
    startPath(x,y);
    this.drawing = true;
  }

  move(evt){

  }

  stop(evt){

  }

  cancel(){

  }

}

class Rotate{
  constructor(){

  }

  start(evt){

  }

  move(evt){

  }

  stop(evt){

  }

  cancel(evt){

  }
}

class ZoomIn{
  constructor(){

  }

  start(evt){

  }

  move(evt){

  }

  stop(evt){

  }

  cancel(evt){

  }
}

class ZoomOut{
  constructor(){

  }

  start(evt){

  }

  move(evt){

  }

  stop(evt){

  }

  cancel(evt){

  }
}

let tools = {
  pen: new Pen(canvas),
  pan: new Pan(canvas),
  rotate: new Rotate(canvas),
  zoomin: new ZoomIn(canvas),
  zoomout: new ZoomOut(canvas)
}

let currentTool = tools.pen;
let currentStrokeWidth = 1;
let currentDoOnionskin = true;

function selectTool(button){
  let name = button.getAttribute('title').toLowerCase();
  document.querySelector('.js-tool.active').classList.remove('active');
  button.classList.add('active');
  switch(name){
    case 'pen': currentTool = tools.pen; break;
    case 'pan': currentTool = tools.pan; break;
    case 'rotate': currentTool = tools.rotate; break;
    case 'zoom in':  currentTool = tools.zoomin; break;
    case 'zoom out': currentTool = tools.zoomout; break;
    default: console.error('unrecognized tool name: %s', name);
  }
}

let currentColor = '#000000';
let currentFrameDelay = 30; // milliseconds

function setFrameRate(input){
  currentFrameDelay = Math.floor(1000 / Number(input.value));
}

function colorPopup(input){
  let popup = document.querySelector('.popup-colour');
  let colorwell = document.querySelector('.colourwell');
  if (popup.style.display === 'none'){
    colorpicker.setColor(input.value);
    popup.style.display = 'block';
  }else{
    let color = colorpicker.getCurColorHex();
    colorButton(colorwell, color);
    colorButton(input, color);
    currentColor = color;
    popup.style.display = 'none';
  }
}

function colorButton(button, color){
  button.value = color;
  button.style.backgroundColor = color;
  if (hexToValue(color) < 0.5){
    button.style.color = '#FFF';
  }else{
    button.style.color = '#000';
  }
}

function hexToValue(hex){
  return colorpicker.rgbToHsv(colorpicker.hexToRgb(hex)).v;
}

function selectColor(input){
  let popup = document.querySelector('.popup-colour');
  let colorwell = document.querySelector('.colourwell');
  if (popup.style.display === 'block'){
    let color = colorpicker.getCurColorHex();
    colorButton(colorwell, color);
    colorButton(input, color);
    currentColor = color;
    popup.style.display = 'none';
  }else{
    colorButton(colorwell, input.value);
    currentColor = input.value;
  }
}

var drawing = false;
var WIDTH = document.body.clientWidth;
var HEIGHT = document.body.clientHeight;

// Prevent control clicks from passing through to svg
function swallowClicks(evt){
  evt.stopPropagation();
}
document.querySelector('.buttonbar.animation').addEventListener('mousedown', swallowClicks);
document.querySelector('.buttonbar.tools').addEventListener('mousedown', swallowClicks);
document.querySelector('.buttonbar.animation').addEventListener('touchstart', swallowClicks);
document.querySelector('.buttonbar.tools').addEventListener('touchstart', swallowClicks);

function inBounds(x,y){
  return !(x < 0 || x > WIDTH || y < 0 || y > HEIGHT);
}

function getXY(evt){
   if (evt.cancelable) {
      evt.preventDefault();
    }

    const rect = this.canvas.getBoundingClientRect();
    const position = evt.changedTouches && evt.changedTouches[0] || evt;
    let x = position.offsetX;
    let y = position.offsetY;

    if (typeof x === 'undefined') {
      x = position.clientX - rect.left;
    }
    if (typeof y === 'undefined') {
      y = position.clientY - rect.top;
    }
    return {x,y};
}

const toolStart = evt => currentTool.start(evt);
const toolMove = evt => currentTool.move(evt);
const toolStop = evt => currentTool.stop(evt);
const toolCancel = evt => currentTool.cancel();
const escCancel = evt => {
  if (evt.code && evt.code === 'Escape'){
    currentTool.cancel();
  }
}

document.body.addEventListener('mousedown', toolStart);
document.body.addEventListener('touchstart', toolStart);
document.body.addEventListener('mousemove', toolMove);
document.body.addEventListener('touchmove', toolMove);
document.body.addEventListener('touchend', toolStop);
document.body.addEventListener('mouseup', toolStop);
document.body.addEventListener('touchcancel', toolCancel);
document.body.addEventListener('keydown', escCancel);

function currentFrame(){
  return document.querySelector('.frame.selected');
}

function playingFrame(){
  return document.querySelector('.frame.play-frame');
}

var currentPath = null;

function startPath(x,y){

  currentPath = currentFrame().appendChild(dom.svg('path', {
      d: 'M ' + x + ',' + y,
      stroke: currentColor,
      'stroke-width': currentStrokeWidth
  }));
  file.onChange();
}

function appendToPath(x,y){
  var path = document.querySelector('.selected path:last-child');
  var d = path.getAttribute('d');
  path.setAttribute('d', `${d} L${x} ${y}`);
}

/***************************************
*
*  MANAGE FRAMES
*
***************************************/

function isOnionskinOn(){
  return currentDoOnionskin;
}

function currentOnionskinFrame(){
  return document.querySelector('.frame.onionskin');
}

function updateOnionskin(){
  if (!isOnionskinOn()) return;
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  dom.addClass(currentFrame().previousElementSibling, 'onionskin');
}

function addFrame(){
  dom.insertAfter(dom.svg('g', {'class': 'frame selected'}), currentFrame());
  currentFrame().classList.remove('selected');
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function cloneFrame(){
  dom.insertAfter(currentFrame().cloneNode(true), currentFrame());
  currentFrame().classList.remove('selected');
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function deleteFrame(){
  var frameToDelete = currentFrame();
  if (frameToDelete.nextElementSibling){
      incrementFrame();
  }else if (frameToDelete.previousElementSibling){
      decrementFrame();
  }
  if (frameToDelete.parentNode.children.length > 1){
    dom.remove(frameToDelete);
  }else{
    dom.clear(frameToDelete); // don't delete the last frame, just its children
  }
  updateOnionskin();
  updateFrameCount();
  file.onChange();
}

function clear(){
  dom.clear(currentFrame());
}

function toggleOnionskin(){
  if (isOnionskinOn()){
      dom.addClass(currentFrame().previousElementSibling, 'onionskin');
  }else{
      dom.removeClass(currentOnionskinFrame(), 'onionskin');
  }
}

function incrementFrame(){
  var curr = currentFrame();
  if (curr.nextElementSibling){
      curr.classList.remove('selected');
      curr.nextElementSibling.classList.add('selected');
  }
  updateOnionskin();
  updateFrameCount();
}

function decrementFrame(){
  var curr = currentFrame();
  if (curr.previousElementSibling){
      curr.classList.remove('selected');
      curr.previousElementSibling.classList.add('selected');
  }
  updateOnionskin();
  updateFrameCount();
}

function gotoFirstFrame(){
  currentFrame().classList.remove('selected');
  document.querySelector('.frame').classList.add('selected');
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  updateFrameCount();
}

function gotoLastFrame(){
  currentFrame().classList.remove('selected');
  document.querySelector('.frame:last-child').classList.add('selected');
  dom.removeClass(currentOnionskinFrame(), 'onionskin');
  dom.addClass(currentFrame().previousElementSibling, 'onionskin');
  updateFrameCount();
}

var _lastFrameTime = 0;
var _frameDelay = 0;

function play(){
  document.body.classList.add('playing');
  // turn play button into stop button
  // disable all other controls
  // temporarily turn off onionskin (remember state)
  // start at beginning of document (remember state)
  document.querySelector('.frame').classList.add('play-frame');
  // add SVG SMIL animation
  // Unless looping, call stop() when animation is finished
  // How much of this can I do by adding "playing" class to body?
  setTimeout(function(){
      _frameDelay = currentFrameDelay;
      _lastFrameTime = Date.now();
      requestAnimationFrame(playNextFrame);
  }, 500);
}

function stop(){
  // remove SMIL animation
  // re-enable all controls
  // return to the frame we were on
  // re-enable onionskin if needed
  // turn stop button into play button
  dom.removeClass(playingFrame(), 'play-frame');
  document.body.classList.remove('playing');
}

function playNextFrame(){
  var time = Date.now();
  if ((time - _lastFrameTime) < _frameDelay){
      requestAnimationFrame(playNextFrame);
      return;
  }
  var currFrame = playingFrame();
  _lastFrameTime = time;
  if (currFrame.nextElementSibling){
      currFrame.classList.remove('play-frame');
      currFrame.nextElementSibling.classList.add('play-frame');
      requestAnimationFrame(playNextFrame);
  }else{
      stop();
  }
}

function updateFrameCount(){
  try{
      var frames = currentFrame().parentElement.children.length;
      var index = dom.indexOf(currentFrame());
      document.querySelector('.framecount').textContent = 'Frame ' + (index+1) + ' of ' + frames;
  }catch(e){
      // wait for the file to load, probably
  }
}

function undoLine(){
  dom.remove(currentFrame().lastElementChild);
  file.onChange();
}

function keydownHandler(evt){
  if ((evt.key || evt.keyIdentifier) === 'Control'){
      document.body.classList.add('usefiles');
  }
}

function keyupHandler(evt){
  if ((evt.key || evt.keyIdentifier) === 'Control'){
      document.body.classList.remove('usefiles');
  }
}

window.app = {
  updateFrameCount: updateFrameCount,
  play: play
};

// document.querySelector('#canvas-undo').addEventListener('click', undoLine, false);
// document.querySelector('#canvas-onionskin').addEventListener('change', toggleOnionskin, false);
document.addEventListener('keydown', keydownHandler, false);
document.addEventListener('keyup', keyupHandler, false);

<|endoftext|>


<commit_before>/* global digitalWrite, A5, A6, save */
/* eslint-disable no-unused-vars */

// Flash this code onto Pico using Espruino IDE
// Link: http://www.espruino.com/Web+IDE

// Treshold for each scanning cycle
var scanTreshold = 5000
// Treshold for swapping slide
var feedNewPicTreshold = 3000
// Treshold for 'pressing swap slide button'
var feedNewPicButtonTreshold = 500
// Treshold for taking picture
var takePictureTreshold = 800
// Treshold for 'pressing shutter button'
var takePictureButtonTreshold = 300
// Default number of slides in session
var numberOfPics = 36
// Counter startindex
var numberOfScans = 0 // DO NOT CHANGE!
// Cycle scanning interval function
var scanPics

// Stop and reset counter
function stopScanning () {
  clearInterval(scanPics)
  numberOfScans = 0
}

function closeRelay (relay, treshold) {
  console.log('Closing ' + relay)
  digitalWrite(relay, false)
  setTimeout(function () {
    openRelay(relay)
  }, treshold)
}

function openRelay (relay) {
  console.log('Opening ' + relay)
  digitalWrite(relay, true)
}

// Close second relay on port A6 for a while
function takePicture () {
  setTimeout(function () {
    closeRelay(A6, takePictureButtonTreshold, false)
    document.getElementById('scanned').innerHTML = numberOfScans
  }, takePictureTreshold)
}

// Close first relay on port A5 for a while,
// wait for feeding, then take picture
function feedNewPic () {
  closeRelay(A5, feedNewPicButtonTreshold, true)
  setTimeout(function () {
    takePicture()
  }, feedNewPicTreshold)
}

// Start feed/scan loop
function startScanning () {
  scanPics = setInterval(function () {
    feedNewPic()
    console.log(numberOfScans + ':' + numberOfPics)
    if (++numberOfScans >= numberOfPics) {
      stopScanning()
    }
  }, scanTreshold)
}

// Simple ui for start, stop and setting number of slides
function onPageRequest (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'})
  res.write('<meta content="width=device-width, initial-scale=1" name="viewport">' +
  '<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" />' +
  '
Speed scanner

Number of slides' +
  '<input class="form-control" id="pictures" max="100" min="1" type="number" ' +
  'onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"' +
  'value="' + numberOfPics +'" />' +
  '<button class="btn btn-success" id="start">Start</button>' +
  '<button class="btn btn-danger" id="stop">Stop</button>' +
  '
Slides scanned:
')
  res.write('')
  res.end('')
}

// Wifi connection
var wlan
function onInit () {
  wlan = require('CC3000').connect()
  // Do not forget to change 'WifiAccessPointName', 'WifiWPA2key' to your own wifi networks name and pw
  wlan.connect('WifiAccessPointName', 'WifiWPA2key', function (s) {
    if (s === 'dhcp') {
      require('http')
        .createServer(onPageRequest)
        .listen(80)
      console.log('Server created at ' + wlan.getIP().ip)
      // Now you can open up a browser at the ip given above
      // A page with the ui should show up
    }
  })
}

// Disconnect wifi, not used atm
// wlan.disconnect()
<commit_msg>:seal: :whale: remove bootstrap css<commit_after>/* global digitalWrite, A5, A6, save */
/* eslint-disable no-unused-vars */

// Flash this code onto Pico using Espruino IDE
// Link: http://www.espruino.com/Web+IDE

// Treshold for each scanning cycle
var scanTreshold = 5000
// Treshold for swapping slide
var feedNewPicTreshold = 3000
// Treshold for 'pressing swap slide button'
var feedNewPicButtonTreshold = 500
// Treshold for taking picture
var takePictureTreshold = 800
// Treshold for 'pressing shutter button'
var takePictureButtonTreshold = 300
// Default number of slides in session
var numberOfPics = 36
// Counter startindex
var numberOfScans = 0 // DO NOT CHANGE!
// Cycle scanning interval function
var scanPics

// Stop and reset counter
function stopScanning () {
  clearInterval(scanPics)
  numberOfScans = 0
}

function closeRelay (relay, treshold) {
  console.log('Closing ' + relay)
  digitalWrite(relay, false)
  setTimeout(function () {
    openRelay(relay)
  }, treshold)
}

function openRelay (relay) {
  console.log('Opening ' + relay)
  digitalWrite(relay, true)
}

// Close second relay on port A6 for a while
function takePicture () {
  setTimeout(function () {
    closeRelay(A6, takePictureButtonTreshold, false)
    document.getElementById('scanned').innerHTML = numberOfScans
  }, takePictureTreshold)
}

// Close first relay on port A5 for a while,
// wait for feeding, then take picture
function feedNewPic () {
  closeRelay(A5, feedNewPicButtonTreshold, true)
  setTimeout(function () {
    takePicture()
  }, feedNewPicTreshold)
}

// Start feed/scan loop
function startScanning () {
  scanPics = setInterval(function () {
    feedNewPic()
    console.log(numberOfScans + ':' + numberOfPics)
    if (++numberOfScans >= numberOfPics) {
      stopScanning()
    }
  }, scanTreshold)
}

// Simple ui for start, stop and setting number of slides
function onPageRequest (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'})
  res.write('<meta content="width=device-width, initial-scale=1" name="viewport">' +
  '' +
  '
Speed scanner

Number of slides' +
  '<input class="form-control" id="pictures" max="100" min="1" type="number" ' +
  'onkeypress="return event.charCode === 0 || /\d/.test(String.fromCharCode(event.charCode));"' +
  'value="' + numberOfPics +'" />' +
  '<button class="btn btn-success" id="start">Start</button>' +
  '<button class="btn btn-danger" id="stop">Stop</button>' +
  '
Slides scanned:
')
  res.write('')
  res.end('')
}

// Wifi connection
var wlan
function onInit () {
  wlan = require('CC3000').connect()
  // Do not forget to change 'WifiAccessPointName', 'WifiWPA2key' to your own wifi networks name and pw
  wlan.connect('WifiAccessPointName', 'WifiWPA2key', function (s) {
    if (s === 'dhcp') {
      require('http')
        .createServer(onPageRequest)
        .listen(80)
      console.log('Server created at ' + wlan.getIP().ip)
      // Now you can open up a browser at the ip given above
      // A page with the ui should show up
    }
  })
}

// Disconnect wifi, not used atm
// wlan.disconnect()
<|endoftext|>


<commit_before>// VARIABLE
var MonthFrenchNameArray = [
	"Janvier",
	"Février",
	"Mars",
	"Avril",
	"Mai",
	"Juin",
	"Juillet",
	"Août",
	"Septembre",
	"Octobre",
	"Novembre",
	"Décembre"
];
var DayOfWeekArray = [
	"D",
	"L",
	"M",
	"M",
	"J",
	"V",
	"S",
];
var Number = 0;
var ThisRel = 0;
var ThisDuration = 0;
var ThisTeamate = 0;
var ThisProject = 0;
var TodayIs = 13; var Size = 40;
function initializePeriod(fromDate, toDate)
{
	if(!fromDate)
	{
		fromDate = new Date();
		// Set to first day of the month
		fromDate.setDate(1);
		fromDate.setMonth(fromDate.getMonth()-2);
	}
	if(!toDate)
	{
		toDate = new Date();
		// Set to first day of the month
		toDate.setDate(1);
		toDate.setMonth(toDate.getMonth()+4+1);
		// Set to last day of the month
		toDate.setDate(0);
	}
	// console.log("fromDate : "+fromDate.toISOString());
	// console.log("toDate : "+toDate.toISOString());
}
function Blocs() {
	// CREATE BLOC
	$('.blocs').empty();
	$('#period .days .bloc').each(function(){
		Number++
		//$('.blocs').append('
'+Number+'
');
		$('.blocs').append('

');
	});
}
function Work() {
	$('.work').each(function(){
		// CREATE WORK
		var This = $(this);
		var TheMonth = This.attr('month');
		var Duration = This.attr('duration');
		var Start = This.attr('start');
		This.css({ width: Size*Duration+(2*Duration), left: Size*(Start-1)+(2*(Start-1))+(TheMonth*Size+TheMonth*2) });
	});
}
function Click() {
	// CLICK PERIOD
	$('#calendar .month').click(function() {
		var Defil = $(this).attr('duration');
		if ($(this).hasClass('first')) {
			$('#today').stop().animate({ marginLeft: 0 });
			$('#period').stop().animate({ marginLeft: 300 });
			$('.blocs, .work').stop().animate({ marginLeft: 0 });
		} else {
			$('#today').stop().animate({ marginLeft: -(Defil*Size + Defil*2)+340 });
			$('#period').stop().animate({ marginLeft: -(Defil*Size + Defil*2)+340 });
			$('.blocs, .work').stop().animate({ marginLeft: -((Defil-1)*Size + (Defil-1)*2) });
		}
	});
}
function Today() {
	$('#today').css({ left: (TodayIs-1)*Size+((TodayIs-1)*2)+301 });
}

$(document).ready(function() {
	initializePeriod();
	Blocs();
	Work();
	Click();
	Today();

/*
	// SMALL
	$(window).keydown(function(e) {
		// RIGHT ARROW
		switch (e.keyCode) {
		case 39:
			$('body').addClass('small');
			Size = 20;
			Blocs();
			Work();
			Click();
			Today();
		}
		// LEFT ARROW
		switch (e.keyCode) {
		case 37:
			$('body').removeClass('small');
			Size = 40;
			Work();
			Blocs();
			Click();
			Today();
		}
	});
*/

	// CLICK FILTER PROJECT
	$('#legend .filter_project').click(function() {
		ThisProject = $(this).attr('rel');
		$('.project').css({ display: 'none' });
		$('.project.'+ThisProject).css({ display: 'block' });
		$('.filter_project, .filter_project_all').removeClass('active');
		$(this).addClass('active');
	});
	$('#legend .filter_project_all').click(function() {
		$('.project').css({ display: 'block' }).addClass('active');
		$('.filter_project').removeClass('active');
		$(this).addClass('active');
	});
	// CLICK FILTER PEOPLE
	$('#legend .filter_people').click(function() {
		ThisProject = $(this).attr('rel');
		$('.user').css({ display: 'none' }); $('.user').parent().css({ display: 'none' });
		$('.user.'+ThisProject).css({ display: 'block' }); $('.user.'+ThisProject).parent().css({ display: 'block' });
		$('.filter_people, .filter_people_all').removeClass('active');
		$(this).addClass('active');
	});
	$('#legend .filter_people_all').click(function() {
		$('.user').css({ display: 'block' });
		$('.filter_people').removeClass('active'); $('.user').parent().css({ display: 'block' });
		$(this).addClass('active');
	});
	// CLICK FILTER METIER
	$('#legend .filter_metier').click(function() {
		ThisProject = $(this).attr('rel');
		$('.project .work').css({ display: 'none' });
		$('.project .work.'+ThisProject).css({ display: 'block' });
		$('.filter_metier, .filter_metier_all').removeClass('active');
		$(this).addClass('active');
	});
	$('#legend .filter_metier_all').click(function() {
		$('.project .work').css({ display: 'block' }).addClass('active');
		$('.filter_metier').removeClass('active');
		$(this).addClass('active');
	});

	// HOVER ON WORK
	$('.work').hover(function(event){
		ThisRel = $(this).attr('rel');
		ThisDuration = $(this).attr('duration');
		var NoLimit = $(this).attr('nolimit');
		ThisTeamate = $(this).parent().parent().find('.name').text();
		$('.work').mousemove(function( event ) {
			var Scroller = $(document).scrollTop();
			$(this).parent().find('.description.'+ThisRel).css({ display: 'block', marginLeft: event.pageX+50, marginTop: event.pageY-Size-30-Scroller });
		});
		if (NoLimit == 'NoLimit') {
			$(this).parent().find('.description.'+ThisRel).find('.title span').html(' [ '+ThisTeamate+', sans date de fin ]');
		} else {
			$(this).parent().find('.description.'+ThisRel).find('.title span').html(' [ '+ThisTeamate+', '+ThisDuration+' jour(s) ]');
		}
	}, function() {
		$(this).parent().find('.description.'+ThisRel).css({ display: 'none' });
	});

	// CURSOR
	$(window).mousemove(function( event ) {
		$('#cursor').css({ left: event.pageX });
	});
});<commit_msg>Implement creation of period of time<commit_after>// VARIABLE
var MonthFrenchNameArray = [
	"Janvier",
	"Février",
	"Mars",
	"Avril",
	"Mai",
	"Juin",
	"Juillet",
	"Août",
	"Septembre",
	"Octobre",
	"Novembre",
	"Décembre"
];
var DayOfWeekArray = [
	"D",
	"L",
	"M",
	"M",
	"J",
	"V",
	"S",
];
var Number = 0;
var ThisRel = 0;
var ThisDuration = 0;
var ThisTeamate = 0;
var ThisProject = 0;
var TodayIs = 13; var Size = 40;
function initializePeriod(fromDate, toDate)
{
	if(!fromDate)
	{
		fromDate = new Date();
		// Set to first day of the month
		fromDate.setDate(1);
		fromDate.setMonth(fromDate.getMonth()-2);
	}
	if(!toDate)
	{
		toDate = new Date();
		// Set to first day of the month
		toDate.setDate(1);
		toDate.setMonth(toDate.getMonth()+4+1);
		// Set to last day of the month
		toDate.setDate(0);
	}
	// console.log("fromDate : "+fromDate.toISOString());
	// console.log("toDate : "+toDate.toISOString());
	if(fromDate>toDate)
	{
		// WARNING : unexpected case
		var temp = fromDate;
		fromDate = toDate;
		toDate = fromDate;
	}
	{
		var periodElement = $("#period");
		periodElement.empty();
		var lastMonthString = null;
		var lastMonthDaysElement = null;
		var lastMonthDateElement = null;
		for (var d = new Date(fromDate); d <= toDate; d.setDate(d.getDate() + 1))
		{
			var currentMonthString = d.getFullYear()+'-'+(d.getMonth()+1);
			console.log("currentMonthString : "+currentMonthString);
			if( currentMonthString != lastMonthString )
			{
				lastMonthDaysElement = null;
				lastMonthDateElement = null;

				var newMonthElement = $('
');
				periodElement.append(newMonthElement);
				newMonthElement.addClass('month').append("
"+MonthFrenchNameArray[d.getMonth()]+" "+d.getFullYear()+"
");
				{
					var newDaysElement = $('
');
					newMonthElement.append(newDaysElement);
					newDaysElement.addClass('days');
					lastMonthDaysElement = newDaysElement;
				}
				{
					var newDateElement = $('
');
					newMonthElement.append(newDateElement);
					newDateElement.addClass('date');
					lastMonthDateElement = newDateElement;
				}
			}
			lastMonthString = currentMonthString;
			if(null != lastMonthDaysElement)
			{
				var newDayElement = $('
');
				lastMonthDaysElement.append(newDayElement);
				newDayElement.addClass('bloc').text(DayOfWeekArray[d.getDay()]);
				if(
					// S
					d.getDay() == 6
					// D
					|| d.getDay() == 0
					)
				{
					newDayElement.addClass('we');
				}
			}
			if(null != lastMonthDateElement)
			{
				var newDateElement = $('
');
				lastMonthDateElement.append(newDateElement);
				newDateElement.addClass('bloc').text(d.getDate());
				if(
					// S
					d.getDay() == 6
					// D
					|| d.getDay() == 0
					)
				{
					newDateElement.addClass('we');
				}
			}
		}
	}
}
function Blocs() {
	// CREATE BLOC
	$('.blocs').empty();
	$('#period .days .bloc').each(function(){
		Number++
		//$('.blocs').append('
'+Number+'
');
		$('.blocs').append('

');
	});
}
function Work() {
	$('.work').each(function(){
		// CREATE WORK
		var This = $(this);
		var TheMonth = This.attr('month');
		var Duration = This.attr('duration');
		var Start = This.attr('start');
		This.css({ width: Size*Duration+(2*Duration), left: Size*(Start-1)+(2*(Start-1))+(TheMonth*Size+TheMonth*2) });
	});
}
function Click() {
	// CLICK PERIOD
	$('#calendar .month').click(function() {
		var Defil = $(this).attr('duration');
		if ($(this).hasClass('first')) {
			$('#today').stop().animate({ marginLeft: 0 });
			$('#period').stop().animate({ marginLeft: 300 });
			$('.blocs, .work').stop().animate({ marginLeft: 0 });
		} else {
			$('#today').stop().animate({ marginLeft: -(Defil*Size + Defil*2)+340 });
			$('#period').stop().animate({ marginLeft: -(Defil*Size + Defil*2)+340 });
			$('.blocs, .work').stop().animate({ marginLeft: -((Defil-1)*Size + (Defil-1)*2) });
		}
	});
}
function Today() {
	$('#today').css({ left: (TodayIs-1)*Size+((TodayIs-1)*2)+301 });
}

$(document).ready(function() {
	initializePeriod();
	Blocs();
	Work();
	Click();
	Today();

/*
	// SMALL
	$(window).keydown(function(e) {
		// RIGHT ARROW
		switch (e.keyCode) {
		case 39:
			$('body').addClass('small');
			Size = 20;
			Blocs();
			Work();
			Click();
			Today();
		}
		// LEFT ARROW
		switch (e.keyCode) {
		case 37:
			$('body').removeClass('small');
			Size = 40;
			Work();
			Blocs();
			Click();
			Today();
		}
	});
*/

	// CLICK FILTER PROJECT
	$('#legend .filter_project').click(function() {
		ThisProject = $(this).attr('rel');
		$('.project').css({ display: 'none' });
		$('.project.'+ThisProject).css({ display: 'block' });
		$('.filter_project, .filter_project_all').removeClass('active');
		$(this).addClass('active');
	});
	$('#legend .filter_project_all').click(function() {
		$('.project').css({ display: 'block' }).addClass('active');
		$('.filter_project').removeClass('active');
		$(this).addClass('active');
	});
	// CLICK FILTER PEOPLE
	$('#legend .filter_people').click(function() {
		ThisProject = $(this).attr('rel');
		$('.user').css({ display: 'none' }); $('.user').parent().css({ display: 'none' });
		$('.user.'+ThisProject).css({ display: 'block' }); $('.user.'+ThisProject).parent().css({ display: 'block' });
		$('.filter_people, .filter_people_all').removeClass('active');
		$(this).addClass('active');
	});
	$('#legend .filter_people_all').click(function() {
		$('.user').css({ display: 'block' });
		$('.filter_people').removeClass('active'); $('.user').parent().css({ display: 'block' });
		$(this).addClass('active');
	});
	// CLICK FILTER METIER
	$('#legend .filter_metier').click(function() {
		ThisProject = $(this).attr('rel');
		$('.project .work').css({ display: 'none' });
		$('.project .work.'+ThisProject).css({ display: 'block' });
		$('.filter_metier, .filter_metier_all').removeClass('active');
		$(this).addClass('active');
	});
	$('#legend .filter_metier_all').click(function() {
		$('.project .work').css({ display: 'block' }).addClass('active');
		$('.filter_metier').removeClass('active');
		$(this).addClass('active');
	});

	// HOVER ON WORK
	$('.work').hover(function(event){
		ThisRel = $(this).attr('rel');
		ThisDuration = $(this).attr('duration');
		var NoLimit = $(this).attr('nolimit');
		ThisTeamate = $(this).parent().parent().find('.name').text();
		$('.work').mousemove(function( event ) {
			var Scroller = $(document).scrollTop();
			$(this).parent().find('.description.'+ThisRel).css({ display: 'block', marginLeft: event.pageX+50, marginTop: event.pageY-Size-30-Scroller });
		});
		if (NoLimit == 'NoLimit') {
			$(this).parent().find('.description.'+ThisRel).find('.title span').html(' [ '+ThisTeamate+', sans date de fin ]');
		} else {
			$(this).parent().find('.description.'+ThisRel).find('.title span').html(' [ '+ThisTeamate+', '+ThisDuration+' jour(s) ]');
		}
	}, function() {
		$(this).parent().find('.description.'+ThisRel).css({ display: 'none' });
	});

	// CURSOR
	$(window).mousemove(function( event ) {
		$('#cursor').css({ left: event.pageX });
	});
});<|endoftext|>


<commit_before>export default {
  analyticsKey: '',
  contactFormEmail: '',
  dashboardUrl: '',
  statusPageStatusUrl: '',
  syncanoAPIBaseUrl: '',
  hello: {
    github: '',
    facebook: '',
    google: '',
    redirect_uri: ''
  }
};
<commit_msg>[WEB-429] Update development config<commit_after>export default {
  analyticsKey: '',
  contactFormEmail: '',
  dashboardUrl: '',
  statusPageStatusUrl: '',
  syncanoAPIBaseUrl: '',
  supportFormEmail: '',
  github: '',
  facebook: '',
  google: '',
  redirect_uri: '',
  twitterConsumerKey: '',
  twitterConsumerSecret: '',
  twitterAccessToken: '',
  twitterAccessTokenSecret: ''
};
<|endoftext|>


<commit_before>var error_nominee_no_text, error_nominee_count_text, success_text, share_text, title_text, close_text;

if(document.URL.indexOf("en") >= 0){
    close_text = "Close";
    error_nominee_no_text = "Number of nominees should be higher than number of winners !";
    error_nominee_count_text = "Number of winners should be higher than 0 !";
    success_text = "Congratulations!";
    share_text = "share: ";
    title_text = "Winner";
} else{
    close_text = "Kapat";
    error_nominee_no_text = "Aday sayısı kazanan sayısından fazla olmalıdır";
    error_nominee_count_text = "Kazanan sayısı en az 1 olmalıdır.";
    success_text = "Tebrikler";
    share_text = "paylaş: ";
    title_text = "Kazananlar";
}

var error_nominee_no = "
" +
    "<button type='button' class='close' data-dismiss='alert' aria-label='"+close_text+"'>" +
    "×</button>" +
    error_nominee_no_text +
    "
";

var error_nominee_count = "
" +
    "<button type='button' class='close' data-dismiss='alert' aria-label='"+close_text+"'>" +
    "×</button>" +
    error_nominee_count_text +
    "
";

var success = "
" +
    "<button type='button' class='close' data-dismiss='alert' aria-label='"+close_text+"'>" +
    "×</button>" +
    "
 "+success_text+"
" +
    "
";

$(document).ready(function(){
    $('#get-result').click(function(e){
        e.preventDefault();
        var lines = $('#user-input').val().replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w]+/g," ").trim().split(' ');
        var message = "";
        var nomineeCount = $('#count').val();
        if((lines.length -1 < nomineeCount))
        {
            message += error_nominee_no;
        }
        else if (nomineeCount<1)
        {
            message += error_nominee_count;
        }
        else
        {
            message += success;
            var winners = [];
            while(nomineeCount != 0)
            {
                for(var i = 0; i < nomineeCount; i++)
                {
                    var winner = lines[Math.floor(lines.length * Math.random())];
                    if($.inArray(winner, winners) <= -1)
                    {
                        winners[i] = winner;
                        message += "
" + winner + "
";
                        nomineeCount--;
                    }
                }
            }
            message += "
";
            message += "
";
        }
        $("#result").hide().html(message).fadeIn('slow');
        $('body').scrollTo('#result');
        $("meta[property='og\\:description']").attr("content", $("#result").text());
    });
    // paylaş butonları
    $("body").floatingSocialShare({
        buttons: ["facebook","twitter"],
        text: share_text,
        title: title_text,
        description: $("#result").text(),
        url: window.location.href
    });
    // analitik
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-63148072-1', 'auto');
    ga('send', 'pageview');
});
(function (d, w, c) {
    (w[c] = w[c] || []).push(function() {
        try {
            w.yaCounter32203149 = new Ya.Metrika({
                id:32203149,
                clickmap:true,
                trackLinks:true,
                accurateTrackBounce:true
            });
        } catch(e) { }
    });

    var n = d.getElementsByTagName("script")[0],
        s = d.createElement("script"),
        f = function () { n.parentNode.insertBefore(s, n); };
    s.type = "text/javascript";
    s.async = true;
    s.src = "https://mc.yandex.ru/metrika/watch.js";

    if (w.opera == "[object Opera]") {
        d.addEventListener("DOMContentLoaded", f, false);
    } else { f(); }
})(document, window, "yandex_metrika_callbacks");
<commit_msg>scroll to func. on comment<commit_after>var error_nominee_no_text, error_nominee_count_text, success_text, share_text, title_text, close_text;

if(document.URL.indexOf("en") >= 0){
    close_text = "Close";
    error_nominee_no_text = "Number of nominees should be higher than number of winners !";
    error_nominee_count_text = "Number of winners should be higher than 0 !";
    success_text = "Congratulations!";
    share_text = "share: ";
    title_text = "Winner";
} else{
    close_text = "Kapat";
    error_nominee_no_text = "Aday sayısı kazanan sayısından fazla olmalıdır";
    error_nominee_count_text = "Kazanan sayısı en az 1 olmalıdır.";
    success_text = "Tebrikler";
    share_text = "paylaş: ";
    title_text = "Kazananlar";
}

var error_nominee_no = "
" +
    "<button type='button' class='close' data-dismiss='alert' aria-label='"+close_text+"'>" +
    "×</button>" +
    error_nominee_no_text +
    "
";

var error_nominee_count = "
" +
    "<button type='button' class='close' data-dismiss='alert' aria-label='"+close_text+"'>" +
    "×</button>" +
    error_nominee_count_text +
    "
";

var success = "
" +
    "<button type='button' class='close' data-dismiss='alert' aria-label='"+close_text+"'>" +
    "×</button>" +
    "
 "+success_text+"
" +
    "
";

$(document).ready(function(){
    $('#get-result').click(function(e){
        e.preventDefault();
        var lines = $('#user-input').val().replace(/[^\u00BF-\u1FFF\u2C00-\uD7FF\w]+/g," ").trim().split(' ');
        var message = "";
        var nomineeCount = $('#count').val();
        if((lines.length -1 < nomineeCount))
        {
            message += error_nominee_no;
        }
        else if (nomineeCount<1)
        {
            message += error_nominee_count;
        }
        else
        {
            message += success;
            var winners = [];
            while(nomineeCount != 0)
            {
                for(var i = 0; i < nomineeCount; i++)
                {
                    var winner = lines[Math.floor(lines.length * Math.random())];
                    if($.inArray(winner, winners) <= -1)
                    {
                        winners[i] = winner;
                        message += "
" + winner + "
";
                        nomineeCount--;
                    }
                }
            }
            message += "
";
            message += "
";
        }
        $("#result").hide().html(message).fadeIn('slow');
        // scroll to func: $('body').scrollTo('#result');
        $("meta[property='og\\:description']").attr("content", $("#result").text());
    });
    // paylaş butonları
    $("body").floatingSocialShare({
        buttons: ["facebook","twitter"],
        text: share_text,
        title: title_text,
        description: $("#result").text(),
        url: window.location.href
    });
    // analitik
    (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
        m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
    })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

    ga('create', 'UA-63148072-1', 'auto');
    ga('send', 'pageview');
});
(function (d, w, c) {
    (w[c] = w[c] || []).push(function() {
        try {
            w.yaCounter32203149 = new Ya.Metrika({
                id:32203149,
                clickmap:true,
                trackLinks:true,
                accurateTrackBounce:true
            });
        } catch(e) { }
    });

    var n = d.getElementsByTagName("script")[0],
        s = d.createElement("script"),
        f = function () { n.parentNode.insertBefore(s, n); };
    s.type = "text/javascript";
    s.async = true;
    s.src = "https://mc.yandex.ru/metrika/watch.js";

    if (w.opera == "[object Opera]") {
        d.addEventListener("DOMContentLoaded", f, false);
    } else { f(); }
})(document, window, "yandex_metrika_callbacks");
<|endoftext|>