<commit_before>//VARIAVEIS GLOBAIS
	var retornoVerificaComerciante = null;
//FIM VARIAVEIS GLOBAIS

function getCidade(el){
	try{
		var cidade = $(el).val();
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/getCidade.php",
			data     : { q : cidade},
			async    : true,
			success  : function (resp){
				var retorno = "
";
				for(row in resp){
					retorno += "
"
						+resp[row].nome_cid+" - "+resp[row].sigla_est+"
";
				}
				retorno += "
";
				$("#returnCidade").empty().append(retorno);
			}
		});
	}catch($e){
		alert('Erro na getCidade : '+$e);
	}
}
function getCidade2(el){
	try{
		var cidade = $(el).val();
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/getCidade.php",
			data     : { q : cidade},
			async    : true,
			success  : function (resp){
				var retorno = "
";
				for(row in resp){
					retorno += "
"+
					resp[row].nome_cid+" - "+resp[row].sigla_est+"
";
				}
				retorno += "
";
				$("#returnCidade").empty().append(retorno);
			}
		});
	}catch($e){
		alert('Erro na getCidade2 : '+$e);
	}
}
function setReturnCidade(){
	setTimeout('$("#returnCidade").empty();', 3000);
}
function setCidade(id_cid){
	window.location = '/OfertaAki/config/connection/loginUsuario.php?id_cid='+id_cid;
}
function setCidade2(id_cid, nome_cid, sigla_est){
	$('#id_cid_com2').val(nome_cid+' - '+sigla_est);
	$('#id_cid_com').val(id_cid);
}
function opcoesComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/opcoesComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function logarComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/logarComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function cadastroComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/cadastroComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function indexGeral(){
	var raiz = location.origin+'/OfertaAki/ajax/indexGeral.html #load';
	$(".content-home > .row").load(raiz);
}
function validarCNPJ(cnpj){

	cnpj = cnpj.replace(/[^\d]+/g,'');

	if(cnpj == '') return true;

	if (cnpj.length != 14)
		return true;

	// Elimina CNPJs invalidos conhecidos
	if (cnpj == "00000000000000" ||
		cnpj == "11111111111111" ||
		cnpj == "22222222222222" ||
		cnpj == "33333333333333" ||
		cnpj == "44444444444444" ||
		cnpj == "55555555555555" ||
		cnpj == "66666666666666" ||
		cnpj == "77777777777777" ||
		cnpj == "88888888888888" ||
		cnpj == "99999999999999")
		return true;

	// Valida DVs
	tamanho = cnpj.length - 2
	numeros = cnpj.substring(0,tamanho);
	digitos = cnpj.substring(tamanho);
	soma = 0;
	pos = tamanho - 7;
	for (i = tamanho; i >= 1; i--) {
		soma += numeros.charAt(tamanho - i) * pos--;
		if (pos < 2)
			pos = 9;
	}
	resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
	if (resultado != digitos.charAt(0))
		return true;

	tamanho = tamanho + 1;
	numeros = cnpj.substring(0,tamanho);
	soma = 0;
	pos = tamanho - 7;
	for (i = tamanho; i >= 1; i--) {
		soma += numeros.charAt(tamanho - i) * pos--;
		if (pos < 2)
			pos = 9;
	}
	resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
	if (resultado != digitos.charAt(1))
		return true;

	return false;

}
function validaEmail(email){
	var er = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;
	if(er.exec(email)){
		return false;
	}else{
		return true;
	}
}
function buscaPorCep(cep){
	cep = cep.val();
	if(cep.length >= 10){
		cep = cep.replace(/[^\d]+/g,'');
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : "https://viacep.com.br/ws/"+cep+"/json",
			async    : true,
			success  : function (resp){
				$('#id_cid_com2').val(resp.localidade);
				$('#bairro_com').val(resp.bairro);
				$('#endereco_com').val(resp.logradouro);
				$.ajax({
					type     : "GET",
					dataType : "json",
					url      : raiz+"/OfertaAki/ajax/getCidade.php",
					data     : { q : resp.localidade},
					async    : true,
					success  : function (resp){
						$('#id_cid_com').val(resp.id_cid);
					}
				});
			}
		});
	}
}
function verificaComerciante(email_com){
	try{
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/verificaComerciante.php",
			data     : { email_com : email_com},
			async    : true,
			success  : function(resp){
				if(resp.verificaComerciante == 'cadastrado'){
					retornoVerificaComerciante = true;
				}else{
					retornoVerificaComerciante = false;
				}
			}
		});
	}catch($e){
		alert('Erro na verificaComerciante : '+$e);
	}
}
function validaCadastroComerciante(){
	try{
		if($('#cnpj_com').val()==''){
			alert("Informe seu CNPJ!");
			$('#cnpj_com').val("");
			$('#cnpj_com').focus();
			return false;
		}else if(validarCNPJ($('#cnpj_com').val())){
			alert("CNPJ Invalido!");
			$('#cnpj_com').val("");
			$('#cnpj_com').focus();
		}else if($('#email_com').val()==''){
			alert("Informe seu EMAIL!");
			$('#email_com').val("");
			$('#email_com').focus();
			return false;
		}else if(validaEmail($('#email_com').val())){
			alert("EMAIL Invalido!");
			$('#email_com').val("");
			$('#email_com').focus();
			return false;
		}else if($('#senha_com').val()==''){
			alert("Informe sua SENHA!");
			$('#senha_com').val("");
			$('#senha_com').focus();
			return false;
		}else if($('#senha_com2').val()!=
			$('#senha_com').val()){
			alert("Senhas informadas são invalidas!");
			$('#senha_com2').val("");
			$('#senha_com2').focus();
			return false;
		}else if($('#id_cid_com').val()==''){
			alert("Informe sua CIDADE!");
			$('#id_cid_com2').val("");
			$('#id_cid_com2').focus();
			return false;
		}else if($('#razaoSocial_com').val()==''){
			alert("Informe sua RAZÃO SOCIAL!");
			$('#razaoSocial_com').val("");
			$('#razaoSocial_com').focus();
			return false;
		}else if($('#responsavel_com').val()==''){
			alert("Informe o RESPONSAVEL pela Empresa!");
			$('#responsavel_com').val("");
			$('#responsavel_com').focus();
			return false;
		}else if($('#bairro_com').val()==''){
			alert("Informe seu BAIRRO!");
			$('#bairro_com').val("");
			$('#bairro_com').focus();
			return false;
		}else if($('#endereco_com').val()==''){
			alert("Informe seu ENDEREÇO!");
			$('#endereco_com').val("");
			$('#endereco_com').focus();
			return false;
		}else{
			verificaComerciante($('#email_com').val());
			if(retornoVerificaComerciante){
				alert("EMAIL '"+$('#email_com').val()+"' já cadastrado, favor informe outro EMAIL!");
				$('#email_com').val("");
				$('#email_com').focus();
				retornoVerificaComerciante = null;
				return false;
			}else{
				alert('Tudo Certo com o Form!');
			}
		}
	}catch($e){
		alert('Erro na validação do cadastro!');
	}
}

$(document).ready(function(){
	indexGeral();
});
<commit_msg>update 01/06/2016<commit_after>//VARIAVEIS GLOBAIS
	var retornoVerificaComerciante = null;
//FIM VARIAVEIS GLOBAIS

function getCidade(el){
	try{
		var cidade = $(el).val();
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/getCidade.php",
			data     : { q : cidade},
			async    : true,
			success  : function (resp){
				var retorno = "
";
				for(row in resp){
					retorno += "
"
						+resp[row].nome_cid+" - "+resp[row].sigla_est+"
";
				}
				retorno += "
";
				$("#returnCidade").empty().append(retorno);
			}
		});
	}catch($e){
		alert('Erro na getCidade : '+$e);
	}
}
function getCidade2(el){
	try{
		var cidade = $(el).val();
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/getCidade.php",
			data     : { q : cidade},
			async    : true,
			success  : function (resp){
				var retorno = "
";
				for(row in resp){
					retorno += "
"+
					resp[row].nome_cid+" - "+resp[row].sigla_est+"
";
				}
				retorno += "
";
				$("#returnCidade").empty().append(retorno);
			}
		});
	}catch($e){
		alert('Erro na getCidade2 : '+$e);
	}
}
function setReturnCidade(){
	setTimeout('$("#returnCidade").empty();', 3000);
}
function setCidade(id_cid){
	window.location = '/OfertaAki/config/connection/loginUsuario.php?id_cid='+id_cid;
}
function setCidade2(id_cid, nome_cid, sigla_est){
	$('#id_cid_com2').val(nome_cid+' - '+sigla_est);
	$('#id_cid_com').val(id_cid);
}
function opcoesComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/opcoesComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function logarComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/logarComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function cadastroComerciante(){
	var raiz = location.origin+'/OfertaAki/ajax/cadastroComerciante.html #load';
	$(".content-home > .row").load(raiz);
}
function indexGeral(){
	var raiz = location.origin+'/OfertaAki/ajax/indexGeral.html #load';
	$(".content-home > .row").load(raiz);
}
function validarCNPJ(cnpj){

	cnpj = cnpj.replace(/[^\d]+/g,'');

	if(cnpj == '') return true;

	if (cnpj.length != 14)
		return true;

	// Elimina CNPJs invalidos conhecidos
	if (cnpj == "00000000000000" ||
		cnpj == "11111111111111" ||
		cnpj == "22222222222222" ||
		cnpj == "33333333333333" ||
		cnpj == "44444444444444" ||
		cnpj == "55555555555555" ||
		cnpj == "66666666666666" ||
		cnpj == "77777777777777" ||
		cnpj == "88888888888888" ||
		cnpj == "99999999999999")
		return true;

	// Valida DVs
	tamanho = cnpj.length - 2
	numeros = cnpj.substring(0,tamanho);
	digitos = cnpj.substring(tamanho);
	soma = 0;
	pos = tamanho - 7;
	for (i = tamanho; i >= 1; i--) {
		soma += numeros.charAt(tamanho - i) * pos--;
		if (pos < 2)
			pos = 9;
	}
	resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
	if (resultado != digitos.charAt(0))
		return true;

	tamanho = tamanho + 1;
	numeros = cnpj.substring(0,tamanho);
	soma = 0;
	pos = tamanho - 7;
	for (i = tamanho; i >= 1; i--) {
		soma += numeros.charAt(tamanho - i) * pos--;
		if (pos < 2)
			pos = 9;
	}
	resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
	if (resultado != digitos.charAt(1))
		return true;

	return false;

}
function validaEmail(email){
	var er = /^[a-zA-Z0-9][a-zA-Z0-9\._-]+@([a-zA-Z0-9\._-]+\.)[a-zA-Z-0-9]{2}/;
	if(er.exec(email)){
		return false;
	}else{
		return true;
	}
}
function buscaPorCep(cep){
	cep = cep.val();
	if(cep.length >= 10){
		cep = cep.replace(/[^\d]+/g,'');
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : "https://viacep.com.br/ws/"+cep+"/json",
			async    : true,
			success  : function (resp){
				$('#id_cid_com2').val(resp.localidade);
				$('#bairro_com').val(resp.bairro);
				$('#endereco_com').val(resp.logradouro);
				$.ajax({
					type     : "GET",
					dataType : "json",
					url      : raiz+"/OfertaAki/ajax/getCidade.php",
					data     : { q : resp.localidade},
					async    : true,
					success  : function (resp){
						for(row in resp){
							$('#id_cid_com').val(resp[row].id_cid);
						}
					}
				});
			}
		});
	}
}
function verificaComerciante(email_com){
	try{
		var raiz = location.origin;
		$.ajax({
			type     : "GET",
			dataType : "json",
			url      : raiz+"/OfertaAki/ajax/verificaComerciante.php",
			data     : { email_com : email_com},
			async    : true,
			success  : function(resp){
				if(resp.verificaComerciante == 'cadastrado'){
					retornoVerificaComerciante = true;
				}else{
					retornoVerificaComerciante = false;
				}
			}
		});
	}catch($e){
		alert('Erro na verificaComerciante : '+$e);
	}
}
function validaCadastroComerciante(){
	try{
		if($('#cnpj_com').val()==''){
			alert("Informe seu CNPJ!");
			$('#cnpj_com').val("");
			$('#cnpj_com').focus();
			return false;
		}else if(validarCNPJ($('#cnpj_com').val())){
			alert("CNPJ Invalido!");
			$('#cnpj_com').val("");
			$('#cnpj_com').focus();
		}else if($('#email_com').val()==''){
			alert("Informe seu EMAIL!");
			$('#email_com').val("");
			$('#email_com').focus();
			return false;
		}else if(validaEmail($('#email_com').val())){
			alert("EMAIL Invalido!");
			$('#email_com').val("");
			$('#email_com').focus();
			return false;
		}else if($('#senha_com').val()==''){
			alert("Informe sua SENHA!");
			$('#senha_com').val("");
			$('#senha_com').focus();
			return false;
		}else if($('#senha_com2').val()!=
			$('#senha_com').val()){
			alert("Senhas informadas são invalidas!");
			$('#senha_com2').val("");
			$('#senha_com2').focus();
			return false;
		}else if($('#id_cid_com').val()==''){
			alert("Informe sua CIDADE!");
			$('#id_cid_com2').val("");
			$('#id_cid_com2').focus();
			return false;
		}else if($('#razaoSocial_com').val()==''){
			alert("Informe sua RAZÃO SOCIAL!");
			$('#razaoSocial_com').val("");
			$('#razaoSocial_com').focus();
			return false;
		}else if($('#responsavel_com').val()==''){
			alert("Informe o RESPONSAVEL pela Empresa!");
			$('#responsavel_com').val("");
			$('#responsavel_com').focus();
			return false;
		}else if($('#bairro_com').val()==''){
			alert("Informe seu BAIRRO!");
			$('#bairro_com').val("");
			$('#bairro_com').focus();
			return false;
		}else if($('#endereco_com').val()==''){
			alert("Informe seu ENDEREÇO!");
			$('#endereco_com').val("");
			$('#endereco_com').focus();
			return false;
		}else{
			verificaComerciante($('#email_com').val());
			if(retornoVerificaComerciante){
				alert("EMAIL '"+$('#email_com').val()+"' já cadastrado, favor informe outro EMAIL!");
				$('#email_com').val("");
				$('#email_com').focus();
				retornoVerificaComerciante = null;
				return false;
			}else{
				alert('Tudo Certo com o Form!');
			}
		}
	}catch($e){
		alert('Erro na validação do cadastro!');
	}
}

$(document).ready(function(){
	indexGeral();
});
<|endoftext|>


<commit_before>$(function(){

//    $('body').tubular({videoId: '_A3i2KorZCk'}); // where idOfYourVideo is the YouTube ID.

	$("#datepicker").datepicker({
		//showButtonPanel: "true"
		onSelect: function(){
			var selectedDate = $("#datepicker").datepicker({dateFormat: 'yy-mm-dd'}).val();
			console.log(selectedDate);
		}
	});
	$("#date").datepicker();
	$(".taskCal").datepicker({
		onSelect: function(){
			var selectedDate = $("#datepicker").datepicker({dateFormat: 'yy-mm-dd'}).val();
			//console.log(selectedDate);
		}
	});
	$(".title").width($("#box").width());

	$(document).on("click", "#create", function(){
		console.log("saveボタンが押された！");
		var t = $(this).parent().parent().find("#Avalue").val();
		var date = $(this).parent().parent().find(".taskCal").val();
		console.log(this);
		console.log(t);
		console.log(date);
		var dateArray = date.split("/");
		var Tdate = dateArray[2] + "-" + dateArray[0] + "-" + dateArray[1];
		var term = dateArray[0] + "/" + dateArray[1];
		console.log(Tdate);
		var data;
		if(t != "" && date != ""){
			var d = false;
			data = {'task' : t , 'date': Tdate};
			if($("li").size() > 0){
				$("li").each(function(){
					console.log($(this).text());
					console.log(t);
					if(t == $(this).text()){
						d = true;
					}
				});
			}
			if(!d){
				$("
" + t + "" + term + "
").prependTo("ul").hide().slideDown(900, function(){
					$(this).show();
				});
				if($("ul").height() >= 250){
					$("#box").css("overflow-y", "scroll");
				}
				//$("ul").prepend("
" + t + "
").hide();
				$("ul").append("
通信中...
");
				$.ajax({
				   type: "POST",
				   url: "add.php",
				   data: data,
				   success: function(){
				     $('#tusin').remove();
				   }
				 });
				$(this).parent().parent().find("#Avalue").val("");
				$("#addTask").modal("toggle");
			}else{
				$("
違う名前を指定してください
").appendTo("#modal1").css("color", "red");
				$("#Avalue").focus(function(){
					$(".warning1").remove();
					$(this).select();
				}).on("click", function(){
					$(this).select();
				});
			}
		}
	});

	$(document).on("click", "li", function(){
		console.log("リストが選択された");
		var flag = $(this).hasClass("selected");
		if(!(flag)){
			$(this).css("color", "white");
			$(this).addClass("selected");
		}else{
			$(this).css("color", "black");
			$(this).removeClass("selected");
		}
	});

	var before_t = "";
	$("#edit").click(function(){
		console.log("editボタンが押された");
		var count = 0;
		var temp = "";
		$("li").each(function(){
			console.log(this);
			var flag = $(this).hasClass("selected");
			if(flag){
				temp = $(this).find(".task").text();
				console.log(this);
				console.log(temp);
				count++;
			}
		});
		if(count == 1){
			$("#editTask").modal("show");
			$("#Evalue").val(temp).focus(function(){
				$(this).select();
			}).on("click", function(){
				$(this).select();
			});

			$(document).on("click", "#change", function(){
				console.log("edit taskボタンが押された！");
				var t = $(this).parent().parent().find("#Evalue").val();
				console.log(this);
				console.log(t);
				var date = $(this).parent().parent().find(".taskCal").val();
				var dateArray = date.split("/");
				var Tdate = dateArray[2] + "-" + dateArray[0] + "-" + dateArray[1];
				var term = dateArray[0] + "/" + dateArray[1];
				console.log(Tdate);
				console.log(date);
				console.log(term);

				if(t != null && date != null){
						$(".selected").replaceWith("
" + t + "" + term + "
").show();
						$(this).parent().parent().find("#Evalue").val("");
						$("#editTask").modal("hide");
						$("ul").append("
通信中...
");
				$.ajax({
				   type: "POST",
				   url: "edit.php",
				   data: 'before=' + temp + '&after=' + t + "&date=" + date,
				   success: function(){
				     $('#tusin').remove();
				   }
				 });
				}
			});
		//	$(".selected").css("color", "black");
		//	$(".selected").removeClass("selected");
		}
	});

	$("#trash").click(function(){
		console.log("trashボタンが押された");
		var temp;
		var array = [];
		$("li").each(function(){
			console.log(this);
			var flag = $(this).hasClass("selected");
			if(flag){
				temp = $(this).find(".task").text();
				console.log(temp);
				array.push(temp);
				//console.log(array);
				$(this).hide(700, function(){
					$(this).remove();
				});
			}
		});
		if (array.length != 0) {
			$("ul").append("
通信中...
");
			console.log(array);
					$.ajax({
					   type: "POST",
					   url: "trash.php",
					   data: {'task' : array},
					   success: function(data){
					     $('#tusin').remove();
						 console.log(data);
					   }
					 });
			array = [];
		};
		if($("ul").height() >= 250){
			$("#box").css("overflow", "hidden");
		}
	});

	$("#achieve").click(function(){
		console.log("achieveボタンが押された");
		var temp = '';
		$("li").each(function(){
			console.log(this);
			var flag = $(this).hasClass("selected");
			temp = $(this).text();
			if(flag){
				$(this).hide(700, function(){
					$(this).remove();
					$("ul").append("
通信中...
");
					$.ajax({
					   type: "POST",
					   url: "achieve.php",
					   data: 'task=' + temp,
					   success: function(){
					     $('#tusin').remove();
					   }
					 });
				});
			}
		});
		if($("ul").height() >= 250){
			$("#box").css("overflow", "hidden");
		}
		if($(".boxSub").height() >= 250){
			$("#boxSub").css("overflow-y", "scroll");
		}
		$("#box").toggle(2000);
		$("#boxSub").toggle(2000);
	});
});<commit_msg>editchange<commit_after>$(function(){

//    $('body').tubular({videoId: '_A3i2KorZCk'}); // where idOfYourVideo is the YouTube ID.

	$("#datepicker").datepicker({
		//showButtonPanel: "true"
		onSelect: function(){
			var selectedDate = $("#datepicker").datepicker({dateFormat: 'yy-mm-dd'}).val();
			console.log(selectedDate);
		}
	});
	$("#date").datepicker();
	$(".taskCal").datepicker({
		onSelect: function(){
			var selectedDate = $("#datepicker").datepicker({dateFormat: 'yy-mm-dd'}).val();
			//console.log(selectedDate);
		}
	});
	$(".title").width($("#box").width());

	$(document).on("click", "#create", function(){
		console.log("saveボタンが押された！");
		var t = $(this).parent().parent().find("#Avalue").val();
		var date = $(this).parent().parent().find(".taskCal").val();
		console.log(this);
		console.log(t);
		console.log(date);
		var dateArray = date.split("/");
		var Tdate = dateArray[2] + "-" + dateArray[0] + "-" + dateArray[1];
		var term = dateArray[0] + "/" + dateArray[1];
		console.log(Tdate);
		var data;
		if(t != "" && date != ""){
			var d = false;
			data = {'task' : t , 'date': Tdate};
			if($("li").size() > 0){
				$("li").each(function(){
					console.log($(this).text());
					console.log(t);
					if(t == $(this).text()){
						d = true;
					}
				});
			}
			if(!d){
				$("
" + t + "" + term + "
").prependTo("ul").hide().slideDown(900, function(){
					$(this).show();
				});
				if($("ul").height() >= 250){
					$("#box").css("overflow-y", "scroll");
				}
				//$("ul").prepend("
" + t + "
").hide();
				$("ul").append("
通信中...
");
				$.ajax({
				   type: "POST",
				   url: "add.php",
				   data: data,
				   success: function(){
				     $('#tusin').remove();
				   }
				 });
				$(this).parent().parent().find("#Avalue").val("");
				$("#addTask").modal("toggle");
			}else{
				$("
違う名前を指定してください
").appendTo("#modal1").css("color", "red");
				$("#Avalue").focus(function(){
					$(".warning1").remove();
					$(this).select();
				}).on("click", function(){
					$(this).select();
				});
			}
		}
	});

	$(document).on("click", "li", function(){
		console.log("リストが選択された");
		var flag = $(this).hasClass("selected");
		if(!(flag)){
			$(this).css("color", "white");
			$(this).addClass("selected");
		}else{
			$(this).css("color", "black");
			$(this).removeClass("selected");
		}
	});

	var before_t = "";
	$("#edit").click(function(){
		console.log("editボタンが押された");
		var count = 0;
		var temp = "";
		var date;
		$("li").each(function(){
			console.log(this);
			var flag = $(this).hasClass("selected");
			if(flag){
				temp = $(this).find(".task").text();
				date = $(this).find(".term").text();
				console.log(date);
				console.log(temp);
				count++;
			}
		});
		if(count == 1){
			$("#editTask").modal("show");
			$("#Evalue").val(temp).focus(function(){
				$(this).select();
			}).on("click", function(){
				$(this).select();
			});
			$(".taskCal").val(date);

			$(document).on("click", "#change", function(){
				console.log("edit taskボタンが押された！");
				var t = $(this).parent().parent().find("#Evalue").val();
				console.log(this);
				console.log(t);
				var date = $(this).parent().parent().find(".taskCal").val();
				var dateArray = date.split("/");
				var Tdate = dateArray[2] + "-" + dateArray[0] + "-" + dateArray[1];
				var term = dateArray[0] + "/" + dateArray[1];
				console.log(Tdate);
				console.log(date);
				console.log(term);

				if(t != null && date != null){
						$(".selected").replaceWith("
" + t + "" + term + "
").show();
						$(this).parent().parent().find("#Evalue").val("");
						$("#editTask").modal("hide");
						$("ul").append("
通信中...
");
				$.ajax({
				   type: "POST",
				   url: "edit.php",
				   data: 'before=' + temp + '&after=' + t + "&date=" + date,
				   success: function(){
				     $('#tusin').remove();
				   }
				 });
				}
			});
		//	$(".selected").css("color", "black");
		//	$(".selected").removeClass("selected");
		}
	});

	$("#trash").click(function(){
		console.log("trashボタンが押された");
		var temp;
		var array = [];
		$("li").each(function(){
			console.log(this);
			var flag = $(this).hasClass("selected");
			if(flag){
				temp = $(this).find(".task").text();
				console.log(temp);
				array.push(temp);
				//console.log(array);
				$(this).hide(700, function(){
					$(this).remove();
				});
			}
		});
		if (array.length != 0) {
			$("ul").append("
通信中...
");
			console.log(array);
					$.ajax({
					   type: "POST",
					   url: "trash.php",
					   data: {'task' : array},
					   success: function(data){
					     $('#tusin').remove();
						 console.log(data);
					   }
					 });
			array = [];
		};
		if($("ul").height() >= 250){
			$("#box").css("overflow", "hidden");
		}
	});

	$("#achieve").click(function(){
		console.log("achieveボタンが押された");
		var temp = '';
		$("li").each(function(){
			console.log(this);
			var flag = $(this).hasClass("selected");
			temp = $(this).text();
			if(flag){
				$(this).hide(700, function(){
					$(this).remove();
					$("ul").append("
通信中...
");
					$.ajax({
					   type: "POST",
					   url: "achieve.php",
					   data: 'task=' + temp,
					   success: function(){
					     $('#tusin').remove();
					   }
					 });
				});
			}
		});
		if($("ul").height() >= 250){
			$("#box").css("overflow", "hidden");
		}
		if($(".boxSub").height() >= 250){
			$("#boxSub").css("overflow-y", "scroll");
		}
		$("#box").toggle(2000);
		$("#boxSub").toggle(2000);
	});
});<|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 = 960;
        var height = 540;
        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();
            for(var i= 0; i< canvas.width; i++){
                var rand = 2 - Math.floor((Math.random() * 3) + 1);
                c.fillStyle = "#000000";
                c.fillRect(i, height/2 + rand, 1, 1);
            }
        }

        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 = 0;
            var multiY = 0;
            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 - (levelSize/2);
            var prevY = height/2 - (levelSize/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 = 960;
        var height = 540;
        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();
            for(var i= 0; i< canvas.width; i++){
                var rand = 2 - Math.floor((Math.random() * 3) + 1);
                c.fillStyle = "#000000";
                c.fillRect(i, height/2 + rand, 1, 1);
            }
        }

        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 = 0;
            var multiY = 0;
            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.lineWidth = 10;
            c.rect(x,y,levelSize,levelSize);
            for(var i = 0; i< 3; i++){
                for(var j = 0; j< 3; j++){
                    c.lineWidth = 1;
                    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 - (levelSize/2);
            var prevY = height/2 - (levelSize/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>/*
 * Created 2014 Triangle717
 * <http://Triangle717.WordPress.com/>
 *
 * Licensed under The MIT License
 * <http://opensource.org/licenses/MIT/>
 */

function makeAnnouncement(message) {
  "use strict";
  /* Show announcement box */

  // Add the box to the page only if one does not exist already
  var announcementBox = '

';
  if (!$("body").find("#announcement").length >= 1) {
    $("body").append(announcementBox);

    // Add the message
    $("#announcement a").html(message);

    // Trigger the fade-in transitions
    $("#announcement").css("display", "block");
    $("#announcement").css("transform", "translate3d(0, 220px, 0)");
  }
}

function hideAnnouncement() {
  "use strict";
  /* Hide announcement box */
  $("#announcement").addClass("fadeout-ani");
}

function detectBrowser() {
  "use strict";
  /* Detect incompatible or unsupported browser
   * and display message to that extent.
   */

  var finalMessage, theBrowser, theBrowserMessage;

  // This is Safari 5 or lower
  if ($.browser.safari && $.browser.versionNumber <= 5) {
    theBrowser = "Safari";
    theBrowserMessage = "Your Safari version does not support my site. " +
    "Please visit browsehappy.com to research a modern browser.";

  } else if ($.browser.msie && $.browser.versionNumber <= 9) {
    // This is Internet Explorer 9 or lower
    theBrowser = "Internet Explorer";
    theBrowserMessage = "Your browser does not support my site. " +
    "Please visit browsehappy.com to research a modern browser.";

    // IE 9 does not like the text-shadow
    $("#announcement a").css("color", "black");

  } else if (!$.browser.chrome && !$.browser.mozilla &&
             !$.browser.msie&& !$.browser.opr && !$.browser.cros) {
    // Some other browser
    theBrowser = "an unidentified browser";
    theBrowserMessage = "Please submit an issue on GitHub with compatibility results. :)";
  }

//  else if ($.browser.mobile) {
  else if ($.browser.mobile || $.browser.desktop) {
    // Mobile browsers
    theBrowser = "a mobile browser";
    /* jshint ignore:start */
    theBrowserMessage = 'Triangle Land is not yet optimized for mobile browsing.';
    /* jshint ignore:end */
  }

  // Create final message
  finalMessage = 'You are using
{0}.
{1}'.format(theBrowser, theBrowserMessage);

  // Make the announcement if there is one to make
  if (theBrowser !== undefined) {
    makeAnnouncement(finalMessage);
  }
}

$(function() {
  "use strict";
  // Run process to detect visitor's browser
  detectBrowser();

  // Replace the SVG with a PNG on IE (IE HATES SVGs)
  if ($.browser.msie) {
    var $imgSrc = $(".loading-ani, .my-logo").attr("src");
    $(".loading-ani, .my-logo").attr("src", $imgSrc.substring(0, $imgSrc.length - 3) + "png");
  }

  // Hide text on mobile browsers until I can work on them
  if ($.browser.mobile) {
    $("#subpages").css("display", "none");
    $("#subsites").css("display", "none");
  }

  // Fully center the items that need centering
  var $centered = $(".fully-centered");
  $centered.css("margin-left", -$centered.width() / 2);
  $centered.css("margin-top", -$centered.height() / 2);

//  // Get date of last commit using GitHub Pages API
//  $.getJSON("https://api.github.com/repos/le717/le717.github.io", function(data) {
//      var lastUpdate = data.updated_at.replace(/(T(.*))$/g, "");
//      //var lastUpdate = "Right now";
//      $("#last-update").text("Last update: {0}".format(lastUpdate));
//    });
});
<commit_msg>[ci skip]<commit_after>/*
 * Created 2014 Triangle717
 * <http://Triangle717.WordPress.com/>
 *
 * Licensed under The MIT License
 * <http://opensource.org/licenses/MIT/>
 */

function makeAnnouncement(message) {
  "use strict";
  /* Show announcement box */

  // Add the box to the page only if one does not exist already
  var announcementBox = '

';
  if ($("body").find("#announcement").length !== 1) {
    $("body").append(announcementBox);

    // Add the message
    $("#announcement a").html(message);

    // Trigger the fade-in transitions
    $("#announcement").css("display", "block");
    $("#announcement").css("transform", "translate3d(0, 220px, 0)");
  }
}

function hideAnnouncement() {
  "use strict";
  /* Hide announcement box */
  $("#announcement").addClass("fadeout-ani");
}

function detectBrowser() {
  "use strict";
  /* Detect incompatible or unsupported browser
   * and display message to that extent.
   */

  var finalMessage, theBrowser, theBrowserMessage;

  // This is Safari 5 or lower
  if ($.browser.safari && $.browser.versionNumber <= 5) {
    theBrowser = "Safari";
    theBrowserMessage = "Your Safari version does not support my site. " +
    "Please visit browsehappy.com to research a modern browser.";

  } else if ($.browser.msie && $.browser.versionNumber <= 9) {
    // This is Internet Explorer 9 or lower
    theBrowser = "Internet Explorer";
    theBrowserMessage = "Your browser does not support my site. " +
    "Please visit browsehappy.com to research a modern browser.";

    // IE 9 does not like the text-shadow
    $("#announcement a").css("color", "black");

  } else if (!$.browser.chrome && !$.browser.mozilla &&
             !$.browser.msie&& !$.browser.opr && !$.browser.cros) {
    // Some other browser
    theBrowser = "an unidentified browser";
    theBrowserMessage = "Please submit an issue on GitHub with compatibility results. :)";
  }

//  else if ($.browser.mobile) {
  else if ($.browser.mobile || $.browser.desktop) {
    // Mobile browsers
    theBrowser = "a mobile browser";
    /* jshint ignore:start */
    theBrowserMessage = 'Triangle Land is not yet optimized for mobile browsing. :frowning:';
    /* jshint ignore:end */
  }

  // Create final message
  finalMessage = 'You are using
{0}.
{1}'.format(theBrowser, theBrowserMessage);

  // Make the announcement if there is one to make
  if (theBrowser !== undefined) {
    makeAnnouncement(finalMessage);
  }
}

$(function() {
  "use strict";
  // Run process to detect visitor's browser
  detectBrowser();

  // Replace the SVG with a PNG on IE (IE HATES SVGs)
  if ($.browser.msie) {
    var $imgSrc = $(".loading-ani, .my-logo").attr("src");
    $(".loading-ani, .my-logo").attr("src", $imgSrc.substring(0, $imgSrc.length - 3) + "png");
  }

  // Hide text on mobile browsers until I can work on them
  if ($.browser.mobile) {
    $("#subpages").css("display", "none");
    $("#subsites").css("display", "none");
  }

  // Fully center the items that need centering
  var $centered = $(".fully-centered");
  $centered.css("margin-left", -$centered.width() / 2);
  $centered.css("margin-top", -$centered.height() / 2);

//  // Get date of last commit using GitHub Pages API
//  $.getJSON("https://api.github.com/repos/le717/le717.github.io", function(data) {
//      var lastUpdate = data.updated_at.replace(/(T(.*))$/g, "");
//      //var lastUpdate = "Right now";
//      $("#last-update").text("Last update: {0}".format(lastUpdate));
//    });
});
<|endoftext|>


<commit_before>import {FefDebounceHelper} from '../classes/fef-debounce-helper';
import {FefResponsiveHelper} from '../classes/fef-responsive-helper';

const KEYCODES = {
    'escape': 27
};
const SUBNAV_CLASS = 'js-subnav-container',
    INNER_CONTAINER_CLASS = 'js-subnav-content',
    BUTTON_BACK_CLASS = 'js-subnav-button-back',
    BUTTON_FORWARD_CLASS = 'js-subnav-button-forward',
    BUTTON_ACTIVE_CLASS = 'subnav__pager--visible',
    MASK_LEFT_CLASS = 'js-subnav-mask-left',
    MASK_RIGHT_CLASS = 'js-subnav-mask-right',
    MASK_VISIBLE_CLASS = 'subnav__mask--visible',
    ITEM_ACTIVE_CLASS = 'js-active-subnav-item',
    ITEM_GROUP_CLASS = 'js-nav-group',
    ITEM_OPEN_GROUP_CLASS = 'js-nav-group-open',
    ITEM_GROUP_WRAPPER_CLASS = 'js-nav-group-wrapper',
    OUTSIDE_CLICK_LISTENER_NAME = 'click.nav-group touchstart.nav-group',
    OUTSIDE_KEYPRESS_LISTENER_NAME = 'keydown.nav-group',
    DEBOUNCETIME = 10,
    THROTTLETIME = 100,
    RIGHT_OFFSET = 24,
    BUTTON_BACK_THRESHOLD = 2,
    INNER_CONTAINER_SCROLL_PADDING = 84,
    ITEM_GROUP_MARGIN = 16,
    DEFAULT_SCROLL_TIME = 200;

export function init() {
    $(`.${SUBNAV_CLASS}`).each((index, element) => {
        new FefSubnav($(element));
    });
}

/**
 * This component handles the behaviour of the subnav, such as paging buttons and paging
 * functionality of a horizontally scrollable items list as well as the masks for
 * overflowing navigation items and 3rd-level navigation.
 */
export class FefSubnav {

    /**
     * @param $element jQuery element
     */
    constructor($element) {
        this.itemLeftPositions = new Array();
        this.itemRightPositions = new Array();
        this.$element = $element;
        this.$innerContainer = $(`.${INNER_CONTAINER_CLASS}`, this.$element);
        this.$buttonBack = $(`.${BUTTON_BACK_CLASS}`, this.$element);
        this.$buttonForward = $(`.${BUTTON_FORWARD_CLASS}`, this.$element);
        this.$maskLeft = $(`.${MASK_LEFT_CLASS}`, this.$element);
        this.$maskRight = $(`.${MASK_RIGHT_CLASS}`, this.$element);

        this.init();
        this.initItemPositions();
        this.registerListeners();

        // Immediately centering the nav bar doesn't work correctly - move to bottom of stack for correct results.
        setTimeout(() => {
            this.centerActiveItem();
        }, 0);
    }

    init() {
        this.updateButtonStatus();
        this.updateMaskStatus();
    }

    initItemPositions() {
        this.$innerContainer.children().each( (index, element) => {
            this.itemLeftPositions.push($(element).position().left);
            this.itemRightPositions.push($(element).position().left + $(element).innerWidth());
        });
    }

    onResize() {
        this.init();
        this.closeAllSubNavs();
    }

    registerListeners() {
        $(window).on('resize', FefDebounceHelper.debounce(() => this.onResize(), DEBOUNCETIME));
        this.$innerContainer.on('scroll', FefDebounceHelper.debounce(() => this.init(), DEBOUNCETIME));
        this.$innerContainer.on('scroll', FefDebounceHelper.throttle(() => this.closeAllSubNavs(), THROTTLETIME));
        this.$buttonBack.on('click', () => { this.pageBack(); });
        this.$buttonForward.on('click', () => { this.pageForward(); });

        this.$element.on('click', `.${ITEM_GROUP_CLASS}`, (e) => {
            if ($(e.target).parent().hasClass(ITEM_GROUP_CLASS)) {
                e.preventDefault();
                e.stopPropagation();
                this.toggleSubNav($(e.currentTarget));
            }
        });
    }

    closeAllSubNavs() {
        $(document).off(`${OUTSIDE_CLICK_LISTENER_NAME} ${OUTSIDE_KEYPRESS_LISTENER_NAME}`);
        let openNavs = this.$element.find(`.${ITEM_OPEN_GROUP_CLASS}`);

        openNavs.each((index, el) => this.closeSubNav($(el)));
    }

    /**
     * Close a subnav-group by fading it out and then setting the styles/classes etc.
     */
    closeSubNav($navItem) {
        let $wrapper = $navItem.find(`.${ITEM_GROUP_WRAPPER_CLASS}`);
        $navItem.find('.expand-icon').removeClass('expand-icon--open');

        this.$element.removeClass('subnav--open-3rd-level');

        $wrapper.animate({'opacity': 0}, 200, 'easeInOutCubic', () => {
            $navItem.removeClass(`${ITEM_OPEN_GROUP_CLASS} nav-group--open`);

            // reset previously applied styles
            $wrapper.css({'left': '', 'right': '', 'opacity': '', 'max-height': ''});
            $wrapper.find('.nav-group__list').width('');
        });
    }

    toggleSubNav($navItem) {
        let isClosing = $navItem.hasClass(ITEM_OPEN_GROUP_CLASS);

        this.closeAllSubNavs();

        if (isClosing) {
            return;
        }

        this.$element.addClass('subnav--open-3rd-level');

        // Listen to clicks outside of the element and Escape keypress --> close element
        $(document).on(OUTSIDE_CLICK_LISTENER_NAME, (e) => {
            this.closeAllSubNavs();
        }).on(OUTSIDE_KEYPRESS_LISTENER_NAME, (e) => {
            if(e.keyCode === KEYCODES.escape) {
                this.closeAllSubNavs();
            }
        });

        $navItem.addClass(`${ITEM_OPEN_GROUP_CLASS} nav-group--open`);
        $navItem.find('.expand-icon').addClass('expand-icon--open');

        if (!FefResponsiveHelper.isSmartphone()) {
            this.positionAndStretchSubNavGroup($navItem);
        } else {
            // Mobile: don't let the nav-group be taller than the space under the masthead. Make it scrollable and set a max-height to guarantee it.
            $navItem.find(`.${ITEM_GROUP_WRAPPER_CLASS}`).css({'max-height': `calc(100vh - ${$('.js-affix').outerHeight(true)}px)`});
        }
    }

    positionAndStretchSubNavGroup($navItem) {
        const $list = $navItem.find('.nav-group__list'),
            $listWrapper = $navItem.find(`.${ITEM_GROUP_WRAPPER_CLASS}`),
            navItemOffset = Math.max(ITEM_GROUP_MARGIN, $navItem.offset().left), // compensate for the 16px negative margin on the NavGroup
            listWidth = Math.max($navItem.outerWidth(), 200, $list.outerWidth());

        // If the parental nav item is wider than the list, make them the same size (compensate for margin)
        if ($navItem.outerWidth() + ITEM_GROUP_MARGIN > $list.outerWidth()) {
            $list.width($navItem.outerWidth() + ITEM_GROUP_MARGIN);
        }

        // if there's not enough space on the right side, align with the right side of the window
        if (navItemOffset + listWidth >= $(window).outerWidth()) {
            $listWrapper.css({'left': '', 'right': 0});
        } else {
            $listWrapper.css({'left': navItemOffset, 'right': ''});
        }
    }

    updateButtonStatus() {
        if (FefResponsiveHelper.isDesktop() || FefResponsiveHelper.isDesktopWide()) {
            // show forward button if needed
            if (this.isAtScrollEnd()) {
                this.$buttonForward.removeClass(BUTTON_ACTIVE_CLASS);
            } else if (this.hasScrollableOverflow()) {
                this.$buttonForward.addClass(BUTTON_ACTIVE_CLASS);
            } else {
                this.$buttonForward.removeClass(BUTTON_ACTIVE_CLASS);
            }

            // show back button if needed
            if (this.hasScrollableOverflow() && this.$innerContainer.scrollLeft() > BUTTON_BACK_THRESHOLD) {
                this.$buttonBack.addClass(BUTTON_ACTIVE_CLASS);
            } else {
                this.$buttonBack.removeClass(BUTTON_ACTIVE_CLASS);
            }
        }
    }

    updateMaskStatus() {
        if (FefResponsiveHelper.isSmartphone() || FefResponsiveHelper.isTablet()) {
            // show right mask if needed
            if (this.isAtScrollEnd()) {
                this.$maskRight.removeClass(MASK_VISIBLE_CLASS);
            } else if (this.hasScrollableOverflow()) {
                this.$maskRight.addClass(MASK_VISIBLE_CLASS);
            } else {
                this.$maskRight.removeClass(MASK_VISIBLE_CLASS);
            }

            // show left mask if needed
            if (this.hasScrollableOverflow() && this.$innerContainer.scrollLeft() > BUTTON_BACK_THRESHOLD) {
                this.$maskLeft.addClass(MASK_VISIBLE_CLASS);
            } else {
                this.$maskLeft.removeClass(MASK_VISIBLE_CLASS);
            }
        }
    }

    pageForward() {
        let visibleAreaRightEdge = this.$innerContainer.scrollLeft() + this.$innerContainer.innerWidth(),
            nextItem = this.itemRightPositions.findIndex(rightEdge => rightEdge > visibleAreaRightEdge),
            newPosition = this.itemLeftPositions[nextItem] - INNER_CONTAINER_SCROLL_PADDING;

        this.scrollToPosition(newPosition);
    }

    pageBack() {
        let visibleAreaLeftEdge = this.$innerContainer.scrollLeft() + INNER_CONTAINER_SCROLL_PADDING,
            nextItem = this.itemRightPositions.findIndex(rightEdge => rightEdge > visibleAreaLeftEdge),
            newPosition = this.itemLeftPositions[nextItem] - this.$innerContainer.innerWidth() + INNER_CONTAINER_SCROLL_PADDING;

        this.scrollToPosition(newPosition);
    }

    centerActiveItem() {
        let $active = $(`.${ITEM_ACTIVE_CLASS}`, this.$element);

        if ($active.length !== 1) {
            return;
        }

        let containerLeftEdge = this.$innerContainer.offset().left,
            containerMiddle = containerLeftEdge + .5 * this.$innerContainer.outerWidth(),
            activeLeftEdge = $active.offset().left,
            activeMiddle = activeLeftEdge + .5 * $active.outerWidth(),
            diff = activeMiddle - containerMiddle,
            currentScroll = this.$innerContainer.scrollLeft(),
            newScrollPos = currentScroll + diff;

        this.scrollToPosition(newScrollPos);
    }

    scrollToPosition(position, time) {
        time = typeof time === 'undefined' ? DEFAULT_SCROLL_TIME : time;

        this.$innerContainer
            .stop(true, false)
            .animate( { scrollLeft: position }, time);
    }

    hasScrollableOverflow() {
        return this.$innerContainer[0].scrollWidth > this.$innerContainer.innerWidth() + RIGHT_OFFSET;
    }

    isAtScrollEnd() {
        return this.$innerContainer.scrollLeft() + this.$innerContainer.innerWidth() >= this.$innerContainer[0].scrollWidth;
    }
}
<commit_msg>bugfix: Don't treat a click on a navItem as an "outside" click<commit_after>import {FefDebounceHelper} from '../classes/fef-debounce-helper';
import {FefResponsiveHelper} from '../classes/fef-responsive-helper';

const KEYCODES = {
    'escape': 27
};
const SUBNAV_CLASS = 'js-subnav-container',
    INNER_CONTAINER_CLASS = 'js-subnav-content',
    BUTTON_BACK_CLASS = 'js-subnav-button-back',
    BUTTON_FORWARD_CLASS = 'js-subnav-button-forward',
    BUTTON_ACTIVE_CLASS = 'subnav__pager--visible',
    MASK_LEFT_CLASS = 'js-subnav-mask-left',
    MASK_RIGHT_CLASS = 'js-subnav-mask-right',
    MASK_VISIBLE_CLASS = 'subnav__mask--visible',
    ITEM_ACTIVE_CLASS = 'js-active-subnav-item',
    ITEM_GROUP_CLASS = 'js-nav-group',
    ITEM_OPEN_GROUP_CLASS = 'js-nav-group-open',
    ITEM_GROUP_WRAPPER_CLASS = 'js-nav-group-wrapper',
    OUTSIDE_CLICK_LISTENER_NAME = 'click.nav-group touchstart.nav-group',
    OUTSIDE_KEYPRESS_LISTENER_NAME = 'keydown.nav-group',
    DEBOUNCETIME = 10,
    THROTTLETIME = 100,
    RIGHT_OFFSET = 24,
    BUTTON_BACK_THRESHOLD = 2,
    INNER_CONTAINER_SCROLL_PADDING = 84,
    ITEM_GROUP_MARGIN = 16,
    DEFAULT_SCROLL_TIME = 200;

export function init() {
    $(`.${SUBNAV_CLASS}`).each((index, element) => {
        new FefSubnav($(element));
    });
}

/**
 * This component handles the behaviour of the subnav, such as paging buttons and paging
 * functionality of a horizontally scrollable items list as well as the masks for
 * overflowing navigation items and 3rd-level navigation.
 */
export class FefSubnav {

    /**
     * @param $element jQuery element
     */
    constructor($element) {
        this.itemLeftPositions = new Array();
        this.itemRightPositions = new Array();
        this.$element = $element;
        this.$innerContainer = $(`.${INNER_CONTAINER_CLASS}`, this.$element);
        this.$buttonBack = $(`.${BUTTON_BACK_CLASS}`, this.$element);
        this.$buttonForward = $(`.${BUTTON_FORWARD_CLASS}`, this.$element);
        this.$maskLeft = $(`.${MASK_LEFT_CLASS}`, this.$element);
        this.$maskRight = $(`.${MASK_RIGHT_CLASS}`, this.$element);

        this.init();
        this.initItemPositions();
        this.registerListeners();

        // Immediately centering the nav bar doesn't work correctly - move to bottom of stack for correct results.
        setTimeout(() => {
            this.centerActiveItem();
        }, 0);
    }

    init() {
        this.updateButtonStatus();
        this.updateMaskStatus();
    }

    initItemPositions() {
        this.$innerContainer.children().each( (index, element) => {
            this.itemLeftPositions.push($(element).position().left);
            this.itemRightPositions.push($(element).position().left + $(element).innerWidth());
        });
    }

    onResize() {
        this.init();
        this.closeAllSubNavs();
    }

    registerListeners() {
        $(window).on('resize', FefDebounceHelper.debounce(() => this.onResize(), DEBOUNCETIME));
        this.$innerContainer.on('scroll', FefDebounceHelper.debounce(() => this.init(), DEBOUNCETIME));
        this.$innerContainer.on('scroll', FefDebounceHelper.throttle(() => this.closeAllSubNavs(), THROTTLETIME));
        this.$buttonBack.on('click', () => { this.pageBack(); });
        this.$buttonForward.on('click', () => { this.pageForward(); });

        this.$element.on('click', `.${ITEM_GROUP_CLASS}`, (e) => {
            if ($(e.target).parent().hasClass(ITEM_GROUP_CLASS)) {
                e.preventDefault();
                e.stopPropagation();
                this.toggleSubNav($(e.currentTarget));
            }
        });
    }

    closeAllSubNavs() {
        $(document).off(`${OUTSIDE_CLICK_LISTENER_NAME} ${OUTSIDE_KEYPRESS_LISTENER_NAME}`);
        let openNavs = this.$element.find(`.${ITEM_OPEN_GROUP_CLASS}`);

        openNavs.each((index, el) => this.closeSubNav($(el)));
    }

    /**
     * Close a subnav-group by fading it out and then setting the styles/classes etc.
     */
    closeSubNav($navItem) {
        let $wrapper = $navItem.find(`.${ITEM_GROUP_WRAPPER_CLASS}`);
        $navItem.find('.expand-icon').removeClass('expand-icon--open');

        this.$element.removeClass('subnav--open-3rd-level');

        $wrapper.animate({'opacity': 0}, 200, 'easeInOutCubic', () => {
            $navItem.removeClass(`${ITEM_OPEN_GROUP_CLASS} nav-group--open`);

            // reset previously applied styles
            $wrapper.css({'left': '', 'right': '', 'opacity': '', 'max-height': ''});
            $wrapper.find('.nav-group__list').width('');
        });
    }

    toggleSubNav($navItem) {
        let isClosing = $navItem.hasClass(ITEM_OPEN_GROUP_CLASS);

        this.closeAllSubNavs();

        if (isClosing) {
            return;
        }

        this.$element.addClass('subnav--open-3rd-level');

        // Listen to clicks outside of the element and Escape keypress --> close element
        $(document).on(OUTSIDE_CLICK_LISTENER_NAME, (e) => {
            if (!$(e.target).hasClass('nav-item')) {
                this.closeAllSubNavs();
            }
        }).on(OUTSIDE_KEYPRESS_LISTENER_NAME, (e) => {
            if(e.keyCode === KEYCODES.escape) {
                this.closeAllSubNavs();
            }
        });

        $navItem.addClass(`${ITEM_OPEN_GROUP_CLASS} nav-group--open`);
        $navItem.find('.expand-icon').addClass('expand-icon--open');

        if (!FefResponsiveHelper.isSmartphone()) {
            this.positionAndStretchSubNavGroup($navItem);
        } else {
            // Mobile: don't let the nav-group be taller than the space under the masthead. Make it scrollable and set a max-height to guarantee it.
            $navItem.find(`.${ITEM_GROUP_WRAPPER_CLASS}`).css({'max-height': `calc(100vh - ${$('.js-affix').outerHeight(true)}px)`});
        }
    }

    positionAndStretchSubNavGroup($navItem) {
        const $list = $navItem.find('.nav-group__list'),
            $listWrapper = $navItem.find(`.${ITEM_GROUP_WRAPPER_CLASS}`),
            navItemOffset = Math.max(ITEM_GROUP_MARGIN, $navItem.offset().left), // compensate for the 16px negative margin on the NavGroup
            listWidth = Math.max($navItem.outerWidth(), 200, $list.outerWidth());

        // If the parental nav item is wider than the list, make them the same size (compensate for margin)
        if ($navItem.outerWidth() + ITEM_GROUP_MARGIN > $list.outerWidth()) {
            $list.width($navItem.outerWidth() + ITEM_GROUP_MARGIN);
        }

        // if there's not enough space on the right side, align with the right side of the window
        if (navItemOffset + listWidth >= $(window).outerWidth()) {
            $listWrapper.css({'left': '', 'right': 0});
        } else {
            $listWrapper.css({'left': navItemOffset, 'right': ''});
        }
    }

    updateButtonStatus() {
        if (FefResponsiveHelper.isDesktop() || FefResponsiveHelper.isDesktopWide()) {
            // show forward button if needed
            if (this.isAtScrollEnd()) {
                this.$buttonForward.removeClass(BUTTON_ACTIVE_CLASS);
            } else if (this.hasScrollableOverflow()) {
                this.$buttonForward.addClass(BUTTON_ACTIVE_CLASS);
            } else {
                this.$buttonForward.removeClass(BUTTON_ACTIVE_CLASS);
            }

            // show back button if needed
            if (this.hasScrollableOverflow() && this.$innerContainer.scrollLeft() > BUTTON_BACK_THRESHOLD) {
                this.$buttonBack.addClass(BUTTON_ACTIVE_CLASS);
            } else {
                this.$buttonBack.removeClass(BUTTON_ACTIVE_CLASS);
            }
        }
    }

    updateMaskStatus() {
        if (FefResponsiveHelper.isSmartphone() || FefResponsiveHelper.isTablet()) {
            // show right mask if needed
            if (this.isAtScrollEnd()) {
                this.$maskRight.removeClass(MASK_VISIBLE_CLASS);
            } else if (this.hasScrollableOverflow()) {
                this.$maskRight.addClass(MASK_VISIBLE_CLASS);
            } else {
                this.$maskRight.removeClass(MASK_VISIBLE_CLASS);
            }

            // show left mask if needed
            if (this.hasScrollableOverflow() && this.$innerContainer.scrollLeft() > BUTTON_BACK_THRESHOLD) {
                this.$maskLeft.addClass(MASK_VISIBLE_CLASS);
            } else {
                this.$maskLeft.removeClass(MASK_VISIBLE_CLASS);
            }
        }
    }

    pageForward() {
        let visibleAreaRightEdge = this.$innerContainer.scrollLeft() + this.$innerContainer.innerWidth(),
            nextItem = this.itemRightPositions.findIndex(rightEdge => rightEdge > visibleAreaRightEdge),
            newPosition = this.itemLeftPositions[nextItem] - INNER_CONTAINER_SCROLL_PADDING;

        this.scrollToPosition(newPosition);
    }

    pageBack() {
        let visibleAreaLeftEdge = this.$innerContainer.scrollLeft() + INNER_CONTAINER_SCROLL_PADDING,
            nextItem = this.itemRightPositions.findIndex(rightEdge => rightEdge > visibleAreaLeftEdge),
            newPosition = this.itemLeftPositions[nextItem] - this.$innerContainer.innerWidth() + INNER_CONTAINER_SCROLL_PADDING;

        this.scrollToPosition(newPosition);
    }

    centerActiveItem() {
        let $active = $(`.${ITEM_ACTIVE_CLASS}`, this.$element);

        if ($active.length !== 1) {
            return;
        }

        let containerLeftEdge = this.$innerContainer.offset().left,
            containerMiddle = containerLeftEdge + .5 * this.$innerContainer.outerWidth(),
            activeLeftEdge = $active.offset().left,
            activeMiddle = activeLeftEdge + .5 * $active.outerWidth(),
            diff = activeMiddle - containerMiddle,
            currentScroll = this.$innerContainer.scrollLeft(),
            newScrollPos = currentScroll + diff;

        this.scrollToPosition(newScrollPos);
    }

    scrollToPosition(position, time) {
        time = typeof time === 'undefined' ? DEFAULT_SCROLL_TIME : time;

        this.$innerContainer
            .stop(true, false)
            .animate( { scrollLeft: position }, time);
    }

    hasScrollableOverflow() {
        return this.$innerContainer[0].scrollWidth > this.$innerContainer.innerWidth() + RIGHT_OFFSET;
    }

    isAtScrollEnd() {
        return this.$innerContainer.scrollLeft() + this.$innerContainer.innerWidth() >= this.$innerContainer[0].scrollWidth;
    }
}
<|endoftext|>


<commit_before>$(document).ready(function() {
  // variables
  var searchInput = $('#search-input'),
      urlResult = $('#url-result'),
      cursor = $('#cursor'),
      previewSearchLink = $('.preview-search-link');

  // display the current location for the shareable url
  urlResult.attr("value", window.location);
  // keep the shareable text selected
  urlResult.mouseup(function() {
    this.select()
  });
  // select the shareable url when they focus on it
  urlResult.focus(function() {
    this.select();
  });

  // get a cookie's value
  // http://stackoverflow.com/a/4825695/4013202
  function getCookie(c_name) {
    if (document.cookie.length > 0) {
      c_start = document.cookie.indexOf(c_name + "=");

      if (c_start != -1) {
        c_start = c_start + c_name.length + 1;
        c_end = document.cookie.indexOf(";", c_start);

        if (c_end == -1) {
          c_end = document.cookie.length;
        }
        return unescape(document.cookie.substring(c_start, c_end));
      }
    }
    return "";
  }

  if (getCookie('theme') == 'dark') {
    $('body').addClass('dark-theme').removeClass('light-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-dark-theme.png');
    $('#ddg-theme-url-param').attr("value", "d");
  }
  else if (getCookie('theme') == 'light') {
    $('body').addClass('light-theme').removeClass('dark-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-light-theme.png');
    $('#ddg-theme-url-param').attr("value", "-1");
  }

  // if they're giving the link to someone else
  if (window.location.search == "") {
    // make the shareable link display the URL in the address bar
    urlResult.attr("value", window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);

    // when they submit the search form
    $('#search-form').submit(function(event) {
      // don't do anything
      event.preventDefault();
      event.stopPropagation();

      // redirect
      window.location = urlResult.attr("value");

      return false;
    });

    // when they press a key
    searchInput.keyup(function(event) {
      var searchVal = $('#search-input').val();

      // make the link below the search bar show the right text and link to the right place
      urlResult.attr("value", window.location.protocol + "//" + window.location.host + window.location.pathname + "?q=" + encodeURIComponent(searchVal));

      // update the preview link
      previewSearchLink.attr("href", window.location.protocol + "//" + window.location.host + window.location.pathname + "?q=" + encodeURIComponent(searchVal));
    });
  }
  // if they're following a link someone else gave them
  else {
    // decode the user's search
    var urlDecoded = decodeURIComponent(window.location.search);

    // trim off everything but the search term
    if (urlDecoded.substr(0, 3) == "?q=") {
      // trim off the "?q=" part of the url
      urlDecoded = urlDecoded.substr(3);
    }

    if (urlDecoded.length > 0) {
      // show the default cursor
      cursor.show();
      cursor.attr("src", "img/cursor-default.png");

      // make sure the link shows the right text and links to the right place
      urlResult.text(window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);
      urlResult.attr("href", window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);

      if ($('body').width() > 650) {
        // animate the cursor down to the search bar
        cursor.animate({
          top: '20px',
          left: '400px'
        }, 2250);

        // change the cursor to the I-beam when over the search bar
        setTimeout(function() {
          cursor.attr("src", "img/cursor-text.png");
        }, 1500);

        // type the users search query
        searchInput.delay(2250).typetype(urlDecoded, {
          // when it finishes typing go click the submit button
          callback: function() {
            cursor.animate({
              top: '10px',
              left: '600px'
            }, 1000);

            // make it look like the submit button is being hovered
            setTimeout(function() {
              $('#search-submit').addClass("hovered");
            }, 800);

            // make the cursor look like it's able to click the submit button
            setTimeout(function() {
              cursor.attr("src", "img/cursor-pointer.png");
            }, 800);

            // simulate a click on the submit button
            setTimeout(function() {
              $('#search-submit').trigger("click");
              $('#search-submit').addClass("active");
            }, 1100);
          }
        });
      }
      else if ($('body').width() <= 650) {
        // animate the cursor down to the search bar
        cursor.animate({
          top: '16px',
          left: '200px'
        }, 1700);

        // change the cursor to an I-beam when over the search bar
        setTimeout(function() {
          cursor.attr("src", "img/cursor-text.png");
        }, 1100);

        // type the users search query
        searchInput.delay(2000).typetype(urlDecoded, {
          // when it finishes typing go click the submit button
          callback: function() {
            cursor.animate({
              top: '10px',
              left: '260px'
            }, 800);

            // make it look like the submit button is being hovered
            setTimeout(function() {
              $('#search-submit').addClass("hovered");
            }, 320);

            // make the cursor look like it's able to click the submit button
            setTimeout(function() {
              cursor.attr("src", "img/cursor-pointer.png");
            }, 320);

            // simulate a click on the submit button
            setTimeout(function() {
              $('#search-submit').trigger("click");
            }, 1000);
          }
        });
      }
    }
  }

  // focus on the input when they click in the search form
  $('#search-form').click(function() {
    $('#search-input').focus();
  });

  // give them the shortened url when they ask for it
  $('#shorten-url-result').click(function(event) {
    event.preventDefault();
    event.stopPropagation();

    var urlToShorten = "https://is.gd/create.php?format=json&url=" + encodeURIComponent(urlResult.attr("value")),
        shortenedURL;

    if (!shortenedURL) {
      $.getJSON(urlToShorten, function(data) {
        shortenedURL = data.shorturl;
        urlResult.attr("value", shortenedURL);
      });
    }
    else {
      urlResult.attr("value", shortenedURL);
    }
  });

  // switching themes
  $('#dark-theme-icon').click(function() {
    $('body').addClass('dark-theme').removeClass('light-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-dark-theme.png');
    $('#ddg-theme-url-param').attr("value", "d");

    document.cookie = 'theme=dark; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;';
  });

  $('#light-theme-icon').click(function() {
    $('body').addClass('light-theme').removeClass('dark-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-light-theme.png');
    $('#ddg-theme-url-param').attr("value", "-1");

    document.cookie = 'theme=light; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;';
  });
});<commit_msg>made result URL for is.gd use 'https'<commit_after>$(document).ready(function() {
  // variables
  var searchInput = $('#search-input'),
      urlResult = $('#url-result'),
      cursor = $('#cursor'),
      previewSearchLink = $('.preview-search-link');

  // display the current location for the shareable url
  urlResult.attr("value", window.location);
  // keep the shareable text selected
  urlResult.mouseup(function() {
    this.select()
  });
  // select the shareable url when they focus on it
  urlResult.focus(function() {
    this.select();
  });

  // get a cookie's value
  // http://stackoverflow.com/a/4825695/4013202
  function getCookie(c_name) {
    if (document.cookie.length > 0) {
      c_start = document.cookie.indexOf(c_name + "=");

      if (c_start != -1) {
        c_start = c_start + c_name.length + 1;
        c_end = document.cookie.indexOf(";", c_start);

        if (c_end == -1) {
          c_end = document.cookie.length;
        }
        return unescape(document.cookie.substring(c_start, c_end));
      }
    }
    return "";
  }

  if (getCookie('theme') == 'dark') {
    $('body').addClass('dark-theme').removeClass('light-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-dark-theme.png');
    $('#ddg-theme-url-param').attr("value", "d");
  }
  else if (getCookie('theme') == 'light') {
    $('body').addClass('light-theme').removeClass('dark-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-light-theme.png');
    $('#ddg-theme-url-param').attr("value", "-1");
  }

  // if they're giving the link to someone else
  if (window.location.search == "") {
    // make the shareable link display the URL in the address bar
    urlResult.attr("value", window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);

    // when they submit the search form
    $('#search-form').submit(function(event) {
      // don't do anything
      event.preventDefault();
      event.stopPropagation();

      // redirect
      window.location = urlResult.attr("value");

      return false;
    });

    // when they press a key
    searchInput.keyup(function(event) {
      var searchVal = $('#search-input').val();

      // make the link below the search bar show the right text and link to the right place
      urlResult.attr("value", window.location.protocol + "//" + window.location.host + window.location.pathname + "?q=" + encodeURIComponent(searchVal));

      // update the preview link
      previewSearchLink.attr("href", window.location.protocol + "//" + window.location.host + window.location.pathname + "?q=" + encodeURIComponent(searchVal));
    });
  }
  // if they're following a link someone else gave them
  else {
    // decode the user's search
    var urlDecoded = decodeURIComponent(window.location.search);

    // trim off everything but the search term
    if (urlDecoded.substr(0, 3) == "?q=") {
      // trim off the "?q=" part of the url
      urlDecoded = urlDecoded.substr(3);
    }

    if (urlDecoded.length > 0) {
      // show the default cursor
      cursor.show();
      cursor.attr("src", "img/cursor-default.png");

      // make sure the link shows the right text and links to the right place
      urlResult.text(window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);
      urlResult.attr("href", window.location.protocol + "//" + window.location.host + window.location.pathname + window.location.search);

      if ($('body').width() > 650) {
        // animate the cursor down to the search bar
        cursor.animate({
          top: '20px',
          left: '400px'
        }, 2250);

        // change the cursor to the I-beam when over the search bar
        setTimeout(function() {
          cursor.attr("src", "img/cursor-text.png");
        }, 1500);

        // type the users search query
        searchInput.delay(2250).typetype(urlDecoded, {
          // when it finishes typing go click the submit button
          callback: function() {
            cursor.animate({
              top: '10px',
              left: '600px'
            }, 1000);

            // make it look like the submit button is being hovered
            setTimeout(function() {
              $('#search-submit').addClass("hovered");
            }, 800);

            // make the cursor look like it's able to click the submit button
            setTimeout(function() {
              cursor.attr("src", "img/cursor-pointer.png");
            }, 800);

            // simulate a click on the submit button
            setTimeout(function() {
              $('#search-submit').trigger("click");
              $('#search-submit').addClass("active");
            }, 1100);
          }
        });
      }
      else if ($('body').width() <= 650) {
        // animate the cursor down to the search bar
        cursor.animate({
          top: '16px',
          left: '200px'
        }, 1700);

        // change the cursor to an I-beam when over the search bar
        setTimeout(function() {
          cursor.attr("src", "img/cursor-text.png");
        }, 1100);

        // type the users search query
        searchInput.delay(2000).typetype(urlDecoded, {
          // when it finishes typing go click the submit button
          callback: function() {
            cursor.animate({
              top: '10px',
              left: '260px'
            }, 800);

            // make it look like the submit button is being hovered
            setTimeout(function() {
              $('#search-submit').addClass("hovered");
            }, 320);

            // make the cursor look like it's able to click the submit button
            setTimeout(function() {
              cursor.attr("src", "img/cursor-pointer.png");
            }, 320);

            // simulate a click on the submit button
            setTimeout(function() {
              $('#search-submit').trigger("click");
            }, 1000);
          }
        });
      }
    }
  }

  // focus on the input when they click in the search form
  $('#search-form').click(function() {
    $('#search-input').focus();
  });

  // give them the shortened url when they ask for it
  $('#shorten-url-result').click(function(event) {
    event.preventDefault();
    event.stopPropagation();

    var urlToShorten = "https://is.gd/create.php?format=json&url=" + encodeURIComponent(urlResult.attr("value")),
        shortenedURL;

    if (!shortenedURL) {
      $.getJSON(urlToShorten, function(data) {
        shortenedURL = data.shorturl;
        shortenedURL = shortenedURL.replace("http:", "https:");
        urlResult.attr("value", shortenedURL);
      });
    }
    else {
      urlResult.attr("value", shortenedURL);
    }
  });

  // switching themes
  $('#dark-theme-icon').click(function() {
    $('body').addClass('dark-theme').removeClass('light-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-dark-theme.png');
    $('#ddg-theme-url-param').attr("value", "d");

    document.cookie = 'theme=dark; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;';
  });

  $('#light-theme-icon').click(function() {
    $('body').addClass('light-theme').removeClass('dark-theme');
    $('#ddg-logo').attr('src', 'img/ddg-logo-light-theme.png');
    $('#ddg-theme-url-param').attr("value", "-1");

    document.cookie = 'theme=light; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/;';
  });
});
<|endoftext|>


<commit_before>var TurndownService=function(){"use strict";function e(e,n){return Array(n+1).join(e)}var n=["address","article","aside","audio","blockquote","body","canvas","center","dd","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frameset","h1","h2","h3","h4","h5","h6","header","hgroup","hr","html","isindex","li","main","menu","nav","noframes","noscript","ol","output","p","pre","section","table","tbody","td","tfoot","th","thead","tr","ul"];function t(e){return-1!==n.indexOf(e.nodeName.toLowerCase())}var r=["area","base","br","col","command","embed","hr","img","input","keygen","link","meta","param","source","track","wbr"];function i(e){return-1!==r.indexOf(e.nodeName.toLowerCase())}var o=r.join();var a={};function l(e){for(var n in this.options=e,this._keep=[],this._remove=[],this.blankRule={replacement:e.blankReplacement},this.keepReplacement=e.keepReplacement,this.defaultRule={replacement:e.defaultReplacement},this.array=[],e.rules)this.array.push(e.rules[n])}function u(e,n,t){for(var r=0;r<e.length;r++){var i=e[r];if(c(i,n,t))return i}}function c(e,n,t){var r=e.filter;if("string"==typeof r){if(r===n.nodeName.toLowerCase())return!0}else if(Array.isArray(r)){if(r.indexOf(n.nodeName.toLowerCase())>-1)return!0}else{if("function"!=typeof r)throw new TypeError("`filter` needs to be a string, array, or function");if(r.call(e,n,t))return!0}}function s(e){var n=e.nextSibling||e.parentNode;return e.parentNode.removeChild(e),n}function f(e,n,t){return e&&e.parentNode===n||t(n)?n.nextSibling||n.parentNode:n.firstChild||n.nextSibling||n.parentNode}a.paragraph={filter:"p",replacement:function(e){return"\n\n"+e+"\n\n"}},a.lineBreak={filter:"br",replacement:function(e,n,t){return t.br+"\n"}},a.heading={filter:["h1","h2","h3","h4","h5","h6"],replacement:function(n,t,r){var i=Number(t.nodeName.charAt(1));return"setext"===r.headingStyle&&i<3?"\n\n"+n+"\n"+e(1===i?"=":"-",n.length)+"\n\n":"\n\n"+e("#",i)+" "+n+"\n\n"}},a.blockquote={filter:"blockquote",replacement:function(e){return"\n\n"+(e=(e=e.replace(/^\n+|\n+$/g,"")).replace(/^/gm,"> "))+"\n\n"}},a.list={filter:["ul","ol"],replacement:function(e,n){var t=n.parentNode;return"LI"===t.nodeName&&t.lastElementChild===n?"\n"+e:"\n\n"+e+"\n\n"}},a.listItem={filter:"li",replacement:function(e,n,t){e=e.replace(/^\n+/,"").replace(/\n+$/,"\n").replace(/\n/gm,"\n    ");var r=t.bulletListMarker+"   ",i=n.parentNode;if("OL"===i.nodeName){var o=i.getAttribute("start"),a=Array.prototype.indexOf.call(i.children,n);r=(o?Number(o)+a:a+1)+".  "}return r+e+(n.nextSibling&&!/\n$/.test(e)?"\n":"")}},a.indentedCodeBlock={filter:function(e,n){return"indented"===n.codeBlockStyle&&"PRE"===e.nodeName&&e.firstChild&&"CODE"===e.firstChild.nodeName},replacement:function(e,n,t){return"\n\n    "+n.firstChild.textContent.replace(/\n/g,"\n    ")+"\n\n"}},a.fencedCodeBlock={filter:function(e,n){return"fenced"===n.codeBlockStyle&&"PRE"===e.nodeName&&e.firstChild&&"CODE"===e.firstChild.nodeName},replacement:function(n,t,r){for(var i,o=((t.firstChild.className||"").match(/language-(\S+)/)||[null,""])[1],a=t.firstChild.textContent,l=r.fence.charAt(0),u=3,c=new RegExp("^"+l+"{3,}","gm");i=c.exec(a);)i[0].length>=u&&(u=i[0].length+1);var s=e(l,u);return"\n\n"+s+o+"\n"+a.replace(/\n$/,"")+"\n"+s+"\n\n"}},a.horizontalRule={filter:"hr",replacement:function(e,n,t){return"\n\n"+t.hr+"\n\n"}},a.inlineLink={filter:function(e,n){return"inlined"===n.linkStyle&&"A"===e.nodeName&&e.getAttribute("href")},replacement:function(e,n){return"["+e+"]("+n.getAttribute("href")+(n.title?' "'+n.title+'"':"")+")"}},a.referenceLink={filter:function(e,n){return"referenced"===n.linkStyle&&"A"===e.nodeName&&e.getAttribute("href")},replacement:function(e,n,t){var r,i,o=n.getAttribute("href"),a=n.title?' "'+n.title+'"':"";switch(t.linkReferenceStyle){case"collapsed":r="["+e+"][]",i="["+e+"]: "+o+a;break;case"shortcut":r="["+e+"]",i="["+e+"]: "+o+a;break;default:var l=this.references.length+1;r="["+e+"]["+l+"]",i="["+l+"]: "+o+a}return this.references.push(i),r},references:[],append:function(e){var n="";return this.references.length&&(n="\n\n"+this.references.join("\n")+"\n\n",this.references=[]),n}},a.emphasis={filter:["em","i"],replacement:function(e,n,t){return e.trim()?t.emDelimiter+e+t.emDelimiter:""}},a.strong={filter:["strong","b"],replacement:function(e,n,t){return e.trim()?t.strongDelimiter+e+t.strongDelimiter:""}},a.code={filter:function(e){var n=e.previousSibling||e.nextSibling,t="PRE"===e.parentNode.nodeName&&!n;return"CODE"===e.nodeName&&!t},replacement:function(e){if(!e.trim())return"";var n="`",t="",r="",i=e.match(/`+/gm);if(i)for(/^`/.test(e)&&(t=" "),/`$/.test(e)&&(r=" ");-1!==i.indexOf(n);)n+="`";return n+t+e+r+n}},a.image={filter:"img",replacement:function(e,n){var t=n.alt||"",r=n.getAttribute("src")||"",i=n.title||"";return r?"!["+t+"]("+r+(i?' "'+i+'"':"")+")":""}},l.prototype={add:function(e,n){this.array.unshift(n)},keep:function(e){this._keep.unshift({filter:e,replacement:this.keepReplacement})},remove:function(e){this._remove.unshift({filter:e,replacement:function(){return""}})},forNode:function(e){return e.isBlank?this.blankRule:(n=u(this.array,e,this.options))?n:(n=u(this._keep,e,this.options))?n:(n=u(this._remove,e,this.options))?n:this.defaultRule;var n},forEach:function(e){for(var n=0;n<this.array.length;n++)e(this.array[n],n)}};var d="undefined"!=typeof window?window:{};var p,h,m=function(){var e=d.DOMParser,n=!1;try{(new e).parseFromString("","text/html")&&(n=!0)}catch(e){}return n}()?d.DOMParser:(p=function(){},function(){var e=!1;try{document.implementation.createHTMLDocument("").open()}catch(n){window.ActiveXObject&&(e=!0)}return e}()?p.prototype.parseFromString=function(e){var n=new window.ActiveXObject("htmlfile");return n.designMode="on",n.open(),n.write(e),n.close(),n}:p.prototype.parseFromString=function(e){var n=document.implementation.createHTMLDocument("");return n.open(),n.write(e),n.close(),n},p);function g(e){var n;"string"==typeof e?n=(h=h||new m).parseFromString('<x-turndown id="turndown-root">'+e+"</x-turndown>","text/html").getElementById("turndown-root"):n=e.cloneNode(!0);return function(e){var n=e.element,t=e.isBlock,r=e.isVoid,i=e.isPre||function(e){return"PRE"===e.nodeName};if(n.firstChild&&!i(n)){for(var o=null,a=!1,l=null,u=f(l,n,i);u!==n;){if(3===u.nodeType||4===u.nodeType){var c=u.data.replace(/[ \r\n\t]+/g," ");if(o&&!/ $/.test(o.data)||a||" "!==c[0]||(c=c.substr(1)),!c){u=s(u);continue}u.data=c,o=u}else{if(1!==u.nodeType){u=s(u);continue}t(u)||"BR"===u.nodeName?(o&&(o.data=o.data.replace(/ $/,"")),o=null,a=!1):r(u)&&(o=null,a=!0)}var d=f(l,u,i);l=u,u=d}o&&(o.data=o.data.replace(/ $/,""),o.data||s(o))}}({element:n,isBlock:t,isVoid:i}),n}function v(e){return e.isBlock=t(e),e.isCode="code"===e.nodeName.toLowerCase()||e.parentNode.isCode,e.isBlank=function(e){return-1===["A","TH","TD","IFRAME","SCRIPT","AUDIO","VIDEO"].indexOf(e.nodeName)&&/^\s*$/i.test(e.textContent)&&!i(e)&&!function(e){return e.querySelector&&e.querySelector(o)}(e)}(e),e.flankingWhitespace=function(e){var n="",t="";if(!e.isBlock){var r=/^\s/.test(e.textContent),i=/\s$/.test(e.textContent),o=e.isBlank&&r&&i;r&&!y("left",e)&&(n=" "),o||!i||y("right",e)||(t=" ")}return{leading:n,trailing:t}}(e),e}function y(e,n){var r,i,o;return"left"===e?(r=n.previousSibling,i=/ $/):(r=n.nextSibling,i=/^ /),r&&(3===r.nodeType?o=i.test(r.nodeValue):1!==r.nodeType||t(r)||(o=i.test(r.textContent))),o}var k=Array.prototype.reduce,b=/^\n*/,w=/\n*$/,N=[[/\\/g,"\\\\"],[/\*/g,"\\*"],[/^-/g,"\\-"],[/^\+ /g,"\\+ "],[/^(=+)/g,"\\$1"],[/^(#{1,6}) /g,"\\$1 "],[/`/g,"\\`"],[/^~~~/g,"\\~~~"],[/\[/g,"\\["],[/\]/g,"\\]"],[/^>/g,"\\>"],[/_/g,"\\_"],[/^(\d+)\. /g,"$1\\. "]];function C(e){if(!(this instanceof C))return new C(e);var n={rules:a,headingStyle:"setext",hr:"* * *",bulletListMarker:"*",codeBlockStyle:"indented",fence:"```",emDelimiter:"_",strongDelimiter:"**",linkStyle:"inlined",linkReferenceStyle:"full",br:"  ",blankReplacement:function(e,n){return n.isBlock?"\n\n":""},keepReplacement:function(e,n){return n.isBlock?"\n\n"+n.outerHTML+"\n\n":n.outerHTML},defaultReplacement:function(e,n){return n.isBlock?"\n\n"+e+"\n\n":e}};this.options=function(e){for(var n=1;n<arguments.length;n++){var t=arguments[n];for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])}return e}({},n,e),this.rules=new l(this.options)}function x(e){var n=this;return k.call(e.childNodes,function(e,t){var r="";return 3===(t=new v(t)).nodeType?r=t.isCode?t.nodeValue:n.escape(t.nodeValue):1===t.nodeType&&(r=function(e){var n=this.rules.forNode(e),t=x.call(this,e),r=e.flankingWhitespace;(r.leading||r.trailing)&&(t=t.trim());return r.leading+n.replacement(t,e,this.options)+r.trailing}.call(n,t)),S(e,r)},"")}function S(e,n){var t,r,i,o=(t=n,r=[e.match(w)[0],t.match(b)[0]].sort(),(i=r[r.length-1]).length<2?i:"\n\n");return(e=e.replace(w,""))+o+(n=n.replace(b,""))}return C.prototype={turndown:function(e){if(!function(e){return null!=e&&("string"==typeof e||e.nodeType&&(1===e.nodeType||9===e.nodeType||11===e.nodeType))}(e))throw new TypeError(e+" is not a string, or an element/document/fragment node.");if(""===e)return"";var n=x.call(this,new g(e));return function(e){var n=this;return this.rules.forEach(function(t){"function"==typeof t.append&&(e=S(e,t.append(n.options)))}),e.replace(/^[\t\r\n]+/,"").replace(/[\t\r\n\s]+$/,"")}.call(this,n)},use:function(e){if(Array.isArray(e))for(var n=0;n<e.length;n++)this.use(e[n]);else{if("function"!=typeof e)throw new TypeError("plugin must be a Function or an Array of Functions");e(this)}return this},addRule:function(e,n){return this.rules.add(e,n),this},keep:function(e){return this.rules.keep(e),this},remove:function(e){return this.rules.remove(e),this},escape:function(e){return N.reduce(function(e,n){return e.replace(n[0],n[1])},e)}},C}();
(function(){

	const $ = (_q) => document.querySelectorAll(_q);
	const $v = (_q) => {
		const _$ = $(_q);
		const len = _$.length;
		if(!len)
		{
			return null;
		}
		const i = len - 1;
		return _$[i].text || _$[i].src || _$[i].href || _$[i].content
	};

	const DEBUG = window.markdownWebNoteDebug;

	const LINK = "//erikccoder.github.io/markdown-web-note/index.html";

	const turndownService = new TurndownService();

	const selection = window.getSelection();
	const author = $v('meta[name="author"], meta[name="twitter:creator"], meta[property="article:author"]');
	const description = selection.rangeCount
						? turndownService.turndown(selection.getRangeAt(0).cloneContents())
						: $v('meta[name="description"], meta[name="twitter:description"], meta[property="og:description"]');
	const image0 = $v('meta[name="twitter:image"], meta[property="og:image"]');
	const image = image0 ? image0 : $v('img');
	const keywords = $v('meta[name="keywords"]');
	const link = $v('link[rel="canonical"], meta[property="og:url"]') || window.location.href;
	const time = $v('meta[property="article:published_time"]');
	const title0 = $v('title, meta[name="twitter:title"], meta[property="og:title"]');
	const title = title0 ? title0.trim() : title0;
	const video = $v('meta[property="og:video"], meta[property="og:video:url"]');
	const tags = keywords
				 ?  '\n -' + keywords.replace(/,\ /g, ',').split(',').join('\n- ')
				 : null;

	const data = {
		link,
		author,
		image,
		time,
		title,
		video,
		tags
	};
	let str = `------\n`;
	Object.keys(data).forEach( k =>
	{
		if(data[k]) str += `${k}: ${data[k]}\n`
	});
	str += `------\n\n`;

	if(title){
		str += `# ${title}\n\n`;
	}
	if(description){
		str += `${description}\n\n`;
	}
	if(image){
		str += `![image](${image})\n\n`;
	}

	str += `${link}\n`;

	const markdown = encodeURIComponent(btoa(unescape(encodeURIComponent(str))));
	let fileName = location.pathname.replace(/\/$/g, '').split('/').pop() + '---' + location.hostname;

	setTimeout(()=>{
		location = DEBUG
					? `${LINK}?file=DEBUG&content=${markdown}`
					: `${LINK}?file=${fileName}&content=${markdown}`
	},0)

})()
<commit_msg>Update bookmarklet.js<commit_after>(function(){

	const $ = (_q) => document.querySelectorAll(_q);
	const $v = (_q) => {
		const _$ = $(_q);
		const len = _$.length;
		if(!len)
		{
			return null;
		}
		const i = len - 1;
		return _$[i].text || _$[i].src || _$[i].href || _$[i].content
	};

	const DEBUG = window.markdownWebNoteDebug;

	const LINK = "//erikccoder.github.io/markdown-web-note/index.html";

	let selection = window.getSelection();
	selection = selection.rangeCount ? selection.getRangeAt(0).cloneContents() : null;
	if(selection){
		const div = document.createElement('div')
		div.style.display = 'none';
		div.appendChild(selection);
		// document.body.appendChild(div);
		selection = div.innerHTML;
	}

	const author = $v('meta[name="author"], meta[name="twitter:creator"], meta[property="article:author"]');
	const description = $v('meta[name="description"], meta[name="twitter:description"], meta[property="og:description"]');
	const image0 = $v('meta[name="twitter:image"], meta[property="og:image"]');
	const image = image0 ? image0 : $v('img');
	const keywords = $v('meta[name="keywords"]');
	const link = $v('link[rel="canonical"], meta[property="og:url"]') || window.location.href;
	const time = $v('meta[property="article:published_time"]');
	const title0 = $v('title, meta[name="twitter:title"], meta[property="og:title"]');
	const title = title0 ? title0.trim() : title0;
	const video = $v('meta[property="og:video"], meta[property="og:video:url"]');
	const tags = keywords
				 ?  '\n- ' + keywords.replace(/,\ /g, ',').split(',').join('\n- ')
				 : null;

	let filename = DEBUG ? 'DEBUG' : location.pathname.replace(/\/$/g, '').split('/').pop() + '---' + location.hostname;

	const data = {
		link,
		author,
		image,
		time,
		title,
		video,
		tags,
		description,
		selection,
		filename
	};

	/*
	let str = `------\n`;
	Object.keys(data).forEach( k =>
	{
		if(data[k]) str += `${k}: ${data[k]}\n`
	});
	str += `------\n\n`;

	if(title){
		str += `# ${title}\n\n`;
	}
	if(description){
		str += `${description}\n\n`;
	}
	if(image){
		str += `![image](${image})\n\n`;
	}

	str += `${link}\n`;
	*/
	// const markdown = encodeURIComponent(btoa(unescape(encodeURIComponent(str))));

	const dataStr = JSON.stringify(data);
	const encoded = encodeURIComponent(dataStr);
	const b64 = encodeURIComponent(btoa(unescape(encoded)));
	// console.log(dataStr);
	// console.log(encoded);
	// console.log(b64);

	setTimeout(()=>{
		location = DEBUG
					? `http://localhost:8080?d=${b64}`
					: `${LINK}?d=${b64}`
	},0)

})()
<|endoftext|>