<commit_before>var app = angular.module("loklak", ['ngRoute']);
app.controller("status", function ($scope, $http) {
  $http.get("http://loklak.org/api/status.json").
    success(function (data, status, headers, config) {
      $scope.index = data.index;
    });
});

app.controller("search", function ($scope, $http) {
  $scope.query = '';
  $scope.results = [];
  $scope.search = function () {
    if ($scope.query != '') {
      $scope.results = [];
      $http.get("http://loklak.org/api/search.json?q=" + $scope.query).
        success(function (data, status, headers, config) {
          for (var i = 0; i < data.statuses.length; i++) {
            $scope.results.push(data.statuses[i].text);
          }
        });
    }
  }
});

app.filter("reverse", function () {
  return function (items) {
    if (!items || !items.length) {
      return;
    }
    return items.slice().reverse();
  };
});

angular.element(document).ready(function () {
  $(".menu-btn").click(function () {
    //$("#navSidebar").show();
  });
  var navString = "";
  var winLocation = window.location.href;
  $.getJSON("/cms/topmenu.json", function (data) {
    navItems = data.items;
    navItems = navItems.reverse();
    var count = 0;
    $.each( navItems, function (index, itemData) {
      name = Object.keys(itemData);
      link = itemData[name];
      // Now construct the li items
      liItem = "
";
      if (winLocation.indexOf(link) != -1 && count != 1) {
        liItem = "
";
        count = count + 1;
      }

        liItem += ""+name+"
";
      liItem = $(liItem);
      $('#navbar > ul').prepend(liItem);
    });
  });
  var lastScrollTop = $(window).scrollTop();
  var sidebarTop = $('.sidebar').position().top;
  $(window).scroll(function(event){
    var st = $(this).scrollTop();
    if (st <= 100){
      $('nav').animate({
        top: "0"
      }, 10);
      $('.sidebar').animate({
        top: sidebarTop
      }, 10);
    }
    else if(st > lastScrollTop && st > 100){
      $('nav').animate({
        top: "-20%"
      }, 5);
      $('.sidebar').animate({
        top: "-5%"
      }, 15);
    }
    lastScrollTop = st;
  });
});
<commit_msg>Updated<commit_after>var app = angular.module("loklak", ['ngRoute']);
app.controller("status", function ($scope, $http) {
  $http.get("http://loklak.org/api/status.json").
    success(function (data, status, headers, config) {
      $scope.index = data.index;
    });
});

app.controller("search", function ($scope, $http) {
  $scope.query = '';
  $scope.results = [];
  $scope.search = function () {
    if ($scope.query != '') {
      $scope.results = [];
      $http.get("http://loklak.org/api/search.json?q=" + $scope.query).
        success(function (data, status, headers, config) {
          for (var i = 0; i < data.statuses.length; i++) {
            $scope.results.push(data.statuses[i].text);
          }
        });
    }
  }
});

app.filter("reverse", function () {
  return function (items) {
    if (!items || !items.length) {
      return;
    }
    return items.slice().reverse();
  };
});

angular.element(document).ready(function () {
  $(".menu-btn").click(function () {
    //$("#navSidebar").show();
  });
  var navString = "";
  var winLocation = window.location.href;
  $.getJSON("/cms/topmenu.json", function (data) {
    navItems = data.items;
    navItems = navItems.reverse();
    var count = 0;
    $.each( navItems, function (index, itemData) {
      name = Object.keys(itemData);
      link = itemData[name];
      // Now construct the li items
      liItem = "
";
      if (winLocation.indexOf(link) != -1 && count != 1) {
        liItem = "
";
        count = count + 1;
      }

        liItem += ""+name+"
";
      liItem = $(liItem);
      $('#navbar > ul').prepend(liItem);
    });
  });
  var lastScrollTop = $(window).scrollTop();
  var sidebarTop = $('.sidebar').position().top;
  $(window).scroll(function(event){
    var st = $(this).scrollTop();
    if (st <= 100){
      $('nav').animate({
        top: "0"
      }, 10);
      $('.sidebar').animate({
        top: sidebarTop
      }, 10);
    }
    else if(st > lastScrollTop && st > 100){
      $('nav').animate({
        top: "-20%"
      }, 5);
      $('.sidebar').animate({
        top: "-5%"
      }, 20);
    }
    lastScrollTop = st;
  });
});
<|endoftext|>


<commit_before>module.exports = function () {
  return function (message) {
    return window.Notification.requestPermission().then(function (result) {
      if (result === 'granted') {
        let notification = new window.Notification(message)

        notification.onclick = function () {
          window.focus()
        }

        return notification
      }

      return Promise.reject(new Error('denied'))
    })
  }
}
<commit_msg>Remove var<commit_after>module.exports = function () {
  return function (message) {
    return window.Notification.requestPermission().then(function (result) {
      if (result === 'granted') {
        const notification = new window.Notification(message)

        notification.onclick = function () {
          window.focus()
        }

        return notification
      }

      return Promise.reject(new Error('denied'))
    })
  }
}
<|endoftext|>


<commit_before>const db = firebase.database();
const auth = firebase.auth();

function logout() {
  auth.signOut();
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return(false);
}

function haySesion() {
  auth.onAuthStateChanged(function (user) {
    if (user) { //si hay un usuario
      mostrarContador();
    }
    else {
      $(location).attr("href", "index.html");
    }
  });
}

haySesion();

function mostrarDatos() {
  let idPedido = getQueryVariable('id');
  let pedidoRef = db.ref('pedidoEntrada/'+idPedido);
  pedidoRef.on('value', function(snapshot) {
    let datos = snapshot.val();

    $('#numPedido').html("Pedido: " + idPedido);
    let diaCaptura = datos.encabezado.fechaCaptura.substr(0,2);
    let mesCaptura = datos.encabezado.fechaCaptura.substr(3,2);
    let añoCaptura = datos.encabezado.fechaCaptura.substr(6,4);
    let fechaCaptura = mesCaptura + '/' + diaCaptura + '/' + añoCaptura;
    moment.locale('es');
    let fechaCapturaMostrar = moment(fechaCaptura).format('LL');
    $('#fechaPedido').html("Recibido el "+fechaCapturaMostrar);
    $('#tienda').html('Tienda: ' + datos.encabezado.tienda);
    let detalle = datos.detalle;
    let trs = "";
    for(let producto in detalle) {
      trs += '
' +
              '' + detalle[producto].clave + '	' +
              '' + detalle[producto].nombre + '	' +
              '' + detalle[producto].degusPz + '	' +
              '' + detalle[producto].pedidoPz + '	' +
              '' + detalle[producto].totalPz + '	' +
              '' + detalle[producto].totalKg + '	' +
              '' + detalle[producto].precioUnitario + '	' +
              '' + detalle[producto].unidad + '	' +
              '' + detalle[producto].cambioFisico + '	' +
             '
';
    }

    $('#tbodyProductos').empty().append(trs);
  });
}

function mostrarNotificaciones() {
  let usuario = auth.currentUser.uid;
  let notificacionesRef = db.ref('notificaciones/almacen/'+usuario+'/lista');
  notificacionesRef.on('value', function(snapshot) {
    let lista = snapshot.val();
    let lis = "";

    let arrayNotificaciones = [];
    for(let notificacion in lista) {
      arrayNotificaciones.push(lista[notificacion]);
    }

    for(let i in arrayNotificaciones) {
      let date = arrayNotificaciones[i].fecha;
      moment.locale('es');
      let fecha = moment(date, "MMMM DD YYYY, HH:mm:ss").fromNow();

      lis += '
' +
               '' +
                '
' +
                  ' ' + arrayNotificaciones[i].mensaje +
                    ''+fecha+'' +
                '
' +
               '' +
             '
';
    }

    $('#contenedorNotificaciones').empty().append('
Notificaciones

');
    $('#contenedorNotificaciones').append(lis);
  });
}

function mostrarContador() {
  let uid = auth.currentUser.uid;
  let notificacionesRef = db.ref('notificaciones/almacen/'+uid);
  notificacionesRef.on('value', function(snapshot) {
    let cont = snapshot.val().cont;

    if(cont > 0) {
      $('#spanNotificaciones').html(cont).show();
    }
    else {
      $('#spanNotificaciones').hide();
    }
  });
}

function verNotificaciones() {
  let uid = auth.currentUser.uid;
  let notificacionesRef = db.ref('notificaciones/almacen/'+uid);
  notificacionesRef.update({cont: 0});
}

$('#campana').click(function() {
  verNotificaciones();
});

$(document).ready(function() {
  mostrarDatos();
  $('[data-toggle="tooltip"]').tooltip();
});

/*function generarPDF() {
  let pdf = new jsPDF('p', 'in', 'letter');

  var source = $('#panel')[0];
  var specialElementHandlers = {
    '#bypassme': function(element, renderer) {
    return true;
    }
  };

  pdf.fromHTML(
    source, // HTML string or DOM elem ref.
    0.5, // x coord
    0.5, // y coord
    {
    'width': 7.5, // max width of content on PDF
    'elementHandlers': specialElementHandlers
  });

  var string = pdf.output('datauristring');
  var iframe = ""
  var x = window.open();
  x.document.open();
  x.document.write(iframe);
  x.document.close();
}*/

function generarPDF() {
  let pdf = new jsPDF();
  pdf.fromHTML($('#panel').get(0), 10, 10, {'width': 180});
  //pdf.autoPrint();
  //pdf.output("dataurlnewwindow"); // this opens a new popup,  after this the PDF opens the print window view but there are browser inconsistencies with how this is handled

  var string = pdf.output('datauristring');
  var iframe = ""
  var x = window.open();
  x.document.open();
  x.document.write(iframe);
  x.document.close();
}
<commit_msg>Impresión de pedidos hijos<commit_after>const db = firebase.database();
const auth = firebase.auth();

function logout() {
  auth.signOut();
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if(pair[0] == variable){return pair[1];}
  }
  return(false);
}

function haySesion() {
  auth.onAuthStateChanged(function (user) {
    if (user) { //si hay un usuario
      mostrarContador();
    }
    else {
      $(location).attr("href", "index.html");
    }
  });
}

haySesion();

function mostrarDatos() {
  let idPedido = getQueryVariable('id');
  let pedidoRef = db.ref('pedidoEntrada/'+idPedido);
  pedidoRef.on('value', function(snapshot) {
    let datos = snapshot.val();

    $('#numPedido').html("Pedido: " + idPedido);
    let diaCaptura = datos.encabezado.fechaCaptura.substr(0,2);
    let mesCaptura = datos.encabezado.fechaCaptura.substr(3,2);
    let añoCaptura = datos.encabezado.fechaCaptura.substr(6,4);
    let fechaCaptura = mesCaptura + '/' + diaCaptura + '/' + añoCaptura;
    moment.locale('es');
    let fechaCapturaMostrar = moment(fechaCaptura).format('LL');
    $('#fechaPedido').html("Recibido el "+fechaCapturaMostrar);
    $('#tienda').html('Tienda: ' + datos.encabezado.tienda);
    let detalle = datos.detalle;
    let trs = "";
    for(let producto in detalle) {
      trs += '
' +
              '' + detalle[producto].clave + '	' +
              '' + detalle[producto].nombre + '	' +
              '' + detalle[producto].degusPz + '	' +
              '' + detalle[producto].pedidoPz + '	' +
              '' + detalle[producto].totalPz + '	' +
              '' + detalle[producto].totalKg + '	' +
              '' + detalle[producto].precioUnitario + '	' +
              '' + detalle[producto].unidad + '	' +
              '' + detalle[producto].cambioFisico + '	' +
             '
';
    }

    $('#tbodyProductos').empty().append(trs);
  });
}

function mostrarNotificaciones() {
  let usuario = auth.currentUser.uid;
  let notificacionesRef = db.ref('notificaciones/almacen/'+usuario+'/lista');
  notificacionesRef.on('value', function(snapshot) {
    let lista = snapshot.val();
    let lis = "";

    let arrayNotificaciones = [];
    for(let notificacion in lista) {
      arrayNotificaciones.push(lista[notificacion]);
    }

    for(let i in arrayNotificaciones) {
      let date = arrayNotificaciones[i].fecha;
      moment.locale('es');
      let fecha = moment(date, "MMMM DD YYYY, HH:mm:ss").fromNow();

      lis += '
' +
               '' +
                '
' +
                  ' ' + arrayNotificaciones[i].mensaje +
                    ''+fecha+'' +
                '
' +
               '' +
             '
';
    }

    $('#contenedorNotificaciones').empty().append('
Notificaciones

');
    $('#contenedorNotificaciones').append(lis);
  });
}

function mostrarContador() {
  let uid = auth.currentUser.uid;
  let notificacionesRef = db.ref('notificaciones/almacen/'+uid);
  notificacionesRef.on('value', function(snapshot) {
    let cont = snapshot.val().cont;

    if(cont > 0) {
      $('#spanNotificaciones').html(cont).show();
    }
    else {
      $('#spanNotificaciones').hide();
    }
  });
}

function verNotificaciones() {
  let uid = auth.currentUser.uid;
  let notificacionesRef = db.ref('notificaciones/almacen/'+uid);
  notificacionesRef.update({cont: 0});
}

$('#campana').click(function() {
  verNotificaciones();
});

$(document).ready(function() {
  mostrarDatos();
  $('[data-toggle="tooltip"]').tooltip();
});

function generarPDF(){
    let contenido= document.getElementById('panel').innerHTML;
    let contenidoOriginal= document.body.innerHTML;
    document.body.innerHTML = contenido;
    window.print();
    document.body.innerHTML = contenidoOriginal;
}<|endoftext|>


<commit_before>load();

var roles = new Array();
var roles_current_page = new Array();
var roles_counter = new Array();
var roles_cycle_proc = new Array();
var roles_pages = new Array();
var current_role_page = new Array();
var signed_in = new Array();

roles[0] = "staff";
roles[1] = "startup";
roles[2] = "visitor";

//people per page
peoplepp = 24;

//starting pages
for (i=0;i<roles.length;i++) {
	//Current page to append people to
	roles_current_page[roles[i]] = 0;
	//Roles counter
	roles_counter[roles[i]] = 0;
	//Roles Pages
	roles_pages[roles[i]] = 0;
	//Cycle process id
	roles_cycle_proc[roles[i]] = undefined;
	//role pages
	current_role_page[roles[i]] = 0;
}

var refresh_interval = 10000;

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

function load() {
	$.get('../staff/get_in_out.php', function(data) {
		process_data(data);
	})
	.fail(function() {
		$.get('staff/get_in_out.php', function(data) {
                	process_data(data);
	        })
	});
}

function reveal(id) {
	hide_all();
	$(id).show();
	$(id+"_nav").addClass("selected");
	window.location.hash = (id);
}
function hide_all() {
	for (i=0;i<roles.length;i++) {
		role = roles[i].trim();
		$('#'+role).hide();
		$('#'+role+'_nav').removeClass("selected");
	}
}

function switch_roles(inrole) {
	for (i=0;i<roles.length;i++) {
		role = roles[i].trim();
		$('#role_' + role).removeClass("role_selected");
	}
	$("#role_" + inrole).addClass("role_selected");
	id = $("input#person_id").val();
	$.post("../staff/staff_action.php", { "action": "role", "id": id, "role": inrole } );
//	$.post("staff/staff_action.php", { "action": "role", "id": id, "role": role } );
}

$(document).ready(function() {
        var hash = window.location.hash;
        if (hash) {
                reveal(hash);
        }
/*
	for (i=0;i<roles.length;i++) {
        	role = roles[i].trim();
		console.log("external + " + role);
		$("#"+role+"_nav").click(function () {
			reveal("#"+role);
        	});
        	$("#role_"+role).click(function () {
                	switch_roles(role);
        	});
	}
*/
		$("#staff_nav").click(function () {
			reveal("#staff");
        	});
        	$("#role_staff").click(function () {
                	switch_roles("staff");
        	});
		$("#visitor_nav").click(function () {
			reveal("#visitor");
        	});
        	$("#role_visitor").click(function () {
                	switch_roles("visitor");
        	});
		$("#startup_nav").click(function () {
			reveal("#startup");
        	});
        	$("#role_startup").click(function () {
                	switch_roles("startup");
        	});

});

function process_data(allText) {

        var allTextLines = allText.split(/\r\n|\n/);

	for (var i=0;i<allTextLines.length-1;i++) {
        	var entry = allTextLines[i].split(',');
		var id = entry[0];
		var email = entry[1];
		var firstname = entry[2];
		var lastname = entry[3];
		var role = entry[4];
		signin_person(id,firstname,lastname,email,role);
	}

	for (i=0;i<roles.length;i++) {
		role = roles[i].trim();
		append_roles_nav(role);
		roles_cycle_proc[role] = window.setInterval(function() {cycle_role(role)},refresh_interval);
	}
	console.log("proc visitor = " + roles_cycle_proc["visitor"] + " <end> ");
	console.log("proc staff = " + roles_cycle_proc["staff"] + " <end> ");
}

function signin_person(id,firstname,lastname,email,role) {
	if (role == "staff") {
		if ($('#'+id).length > 0) {
			$('#'+id).css('display','inline-block')
		} else {
			append_person(id,firstname,lastname,email,role);
		}
	} else {
		append_person(id,firstname,lastname,email,role);
	}
}

function append_person(id,firstname,lastname,email,role) {
	if (signed_in[email]) {
		return;
	}
	role = role.trim();
	roles_current_page[role] = 0;
	current_node = role + "_" + roles_current_page[roles[i]];
	//Cycle process id
	roles_cycle_proc[roles[i]] = undefined;
	if (roles_counter[role] == 0 || (roles_counter[role] % peoplepp) == 0) {
		current_node = role + "_" + roles_pages[role];
		if (roles_pages[role] < 1) {
			$('#' + role).append('

');
		} else {
			$('#' + role).append('

');
		}
		roles_pages[role]++;
	}
	current_node = role + "_" + (roles_pages[role] - 1);
	$('#' + current_node).append('
'+firstname + " " + lastname + '
');
	roles_counter[role]++;
	signed_in[email] = true;
}

function append_roles_nav(role) {
	role = role.trim();
	if (roles_pages[role] < 2) {
		return;
	} else {
		$('#'+role).append('

');
		for (i=0;i<roles_pages[role];i++) {
			show = i + 1;
			if (i == 0) {
				$('#'+role+'_pages').append('' + show + ' | ');
			} else {
				$('#'+role+'_pages').append('' + show + ' | ');
			}
		}
		$('#'+role+'_pages').append('>>');
	}
}

function cycle_role(role) {
	var next_page = current_role_page[role] + 1;
	if (next_page == roles_pages[role]) {
		next_page = 0;
	}
	$('#'+role+'_' + current_role_page[role]).fadeOut(function() {
		$('#'+role+'_pages_' + next_page).css('font-weight','bold');
		$('#'+role+'_pages_' + current_role_page[role]).css('font-weight','');
		$('#' + role + '_' + next_page).fadeIn(function() {
			current_role_page[role] = next_page;
		});
	});
}

function show_role_page(page,role) {
	role = role.trim();
	clearInterval(roles_cycle_proc[role]);
	roles_cycle_proc[role] = undefined;
	for (i=0;i<roles_counter[role];i++) {
		$('#' + role + '_pages_' + i).css('font-weight','');
		if ($('#' + role + '_' + i).css("opacity") == 1) {
			$('#' + role + '_' + i).fadeOut(function() {
				$('#' + role + '_pages_' + page).css('font-weight','bold');
				$('#' + role + '_' + page).fadeIn(function() {
					current_role_page[role] = page;
				});
			});
		}
	}
}

function reset_interval(role) {
	if (roles_cycle_proc[role] == undefined) {
		roles_cycle_proc[role] = window.setInterval(function() {cycle_role(role)},refresh_interval);
	}
}

<commit_msg>Tidying<commit_after>load();

var roles = new Array();
var roles_current_page = new Array();
var roles_counter = new Array();
var roles_cycle_proc = new Array();
var roles_pages = new Array();
var current_role_page = new Array();
var signed_in = new Array();

roles[0] = "staff";
roles[1] = "startup";
roles[2] = "visitor";

//people per page
peoplepp = 24;

//starting pages
for (i=0;i<roles.length;i++) {
	//Current page to append people to
	roles_current_page[roles[i]] = 0;
	//Roles counter
	roles_counter[roles[i]] = 0;
	//Roles Pages
	roles_pages[roles[i]] = 0;
	//Cycle process id
	roles_cycle_proc[roles[i]] = undefined;
	//role pages
	current_role_page[roles[i]] = 0;
}

var refresh_interval = 10000;

$.ajaxSetup ({
    // Disable caching of AJAX responses
    cache: false
});

function load() {
	$.get('../staff/get_in_out.php', function(data) {
		process_data(data);
	})
	.fail(function() {
		$.get('staff/get_in_out.php', function(data) {
                	process_data(data);
	        })
	});
}

function reveal(id) {
	hide_all();
	$(id).show();
	$(id+"_nav").addClass("selected");
	window.location.hash = (id);
}
function hide_all() {
	for (i=0;i<roles.length;i++) {
		role = roles[i].trim();
		$('#'+role).hide();
		$('#'+role+'_nav').removeClass("selected");
	}
}

function switch_roles(inrole) {
	for (i=0;i<roles.length;i++) {
		role = roles[i].trim();
		$('#role_' + role).removeClass("role_selected");
	}
	$("#role_" + inrole).addClass("role_selected");
	id = $("input#person_id").val();
	$.post("../staff/staff_action.php", { "action": "role", "id": id, "role": inrole } );
//	$.post("staff/staff_action.php", { "action": "role", "id": id, "role": role } );
}

$(document).ready(function() {
        var hash = window.location.hash;
        if (hash) {
                reveal(hash);
        }
/*
	FIXME
	for (i=0;i<roles.length;i++) {
        	role = roles[i].trim();
		console.log("external + " + role);
		$("#"+role+"_nav").click(function () {
			reveal("#"+role);
        	});
        	$("#role_"+role).click(function () {
                	switch_roles(role);
        	});
	}
*/
		$("#staff_nav").click(function () {
			reveal("#staff");
        	});
        	$("#role_staff").click(function () {
                	switch_roles("staff");
        	});
		$("#visitor_nav").click(function () {
			reveal("#visitor");
        	});
        	$("#role_visitor").click(function () {
                	switch_roles("visitor");
        	});
		$("#startup_nav").click(function () {
			reveal("#startup");
        	});
        	$("#role_startup").click(function () {
                	switch_roles("startup");
        	});

});

function process_data(allText) {

        var allTextLines = allText.split(/\r\n|\n/);

	for (var i=0;i<allTextLines.length-1;i++) {
        	var entry = allTextLines[i].split(',');
		var id = entry[0];
		var email = entry[1];
		var firstname = entry[2];
		var lastname = entry[3];
		var role = entry[4];
		signin_person(id,firstname,lastname,email,role);
	}

	for (i=0;i<roles.length;i++) {
		role = roles[i].trim();
		append_roles_nav(role);
		roles_cycle_proc[role] = window.setInterval(function() {cycle_role(role)},refresh_interval);
	}
	console.log("proc visitor = " + roles_cycle_proc["visitor"] + " <end> ");
	console.log("proc staff = " + roles_cycle_proc["staff"] + " <end> ");
}

function signin_person(id,firstname,lastname,email,role) {
	// The place to sort staff (optional)
	append_person(id,firstname,lastname,email,role);
}

function append_person(id,firstname,lastname,email,role) {
	if (signed_in[email]) {
		return;
	}
	role = role.trim();
	roles_current_page[role] = 0;
	current_node = role + "_" + roles_current_page[roles[i]];
	//Cycle process id
	roles_cycle_proc[roles[i]] = undefined;
	if (roles_counter[role] == 0 || (roles_counter[role] % peoplepp) == 0) {
		current_node = role + "_" + roles_pages[role];
		if (roles_pages[role] < 1) {
			$('#' + role).append('

');
		} else {
			$('#' + role).append('

');
		}
		roles_pages[role]++;
	}
	current_node = role + "_" + (roles_pages[role] - 1);
	$('#' + current_node).append('
'+firstname + " " + lastname + '
');
	roles_counter[role]++;
	signed_in[email] = true;
}

function append_roles_nav(role) {
	role = role.trim();
	if (roles_pages[role] < 2) {
		return;
	} else {
		$('#'+role).append('

');
		for (i=0;i<roles_pages[role];i++) {
			show = i + 1;
			if (i == 0) {
				$('#'+role+'_pages').append('' + show + ' | ');
			} else {
				$('#'+role+'_pages').append('' + show + ' | ');
			}
		}
		$('#'+role+'_pages').append('>>');
	}
}

function cycle_role(role) {
	var next_page = current_role_page[role] + 1;
	if (next_page == roles_pages[role]) {
		next_page = 0;
	}
	$('#'+role+'_' + current_role_page[role]).fadeOut(function() {
		$('#'+role+'_pages_' + next_page).css('font-weight','bold');
		$('#'+role+'_pages_' + current_role_page[role]).css('font-weight','');
		$('#' + role + '_' + next_page).fadeIn(function() {
			current_role_page[role] = next_page;
		});
	});
}

function show_role_page(page,role) {
	role = role.trim();
	clearInterval(roles_cycle_proc[role]);
	roles_cycle_proc[role] = undefined;
	for (i=0;i<roles_counter[role];i++) {
		$('#' + role + '_pages_' + i).css('font-weight','');
		if ($('#' + role + '_' + i).css("opacity") == 1) {
			$('#' + role + '_' + i).fadeOut(function() {
				$('#' + role + '_pages_' + page).css('font-weight','bold');
				$('#' + role + '_' + page).fadeIn(function() {
					current_role_page[role] = page;
				});
			});
		}
	}
}

function reset_interval(role) {
	if (roles_cycle_proc[role] == undefined) {
		roles_cycle_proc[role] = window.setInterval(function() {cycle_role(role)},refresh_interval);
	}
}

<|endoftext|>


<commit_before>const pi = 3.14159265359;
const bohr2ang = 0.529177249;

class PhononWebpage {

    constructor(visualizer, dispersion) {
        this.k = 0;
        this.n = 0;
        this.nx = 1;
        this.ny = 1;
        this.nz = 1;
        this.amplitude = 0.5;

        //select visualization
        this.visualizer = visualizer;

        //select dispersion
        this.dispersion = dispersion;

        //bind some functions (TODO: improve this)
        this.exportXSF    = exportXSF.bind(this);
        this.exportPOSCAR = exportPOSCAR.bind(this);
    }

    getRepetitions() {
        /*
        read the number of repetitions in each direction and update it
        */
        this.nx = $('#nx').val();
        this.ny = $('#ny').val();
        this.nz = $('#nz').val();
    }

    setRepetitions(repetitions) {
        /*
        set the number of repetitions on the interface
        */

        if (repetitions) {
            this.nx = repetitions[0];
            this.ny = repetitions[1];
            this.nz = repetitions[2];
        }

        $('#nx').val(this.nx);
        $('#ny').val(this.ny);
        $('#nz').val(this.nz);
    }

    loadCustomFile(event) {
        /*
        find the type of file and call the corresponding function to read it

        two formats available:
            phonopy files (band.yaml)
            internal .json format (*.json) description available in ./phononweb/phononweb.py
        */

        let yaml = null;
        let json = null;

        for (let i=0; i<event.target.files.length; i++) {
            let file = event.target.files[i];
            if (file.name.indexOf(".yaml") > -1) { yaml = file; }
            if (file.name.indexOf(".json") > -1) { json = file; }
        }

        this.phonon.name = "Custom file"
        if      (json) {
            this.phonon = new PhononJson();
            this.phonon.getFromFile(json, this.loadCallback.bind(this) );
        }
        else if (yaml) {
            this.phonon = new PhononYaml();
            this.phonon.getFromFile(yaml, this.loadCallback.bind(this) );
        }
        else {
            alert("Ivalid file");
        }
    }

    loadURL(url_vars) {
        /*
        load file from post request in the url

        two formats available:
            phonopy files (band.yaml)
            internal .json format (*.json) description available in ./phononweb/phononweb.py
        */

        function onReadJson(text) {
            this.phonon = new PhononJson();
            this.phonon.getFromJson(text, this.loadCallback.bind(this) );
        }

        function onReadYaml(text) {
            this.phonon = new PhononYaml();
            this.phonon.getFromString(text, this.loadCallback.bind(this) );
        }

        if (!("yaml" in url_vars) && !("json" in url_vars)) {
            alert("Ivalid url");
        }

        this.phonon.name = "Custom file";
        for (let key in url_vars) {
            if ( key == "yaml" ) { $.get(url_vars[key], onReadYaml.bind(this)); }
            if ( key == "json" ) { $.get(url_vars[key], onReadJson.bind(this)); }
            if ( key == "name" ) { $('#t1').html(url_vars[key]);     }
        }

    }

    loadId(id) {
        /*
        load a material from phonodb
        http://phonondb.mtl.kyoto-u.ac.jp
        */

        this.loadURL( { yaml: this.materials[id]['url'] } );
        this.phonon.name = this.materials[id]['name'] +  " mp-"+id+"";
        this.update();
    }

    loadLocal(folder='graphene') {
        /*
        read structure from a local file distributed with the repository
        */

        let readJson = function(string) {
            this.phonon = new PhononJson();
            this.phonon.getFromString(string, this.loadCallback.bind(this) );
        }

        $.get(folder+'/data.json', readJson.bind(this), "html" );
    }

    loadCallback() {
        /*
        Fuunction to be called once the file is loaded
        */
        this.setRepetitions(this.phonon.repetitions);
        this.update()
    }

    getStructure(nx,ny,nz) {
        let lat = this.phonon.lat;
        let apc = this.phonon.atom_pos_car;
        let atoms = [];

	    for (let ix=0;ix<nx;ix++) {
            for (let iy=0;iy<ny;iy++) {
                for (let iz=0;iz<nz;iz++) {
                    for (let i=0;i<this.phonon.natoms;i++) {

                        //postions of the atoms
                        let x = apc[i][0] + ix*lat[0][0] + iy*lat[1][0] + iz*lat[2][0];
                        let y = apc[i][1] + ix*lat[0][1] + iy*lat[1][1] + iz*lat[2][1];
                        let z = apc[i][2] + ix*lat[0][2] + iy*lat[1][2] + iz*lat[2][2];

                        atoms.push( [i,x,y,z] );
                    }
                }
            }
        }

        return atoms;
    }

    getBondingDistance() {
        /*
        replicate the atoms two times in each direction
        */
        let atoms = this.getStructure(2,2,2);

        let combinations = getCombinations( atoms );
        let min = 1e9;
        for (let i=0; i<combinations.length; i++ ) {
            let a = combinations[i][0];
            let b = combinations[i][1];

            let dist = distance(a.slice(1),b.slice(1));
            if (min > dist) {
                min = dist;
            }
        }
        return min;
    }

    getVibrations(nx,ny,nz) {
        /*
        Calculate the vibration patterns for all the atoms
        */
        let phonon = this.phonon;
        let veckn = phonon.vec[this.k][this.n];
        let vibrations = [];
        let kpt = phonon.kpoints[this.k];

        //additional phase if necessary
        let atom_phase = []
        if (phonon.addatomphase) {
            for (let i=0; i<phonon.natoms; i++) {
                let phase = kpt[0]*phonon.atom_pos_red[i][0] +
                        kpt[1]*phonon.atom_pos_red[i][1] +
                        kpt[2]*phonon.atom_pos_red[i][2];
                atom_phase.push(phase);
            }
        }
        else {
            for (let i=0; i<phonon.natoms; i++) {
                atom_phase.push(0);
            }
        }

        for (var ix=0; ix<nx; ix++) {
            for (var iy=0; iy<ny; iy++) {
                for (var iz=0; iz<nz; iz++) {

                    for (let i=0; i<phonon.natoms; i++) {
                        let sprod = kpt[0]*ix + kpt[1]*iy + kpt[2]*iz + atom_phase[i];
                        let phase = Complex.Polar(1.0,sprod*2.0*pi);

                        //Displacements of the atoms
                        let x = Complex(veckn[i][0][0],veckn[i][0][1]).mult(phase);
                        let y = Complex(veckn[i][1][0],veckn[i][1][1]).mult(phase);
                        let z = Complex(veckn[i][2][0],veckn[i][2][1]).mult(phase);

                        vibrations.push( [x,y,z] );
                    }
                }
            }
        }

        return vibrations;
    }

    setVibrations() {
        this.vibrations = this.getVibrations(this.nx,this.ny,this.nz);
    }

    updatePage() {
        /*
        lattice vectors table
        */

        for (let i=0; i<3; i++) {
            for (let j=0; j<3; j++) {
                //round lattice values
                $('#uc_'+i+j).html( this.phonon.lat[i][j].toPrecision(5) );
            }
        }

        //unit cell table
        $('#uc_natoms').html( this.phonon.natoms );
        $('#uc_atypes').html( this.phonon.formula );

        //atomic positions table
        let pos = this.phonon.atom_pos_red;
        $('#atompos').empty() //clean the atomic positions table
        for (let i=0; i<this.phonon.natoms; i++) {
            $('#atompos').append('

');
            $('#atompos tr:last').append(''+this.phonon.atom_types[i]+'	');
            for (let j=0; j<3; j++) {
                $('#atompos tr:last').append(''+pos[i][j].toFixed(4)+'	');
            }
        }

        //update title
        $('#t1').html(this.phonon.name);
    }

    update(dispersion=true) {
        /*
        Update all the aspects fo the webpage
        */

        //update structure
        this.getRepetitions();
        this.atoms = this.getStructure(this.nx,this.ny,this.nz);
        this.vibrations = this.getVibrations(this.nx,this.ny,this.nz);
        this.phonon.nndist = this.getBondingDistance();

        //update page
        this.updatePage();

        //update dispersion
        if (dispersion) { this.dispersion.update(this.phonon); }

        //update visualizer
        this.visualizer.update(this);
    }

    createPhonodbMenu(phonodb) {
        /*
        Create the phonondb menu
        */

        $("#div-phonodb").css('display', 'inline');
        let materials = jsyaml.load(phonodb);
        let materials_ref = {};
        $('#phonodb').empty();
        for (let i=0;i<materials.length;i++) {
            let material = materials[i];
            materials_ref[material['id']] = material;
            $('#phonodb').append('

');
            $('#phonodb li:last').append(""+material['name']+"");
        }

        this.materials = materials_ref;
    }

    updateMenu() {
        /*
        create menu with:
            local files (files distributed with the website)
            files from the phonodb database
        */

        //get a list of local materials
        $.getJSON('models.json', function(data) {
            let nmodels = data["nmodels"];
            let models  = data["models"];
            $('#mat').empty() //clean the atomic positions table

            for (let i=0; i<nmodels; i++) {
                $('#mat').append('

');
                $('#mat li:last').append(""+models[i]["name"]+"");
            }
        });

        //get a list of materials from phonodb
        $.get('phonondb.yaml', this.createPhonodbMenu.bind(this));
    }

    static getUrlVars() {
        /*
        get variables from the url
        from http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url

        currently the possible options are:
            json : load a json file from location
            yaml : load a yaml file from location
            name : change the display name of the material
        */
        let vars = {};
        let hash;

        if (location.search) {
            let hashes = location.search.slice(1).split('&');
            for(let i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars[hash[0]] = hash[1];
            }
            return vars;
        }
        else {
            return null;
        }
    }

}

$(document).ready(function() {

    //visualizer
    v = new VibCrystal($('#vibcrystal'));
    //dispersion
    d = new PhononHighcharts($('#highcharts'));
    //phonon class
    p = new PhononWebpage(v,d);

    /*
    check if its Chrome 1+ taken from
    http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
    only show webm button for chrome
    */
    let isChrome = !!window.chrome && !!window.chrome.webstore;
    if (!isChrome) {
        $('#webmbutton')[0].style.visibility = 'hidden';
    }

    //get if the draw vectors option is activated
    v.arrows = $('#drawvectors')[0].checked;
    $('#file-input')[0].addEventListener('change', p.loadCustomFile.bind(p), false);
    $('#file-input')[0].addEventListener('click', function() { this.value = '';}, false);
    p.updateMenu();

    let url_vars = PhononWebpage.getUrlVars();
    if (url_vars) { p.loadURL(url_vars); }
    else          { p.loadLocal();       }

    // check if webgl is available
    if ( ! Detector.webgl ) {
        Detector.addGetWebGLMessage();
    }

    //jquery to make an action once you change the number of repetitions
    $(".input-rep").keyup(function(event){
        if(event.keyCode == 13) p.update(dispersion=false);
    });

});
<commit_msg>Fixed a problem in loadURL<commit_after>const pi = 3.14159265359;
const bohr2ang = 0.529177249;

class PhononWebpage {

    constructor(visualizer, dispersion) {
        this.k = 0;
        this.n = 0;
        this.nx = 1;
        this.ny = 1;
        this.nz = 1;
        this.amplitude = 0.5;

        //select visualization
        this.visualizer = visualizer;

        //select dispersion
        this.dispersion = dispersion;

        //bind some functions (TODO: improve this)
        this.exportXSF    = exportXSF.bind(this);
        this.exportPOSCAR = exportPOSCAR.bind(this);
    }

    getRepetitions() {
        /*
        read the number of repetitions in each direction and update it
        */
        this.nx = $('#nx').val();
        this.ny = $('#ny').val();
        this.nz = $('#nz').val();
    }

    setRepetitions(repetitions) {
        /*
        set the number of repetitions on the interface
        */

        if (repetitions) {
            this.nx = repetitions[0];
            this.ny = repetitions[1];
            this.nz = repetitions[2];
        }

        $('#nx').val(this.nx);
        $('#ny').val(this.ny);
        $('#nz').val(this.nz);
    }

    loadCustomFile(event) {
        /*
        find the type of file and call the corresponding function to read it

        two formats available:
            phonopy files (band.yaml)
            internal .json format (*.json) description available in ./phononweb/phononweb.py
        */

        let yaml = null;
        let json = null;

        for (let i=0; i<event.target.files.length; i++) {
            let file = event.target.files[i];
            if (file.name.indexOf(".yaml") > -1) { yaml = file; }
            if (file.name.indexOf(".json") > -1) { json = file; }
        }

        this.phonon.name = "Custom file"
        if      (json) {
            this.phonon = new PhononJson();
            this.phonon.getFromFile(json, this.loadCallback.bind(this) );
        }
        else if (yaml) {
            this.phonon = new PhononYaml();
            this.phonon.getFromFile(yaml, this.loadCallback.bind(this) );
        }
        else {
            alert("Ivalid file");
        }
    }

    loadURL(url_vars) {
        /*
        load file from post request in the url

        two formats available:
            phonopy files (band.yaml)
            internal .json format (*.json) description available in ./phononweb/phononweb.py
        */

        function onReadJson(text) {
            this.phonon = new PhononJson();
            this.phonon.getFromJson(text, this.loadCallback.bind(this) );
        }

        function onReadYaml(text) {
            this.phonon = new PhononYaml();
            this.phonon.getFromString(text, this.loadCallback.bind(this) );
        }

        if (!("yaml" in url_vars) && !("json" in url_vars)) {
            alert("Ivalid url");
        }

        for (let key in url_vars) {
            if ( key == "yaml" ) { $.get(url_vars[key], onReadYaml.bind(this)); }
            if ( key == "json" ) { $.get(url_vars[key], onReadJson.bind(this)); }
            if ( key == "name" ) { $('#t1').html(url_vars[key]);     }
        }
        this.phonon.name = "Custom file";

    }

    loadId(id) {
        /*
        load a material from phonodb
        http://phonondb.mtl.kyoto-u.ac.jp
        */

        this.loadURL( { yaml: this.materials[id]['url'] } );
        this.phonon.name = this.materials[id]['name'] +  " mp-"+id+"";
        this.update();
    }

    loadLocal(folder='graphene') {
        /*
        read structure from a local file distributed with the repository
        */

        let readJson = function(string) {
            this.phonon = new PhononJson();
            this.phonon.getFromString(string, this.loadCallback.bind(this) );
        }

        $.get(folder+'/data.json', readJson.bind(this), "html" );
    }

    loadCallback() {
        /*
        Fuunction to be called once the file is loaded
        */
        this.setRepetitions(this.phonon.repetitions);
        this.update()
    }

    getStructure(nx,ny,nz) {
        let lat = this.phonon.lat;
        let apc = this.phonon.atom_pos_car;
        let atoms = [];

	    for (let ix=0;ix<nx;ix++) {
            for (let iy=0;iy<ny;iy++) {
                for (let iz=0;iz<nz;iz++) {
                    for (let i=0;i<this.phonon.natoms;i++) {

                        //postions of the atoms
                        let x = apc[i][0] + ix*lat[0][0] + iy*lat[1][0] + iz*lat[2][0];
                        let y = apc[i][1] + ix*lat[0][1] + iy*lat[1][1] + iz*lat[2][1];
                        let z = apc[i][2] + ix*lat[0][2] + iy*lat[1][2] + iz*lat[2][2];

                        atoms.push( [i,x,y,z] );
                    }
                }
            }
        }

        return atoms;
    }

    getBondingDistance() {
        /*
        replicate the atoms two times in each direction
        */
        let atoms = this.getStructure(2,2,2);

        let combinations = getCombinations( atoms );
        let min = 1e9;
        for (let i=0; i<combinations.length; i++ ) {
            let a = combinations[i][0];
            let b = combinations[i][1];

            let dist = distance(a.slice(1),b.slice(1));
            if (min > dist) {
                min = dist;
            }
        }
        return min;
    }

    getVibrations(nx,ny,nz) {
        /*
        Calculate the vibration patterns for all the atoms
        */
        let phonon = this.phonon;
        let veckn = phonon.vec[this.k][this.n];
        let vibrations = [];
        let kpt = phonon.kpoints[this.k];

        //additional phase if necessary
        let atom_phase = []
        if (phonon.addatomphase) {
            for (let i=0; i<phonon.natoms; i++) {
                let phase = kpt[0]*phonon.atom_pos_red[i][0] +
                        kpt[1]*phonon.atom_pos_red[i][1] +
                        kpt[2]*phonon.atom_pos_red[i][2];
                atom_phase.push(phase);
            }
        }
        else {
            for (let i=0; i<phonon.natoms; i++) {
                atom_phase.push(0);
            }
        }

        for (var ix=0; ix<nx; ix++) {
            for (var iy=0; iy<ny; iy++) {
                for (var iz=0; iz<nz; iz++) {

                    for (let i=0; i<phonon.natoms; i++) {
                        let sprod = kpt[0]*ix + kpt[1]*iy + kpt[2]*iz + atom_phase[i];
                        let phase = Complex.Polar(1.0,sprod*2.0*pi);

                        //Displacements of the atoms
                        let x = Complex(veckn[i][0][0],veckn[i][0][1]).mult(phase);
                        let y = Complex(veckn[i][1][0],veckn[i][1][1]).mult(phase);
                        let z = Complex(veckn[i][2][0],veckn[i][2][1]).mult(phase);

                        vibrations.push( [x,y,z] );
                    }
                }
            }
        }

        return vibrations;
    }

    setVibrations() {
        this.vibrations = this.getVibrations(this.nx,this.ny,this.nz);
    }

    updatePage() {
        /*
        lattice vectors table
        */

        for (let i=0; i<3; i++) {
            for (let j=0; j<3; j++) {
                //round lattice values
                $('#uc_'+i+j).html( this.phonon.lat[i][j].toPrecision(5) );
            }
        }

        //unit cell table
        $('#uc_natoms').html( this.phonon.natoms );
        $('#uc_atypes').html( this.phonon.formula );

        //atomic positions table
        let pos = this.phonon.atom_pos_red;
        $('#atompos').empty() //clean the atomic positions table
        for (let i=0; i<this.phonon.natoms; i++) {
            $('#atompos').append('

');
            $('#atompos tr:last').append(''+this.phonon.atom_types[i]+'	');
            for (let j=0; j<3; j++) {
                $('#atompos tr:last').append(''+pos[i][j].toFixed(4)+'	');
            }
        }

        //update title
        $('#t1').html(this.phonon.name);
    }

    update(dispersion=true) {
        /*
        Update all the aspects fo the webpage
        */

        //update structure
        this.getRepetitions();
        this.atoms = this.getStructure(this.nx,this.ny,this.nz);
        this.vibrations = this.getVibrations(this.nx,this.ny,this.nz);
        this.phonon.nndist = this.getBondingDistance();

        //update page
        this.updatePage();

        //update dispersion
        if (dispersion) { this.dispersion.update(this.phonon); }

        //update visualizer
        this.visualizer.update(this);
    }

    createPhonodbMenu(phonodb) {
        /*
        Create the phonondb menu
        */

        $("#div-phonodb").css('display', 'inline');
        let materials = jsyaml.load(phonodb);
        let materials_ref = {};
        $('#phonodb').empty();
        for (let i=0;i<materials.length;i++) {
            let material = materials[i];
            materials_ref[material['id']] = material;
            $('#phonodb').append('

');
            $('#phonodb li:last').append(""+material['name']+"");
        }

        this.materials = materials_ref;
    }

    updateMenu() {
        /*
        create menu with:
            local files (files distributed with the website)
            files from the phonodb database
        */

        //get a list of local materials
        $.getJSON('models.json', function(data) {
            let nmodels = data["nmodels"];
            let models  = data["models"];
            $('#mat').empty() //clean the atomic positions table

            for (let i=0; i<nmodels; i++) {
                $('#mat').append('

');
                $('#mat li:last').append(""+models[i]["name"]+"");
            }
        });

        //get a list of materials from phonodb
        $.get('phonondb.yaml', this.createPhonodbMenu.bind(this));
    }

    static getUrlVars() {
        /*
        get variables from the url
        from http://stackoverflow.com/questions/4656843/jquery-get-querystring-from-url

        currently the possible options are:
            json : load a json file from location
            yaml : load a yaml file from location
            name : change the display name of the material
        */
        let vars = {};
        let hash;

        if (location.search) {
            let hashes = location.search.slice(1).split('&');
            for(let i = 0; i < hashes.length; i++) {
                hash = hashes[i].split('=');
                vars[hash[0]] = hash[1];
            }
            return vars;
        }
        else {
            return null;
        }
    }

}

$(document).ready(function() {

    //visualizer
    v = new VibCrystal($('#vibcrystal'));
    //dispersion
    d = new PhononHighcharts($('#highcharts'));
    //phonon class
    p = new PhononWebpage(v,d);

    /*
    check if its Chrome 1+ taken from
    http://stackoverflow.com/questions/9847580/how-to-detect-safari-chrome-ie-firefox-and-opera-browser
    only show webm button for chrome
    */
    let isChrome = !!window.chrome && !!window.chrome.webstore;
    if (!isChrome) {
        $('#webmbutton')[0].style.visibility = 'hidden';
    }

    //get if the draw vectors option is activated
    v.arrows = $('#drawvectors')[0].checked;
    $('#file-input')[0].addEventListener('change', p.loadCustomFile.bind(p), false);
    $('#file-input')[0].addEventListener('click', function() { this.value = '';}, false);
    p.updateMenu();

    let url_vars = PhononWebpage.getUrlVars();
    if (url_vars) { p.loadURL(url_vars); }
    else          { p.loadLocal();       }

    // check if webgl is available
    if ( ! Detector.webgl ) {
        Detector.addGetWebGLMessage();
    }

    //jquery to make an action once you change the number of repetitions
    $(".input-rep").keyup(function(event){
        if(event.keyCode == 13) p.update(dispersion=false);
    });

});
<|endoftext|>


<commit_before>'use strict';
app.Router = Backbone.Router.extend({
  routes: {
    "": "home",
    "login": "openLoginModal",
    "register": "openRegisterModal",
    "profile": "openProfileModal",
    "me": "openProfileModal",
    "logout": "logout",
    "album/add": "addAlbum",
    "album/edit/:objectId": "editAlbum",
    "album/list": "listAlbums",
    "picture/upload": "uploadPicture",
    "picture/view/:objectId": "viewPicture",
  },

  markers: {},
  map: {},

  initialize: function () {
    $('header').html(new app.HeaderView().render().el);
    $('#main').html(new app.HomeView().render().el);
  },

  home: function() {
    $('#main').html(new app.HomeView().render().el);
  },

  uploadPicture: function() {
    if (app.CurrentUser.id) {
      $('#main').html(new app.PictureUploadView().render().el);
      var mapOptions = {
        zoom: 10,
        center: new google.maps.LatLng(42.6833333, 23.3166667)
      };
      var pictureUploadMap = new google.maps.Map(document.getElementById('pictureUploadMap'), mapOptions);
      this.activateMap(
        pictureUploadMap,
        'pictureUploadMarkers', {
          lat: 'input[name="location[lat]"]',
          lng: 'input[name="location[lng]"]',
          location_name: 'input[name="location[name]"]'
        },
        true
      );

      that.addSelctize('#pictureTags');
    }
  },

  viewPicture: function(objectId) {
    $('#main').html(new app.PictureViewView(objectId).render().el);
  },

  openLoginModal: function() {
    new app.LoginModal().render();
  },

  openProfileModal: function() {
    new app.ProfileModal().render();
  },

  openRegisterModal: function() {
    new app.RegisterModal().render();
  },

  clearMarkers: function(markers) {
    for (var i = 0; i < markers.length; i++ ) {
      markers[i].setMap(null);
    }
    markers.length = 0;
  },

  activateMap: function(map, markersKey, selectors, setLocationName) {
      var that = this;
      google.maps.event.addListener(map, "click", function (event) {

        if(that.markers[markersKey] !== undefined) {
          that.clearMarkers(that.markers[markersKey]);
        }

        var latitude = event.latLng.lat();
        var longitude = event.latLng.lng();
        var marker = new google.maps.Marker({
            position: event.latLng,
            map: map
        });

        $(selectors.lat).val(latitude);
        $(selectors.lng).val(longitude);

        if(setLocationName) {
          that.setLocationName(latitude, longitude, selectors.location_name);
        }

        if(that.markers[markersKey] === undefined) {
          that.markers[markersKey] = [];
        }

        that.markers[markersKey].push(marker);
    });
  },

  setLocationName: function(lat, lng, selector) {
    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        $(selector).val(results[2].formatted_address);
      }
    });
  },

  addAlbum: function() {
    if (app.CurrentUser.id) {
      $('#main').html(new app.AddAlbumView().render().el);

      var mapOptions = {
        zoom: 10,
        center: new google.maps.LatLng(42.6833333, 23.3166667)
      };

      var addAlbumMap = new google.maps.Map(document.getElementById('albumFormMap'), mapOptions);
      this.activateMap(
        addAlbumMap,
        'albumMapMarkers', {
          lat: 'input[name="albumLocationLat"]',
          lng: 'input[name="albumLocationLng"]',
          location_name: 'input[name="albumLocationName"]'
        },
        true
      );
    }

    that.addSelctize('#albumTags');
  },

  editAlbum: function(objectId) {
    var albumModel = new app.AlbumModel({id: objectId});
    var that = this;
    albumModel.fetch({
      success: function(data){
        var album = data.attributes;
        $('#main').html(new app.EditAlbumView().render(album).el);
        var mapOptions = {
          zoom: 10,
          center: new google.maps.LatLng(album.location.lat, album.location.lng)
        };

        var editAlbumMap = new google.maps.Map(document.getElementById('editAlbumFormMap'), mapOptions);
        that.activateMap(
          editAlbumMap,
          'editAlbumMapMarkers', {
            lat: 'input[name="albumLocationLat"]',
            lng: 'input[name="albumLocationLng"]',
            location_name: 'input[name="albumLocationName"]'
          },
          false
        );

        that.addSelctize('#albumTags');

        var latLng = new google.maps.LatLng(album.location.lat, album.location.lng);
        new google.maps.Marker({
            position: latLng,
            map: editAlbumMap
        });
      }
    });
  },

  addSelctize: function(selector) {
    $(selector).selectize({
        delimiter: ',',
        persist: false,
        create: function(input) {
            return {
                value: input,
                text: input
            }
        }
    });
  },

  logout: function() {
    app.CurrentUser.logout();
    Backbone.history.navigate("#", true);
    Backbone.trigger('flash', { message: 'Your are now logged out!', type: 'success' });
    this.home();
  }

});
<commit_msg>Sorry, that is not defined..<commit_after>'use strict';
app.Router = Backbone.Router.extend({
  routes: {
    "": "home",
    "login": "openLoginModal",
    "register": "openRegisterModal",
    "profile": "openProfileModal",
    "me": "openProfileModal",
    "logout": "logout",
    "album/add": "addAlbum",
    "album/edit/:objectId": "editAlbum",
    "album/list": "listAlbums",
    "picture/upload": "uploadPicture",
    "picture/view/:objectId": "viewPicture",
  },

  markers: {},
  map: {},

  initialize: function () {
    $('header').html(new app.HeaderView().render().el);
    $('#main').html(new app.HomeView().render().el);
  },

  home: function() {
    $('#main').html(new app.HomeView().render().el);
  },

  uploadPicture: function() {
    if (app.CurrentUser.id) {
      $('#main').html(new app.PictureUploadView().render().el);
      var mapOptions = {
        zoom: 10,
        center: new google.maps.LatLng(42.6833333, 23.3166667)
      };
      var pictureUploadMap = new google.maps.Map(document.getElementById('pictureUploadMap'), mapOptions);
      this.activateMap(
        pictureUploadMap,
        'pictureUploadMarkers', {
          lat: 'input[name="location[lat]"]',
          lng: 'input[name="location[lng]"]',
          location_name: 'input[name="location[name]"]'
        },
        true
      );

      this.addSelctize('#pictureTags');
    }
  },

  viewPicture: function(objectId) {
    $('#main').html(new app.PictureViewView(objectId).render().el);
  },

  openLoginModal: function() {
    new app.LoginModal().render();
  },

  openProfileModal: function() {
    new app.ProfileModal().render();
  },

  openRegisterModal: function() {
    new app.RegisterModal().render();
  },

  clearMarkers: function(markers) {
    for (var i = 0; i < markers.length; i++ ) {
      markers[i].setMap(null);
    }
    markers.length = 0;
  },

  activateMap: function(map, markersKey, selectors, setLocationName) {
      var that = this;
      google.maps.event.addListener(map, "click", function (event) {

        if(that.markers[markersKey] !== undefined) {
          that.clearMarkers(that.markers[markersKey]);
        }

        var latitude = event.latLng.lat();
        var longitude = event.latLng.lng();
        var marker = new google.maps.Marker({
            position: event.latLng,
            map: map
        });

        $(selectors.lat).val(latitude);
        $(selectors.lng).val(longitude);

        if(setLocationName) {
          that.setLocationName(latitude, longitude, selectors.location_name);
        }

        if(that.markers[markersKey] === undefined) {
          that.markers[markersKey] = [];
        }

        that.markers[markersKey].push(marker);
    });
  },

  setLocationName: function(lat, lng, selector) {
    var geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({'latLng': latlng}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        $(selector).val(results[2].formatted_address);
      }
    });
  },

  addAlbum: function() {
    if (app.CurrentUser.id) {
      $('#main').html(new app.AddAlbumView().render().el);

      var mapOptions = {
        zoom: 10,
        center: new google.maps.LatLng(42.6833333, 23.3166667)
      };

      var addAlbumMap = new google.maps.Map(document.getElementById('albumFormMap'), mapOptions);
      this.activateMap(
        addAlbumMap,
        'albumMapMarkers', {
          lat: 'input[name="albumLocationLat"]',
          lng: 'input[name="albumLocationLng"]',
          location_name: 'input[name="albumLocationName"]'
        },
        true
      );
    }

    this.addSelctize('#albumTags');
  },

  editAlbum: function(objectId) {
    var albumModel = new app.AlbumModel({id: objectId});
    var that = this;
    albumModel.fetch({
      success: function(data){
        var album = data.attributes;
        $('#main').html(new app.EditAlbumView().render(album).el);
        var mapOptions = {
          zoom: 10,
          center: new google.maps.LatLng(album.location.lat, album.location.lng)
        };

        var editAlbumMap = new google.maps.Map(document.getElementById('editAlbumFormMap'), mapOptions);
        that.activateMap(
          editAlbumMap,
          'editAlbumMapMarkers', {
            lat: 'input[name="albumLocationLat"]',
            lng: 'input[name="albumLocationLng"]',
            location_name: 'input[name="albumLocationName"]'
          },
          false
        );

        that.addSelctize('#albumTags');

        var latLng = new google.maps.LatLng(album.location.lat, album.location.lng);
        new google.maps.Marker({
            position: latLng,
            map: editAlbumMap
        });
      }
    });
  },

  addSelctize: function(selector) {
    $(selector).selectize({
        delimiter: ',',
        persist: false,
        create: function(input) {
            return {
                value: input,
                text: input
            }
        }
    });
  },

  logout: function() {
    app.CurrentUser.logout();
    Backbone.history.navigate("#", true);
    Backbone.trigger('flash', { message: 'Your are now logged out!', type: 'success' });
    this.home();
  }

});
<|endoftext|>


<commit_before>/* global google */
(function () {
	'use strict';

	var $routeOrigin = document.querySelector('#route-origin'),
		$routeDest   = document.querySelector('#route-dest'),
		$mapCanvas   = document.querySelector('#map-canvas');

	var map,
		directionsDisplay,
		directionsService = new google.maps.DirectionsService();

	function createMap() {
		var mapOptions = {
			zoom: 16,
			scrollwheel: false,

			// Unicamp
			center: new google.maps.LatLng(-22.8159666, -47.070069)
		};

		map = new google.maps.Map($mapCanvas, mapOptions);

		directionsDisplay = new google.maps.DirectionsRenderer();
		directionsDisplay.setMap(map);

		calculateRoute();
	}

	function calculateRoute() {
		var origin = $routeOrigin.value.split(','),
			dest   = $routeDest.value.split(',');

		var request = {
			origin: new google.maps.LatLng(parseFloat(origin[0], 10), parseFloat(origin[1], 10)),
			destination: new google.maps.LatLng(parseFloat(dest[0], 10), parseFloat(dest[1], 10)),
			travelMode: google.maps.TravelMode.WALKING
		};

		console.log(request);

		directionsService.route(request, function (response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setDirections(response);
			}
		});
	}

	google.maps.event.addDomListener(window, 'load', createMap);

	$routeOrigin.addEventListener('change', calculateRoute);
	$routeDest.addEventListener('change', calculateRoute);
})();<commit_msg>Fix linting errors<commit_after>/* global google */
(function () {
	'use strict';

	var $routeOrigin = document.querySelector('#route-origin'),
		$routeDest   = document.querySelector('#route-dest'),
		$mapCanvas   = document.querySelector('#map-canvas');

	var map,
		directionsDisplay,
		directionsService = new google.maps.DirectionsService();

	function createMap() {
		var mapOptions = {
			zoom: 16,
			scrollwheel: false,

			// Unicamp
			center: new google.maps.LatLng(-22.8159666, -47.070069),
		};

		map = new google.maps.Map($mapCanvas, mapOptions);

		directionsDisplay = new google.maps.DirectionsRenderer();
		directionsDisplay.setMap(map);

		calculateRoute();
	}

	function calculateRoute() {
		var origin = $routeOrigin.value.split(','),
			dest   = $routeDest.value.split(',');

		var request = {
			origin: new google.maps.LatLng(parseFloat(origin[0], 10), parseFloat(origin[1], 10)),
			destination: new google.maps.LatLng(parseFloat(dest[0], 10), parseFloat(dest[1], 10)),
			travelMode: google.maps.TravelMode.WALKING,
		};

		directionsService.route(request, function (response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setDirections(response);
			}
		});
	}

	google.maps.event.addDomListener(window, 'load', createMap);

	$routeOrigin.addEventListener('change', calculateRoute);
	$routeDest.addEventListener('change', calculateRoute);
})();<|endoftext|>


<commit_before>function Scene0() {
    var textMaterial = new THREE.MeshPhongMaterial({
        color: 0x00dddd,
        specular: 0xffffff,
        shininess: 100
    });
    var textGeom = new THREE.TextGeometry( 'rect.get();', {
        font: 'helvetiker',
        size: 10,
        height: 2
    });
    this.textMesh = new THREE.Mesh( textGeom, textMaterial );
    this._sceneTime = barCycle * 8; // scene active time in ms
    this.tempSpeed = 0;
    this.flag = 0.01;

    this.cameraDistance = 50;
    this.cameraAngle = 0;
};

Scene0.prototype.init = function() {
    camera = new THREE.PerspectiveCamera( 70, window.innerWidth/window.innerHeight, 0.1, 1000 );
    curThreeScene = new THREE.Scene();
    camera.position.z = 50;
    this.textMesh.position.x = -25;
    curThreeScene.add(this.textMesh);

    renderer.setClearColor(0x004444, 1);

    var pointLight = new THREE.PointLight( 0xffffff, 0.9)
    pointLight.position.set( 0, -5 , -5 );
    curThreeScene.add(pointLight);

    var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.9);
    directionalLight.position.set( 2, 2, 2 );
    curThreeScene.add(directionalLight);

    // postprocessing
    composer = new THREE.EffectComposer( renderer );
    composer.addPass( new THREE.RenderPass( curThreeScene, camera ) );

    this.rgbeffect = new THREE.ShaderPass( THREE.RGBShiftShader );
    this.rgbeffect.uniforms[ 'amount' ].value = 0.003;
    composer.addPass( this.rgbeffect );

    this.colorcorr = new THREE.ShaderPass( THREE.ColorCorrectionShader );
    //this.colorcorr.uniforms[ 'amount' ].value = 0.0015;
    composer.addPass( this.colorcorr );

    var vignette = new THREE.ShaderPass( THREE.VignetteShader );
    vignette.uniforms['darkness'].value = 1.5;
    vignette.uniforms['offset'].value = 0.5;
    vignette.renderToScreen = true;
    composer.addPass(vignette);
};

Scene0.prototype.deinit = function() {
    renderer.setClearColor(0x000000, 1);
};

Scene0.prototype.update = function(dt, t) {
    // Increment camera angle [0,PI]
    this.cameraAngle = Math.PI/2 + Math.cos(t / 1000) * Math.PI/3;

    // Camera spin around origin + bass
    camera.position.x = Math.cos(this.cameraAngle) * this.cameraDistance * (0.5 + 0.5* bass);
    camera.position.z = Math.sin(this.cameraAngle) * this.cameraDistance * (0.5 + 0.5* bass);
    camera.up = new THREE.Vector3(0,1,0);
    camera.lookAt( new THREE.Vector3(0, 0, 0) );

    // Bouncy text
    if (bass > 0.8 && this.tempSpeed == 0 && this.textMesh.position.y <= 0) {
        this.tempSpeed = 10;
        this.flag = 0;
    }
    if (this.tempSpeed > 0) {
        this.textMesh.position.y += 0.01 * this.tempSpeed;
        this.tempSpeed -= 1;
    }
    if (this.textMesh.position.y > 0 && this.tempSpeed == 0)
        this.textMesh.position.y -= 0.5;
};
<commit_msg>Scene0/ Done<commit_after>function Scene0() {
    var textMaterial2 = new THREE.MeshPhongMaterial({
        color: 0xff0011,
        specular: 0xffffff,
        shininess: 100
    });
    var textMaterial = new THREE.MeshPhongMaterial({
        color: 0x00dddd,
        specular: 0xffffff,
        shininess: 100
    });
    var textGet = new THREE.TextGeometry( 'get', {
        font: 'helvetiker',
        size: 10,
        height: 2
    });
    var textRekt = new THREE.TextGeometry( 'rekt', {
        font: 'helvetiker',
        size: 10,
        height: 2
    });
    var textCubed = new THREE.TextGeometry( 'cubed', {
        font: 'helvetiker',
        size: 10,
        height: 2
    });
    var textDOTted = new THREE.TextGeometry( 'DOTted', {
        font: 'helvetiker',
        size: 10,
        height: 2
    });

    var textLined = new THREE.TextGeometry( 'lined', {
        font: 'helvetiker',
        size: 10,
        height: 2
    });

    var textShaded = new THREE.TextGeometry( 'shaded', {
        font: 'helvetiker',
        size: 10,
        height: 2
    });

    this.textMesh1 = new THREE.Mesh( textGet, textMaterial );
    this.textMesh2 = new THREE.Mesh( textRekt, textMaterial2 );
    this.textMesh3 = new THREE.Mesh( textCubed, textMaterial );
    this.textMesh4 = new THREE.Mesh( textDOTted, textMaterial );
    this.textMesh5 = new THREE.Mesh( textLined, textMaterial );
    this.textMesh6 = new THREE.Mesh( textShaded, textMaterial );
    this._sceneTime = barCycle * 8; // scene active time in ms
    this.tempSpeed = 0;
    this.index = 0;

    this.cameraDistance = 75;
    this.cameraAngle = 0;
    this.beat = false;
};

Scene0.prototype.init = function() {
    camera = new THREE.PerspectiveCamera( 70, window.innerWidth/window.innerHeight, 0.1, 1000 );
    curThreeScene = new THREE.Scene();
    camera.position.z = 50;
    this.textMesh1.position.x = -25;
    curThreeScene.add(this.textMesh1);
    curThreeScene.add(this.textMesh2);
    curThreeScene.add(this.textMesh3);
    curThreeScene.add(this.textMesh4);
    curThreeScene.add(this.textMesh5);
    curThreeScene.add(this.textMesh6);

    this.textMesh2.visible = false;
    this.textMesh3.visible = false;
    this.textMesh4.visible = false;
    this.textMesh5.visible = false;
    this.textMesh6.visible = false;

    this.textArray = [];
    this.textArray.push(this.textMesh5);
    this.textArray.push(this.textMesh3);
    this.textArray.push(this.textMesh4);
    this.textArray.push(this.textMesh6);
    this.textArray.push(this.textMesh2);

    renderer.setClearColor(0x004444, 1);

    var pointLight = new THREE.PointLight( 0xffffff, 0.9)
    pointLight.position.set( 0, -5 , -5 );
    curThreeScene.add(pointLight);

    var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.9);
    directionalLight.position.set( 2, 2, 2 );
    curThreeScene.add(directionalLight);

    // postprocessing
    composer = new THREE.EffectComposer( renderer );
    composer.addPass( new THREE.RenderPass( curThreeScene, camera ) );

    this.rgbeffect = new THREE.ShaderPass( THREE.RGBShiftShader );
    this.rgbeffect.uniforms[ 'amount' ].value = 0.003;
    composer.addPass( this.rgbeffect );

    this.colorcorr = new THREE.ShaderPass( THREE.ColorCorrectionShader );
    //this.colorcorr.uniforms[ 'amount' ].value = 0.0015;
    composer.addPass( this.colorcorr );

    var vignette = new THREE.ShaderPass( THREE.VignetteShader );
    vignette.uniforms['darkness'].value = 1.5;
    vignette.uniforms['offset'].value = 0.5;
    vignette.renderToScreen = true;
    composer.addPass(vignette);
};

Scene0.prototype.deinit = function() {
    renderer.setClearColor(0x000000, 1);
};

Scene0.prototype.update = function(dt, t) {

    // Increment camera angle [0,PI]
    this.cameraAngle = Math.PI/2 + Math.cos(t / 1000) * Math.PI/6;

    // Every drum beat
    if (t % (barCycle / 2) < 350)
        this.textMesh1.visible = true;
    else
        this.textMesh1.visible = false;

    if (t % (barCycle / 2) < 100) {
        if (this.beat == false) {
            this.beat = true;
            this.textMesh2.visible = false;
            this.textMesh3.visible = false;
            this.textMesh4.visible = false;
            this.textMesh5.visible = false;
            this.textMesh6.visible = false;
            this.textArray[this.index].visible = true;
            this.index = (this.index + 1) % this.textArray.length;
        }
    }
    else {
        this.beat = false;
    }
    console.log(this.beat);

    // Camera spin around origin + bass
    camera.position.x = Math.cos(this.cameraAngle) * this.cameraDistance * (0.5 + 0.5* bass);
    camera.position.z = Math.sin(this.cameraAngle) * this.cameraDistance * (0.5 + 0.5* bass);
    camera.up = new THREE.Vector3(0,1,0);
    camera.lookAt( new THREE.Vector3(0, 0, 0) );

    // Bouncy text
    if (bass > 0.9 && this.tempSpeed == 0 && this.textMesh2.position.y <= 0)
        this.tempSpeed = 10;

    if (this.tempSpeed > 0) {
        this.textMesh2.position.y += 0.01 * this.tempSpeed;
        this.tempSpeed -= 1;
    }
    if (this.textMesh2.position.y > 0 && this.tempSpeed == 0)
        this.textMesh2.position.y -= 0.5;
};
<|endoftext|>


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

// Some global vars to improve performances
var selectedConversation = null;
var curPhoneNumber = null;

// Source: http://www.sitepoint.com/url-parameters-jquery/
$.urlParam = function(name){
	var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results == null) {
		return null;
	}
	else {
		return results[1] || 0;
	}
};

var refreshConversation = function() {
	alert(curPhoneNumber);
};

function fetchConversation(phoneNumber) {
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{'phoneNumber': phoneNumber},
		function(jsondata, status) {
			// Improve jQuery performance
			var conversationBuf = "";
			// Improve JS performance
			var msgClass = '';
			var unixDate = '';
			var formatedDate = '';
			var formatedHour = '00';
			var formatedMin = '00';
			var months = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.',
				'Oct.', 'Nov.', 'Dec.'];

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

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

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

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

				conversationBuf += '

' +
					vals["msg"] + '

' +
					formatedDate + '

';
				curPhoneNumber = phoneNumber;
			});

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

function changeSelectedConversation(item) {
	if (selectedConversation != null) {
		selectedConversation.parent().removeClass('selected');
	}
	selectedConversation = item;
	selectedConversation.parent().addClass('selected');
}

(function ($, OC) {
	$(document).ready(function () {
		// Now bind the events when we click on the phone number
		$.getJSON(OC.generateUrl('/apps/ocsms/get/peerlist'), function(jsondata, status) {
			// Use a buffer for better jQuery performance
			var peerListBuf = "";

			$.each(jsondata['phonelist'], function(id, val) {
				peerListBuf += '
' + val + '
';
			});

			$('#app-mailbox-peers ul').html(peerListBuf);

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

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

				var pObject = $("a[mailbox-navigation='" + urlPhoneNumber + "']");
				if (pObject != null) {
					changeSelectedConversation(pObject);
				}
			}
	     });
	     setInterval(refreshConversation, 10000);
	});

})(jQuery, OC);
<commit_msg>remove alert(). This function is valid<commit_after>/**
 * ownCloud - ocsms
 *
 * This file is licensed under the Affero General Public License version 3 or
 * later. See the COPYING file.
 *
 * @author Loic Blot <loic.blot@unix-experience.fr>
 * @copyright Loic Blot 2014
 */

// Some global vars to improve performances
var selectedConversation = null;
var curPhoneNumber = null;

// Source: http://www.sitepoint.com/url-parameters-jquery/
$.urlParam = function(name){
	var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
	if (results == null) {
		return null;
	}
	else {
		return results[1] || 0;
	}
};

var refreshConversation = function() {

};

function fetchConversation(phoneNumber) {
	$.getJSON(OC.generateUrl('/apps/ocsms/get/conversation'),
		{'phoneNumber': phoneNumber},
		function(jsondata, status) {
			// Improve jQuery performance
			var conversationBuf = "";
			// Improve JS performance
			var msgClass = '';
			var unixDate = '';
			var formatedDate = '';
			var formatedHour = '00';
			var formatedMin = '00';
			var months = ['Jan.', 'Feb.', 'Mar.', 'Apr.', 'May', 'Jun.', 'Jul.', 'Aug.', 'Sep.',
				'Oct.', 'Nov.', 'Dec.'];

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

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

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

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

				conversationBuf += '

' +
					vals["msg"] + '

' +
					formatedDate + '

';
				curPhoneNumber = phoneNumber;
			});

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

function changeSelectedConversation(item) {
	if (selectedConversation != null) {
		selectedConversation.parent().removeClass('selected');
	}
	selectedConversation = item;
	selectedConversation.parent().addClass('selected');
}

(function ($, OC) {
	$(document).ready(function () {
		// Now bind the events when we click on the phone number
		$.getJSON(OC.generateUrl('/apps/ocsms/get/peerlist'), function(jsondata, status) {
			// Use a buffer for better jQuery performance
			var peerListBuf = "";

			$.each(jsondata['phonelist'], function(id, val) {
				peerListBuf += '
' + val + '
';
			});

			$('#app-mailbox-peers ul').html(peerListBuf);

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

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

				var pObject = $("a[mailbox-navigation='" + urlPhoneNumber + "']");
				if (pObject != null) {
					changeSelectedConversation(pObject);
				}
			}
	     });
	     setInterval(refreshConversation, 10000);
	});

})(jQuery, OC);
<|endoftext|>


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

	$(window).scroll(function () {

   $('#slow').css({
      'top' : -($(this).scrollTop()/3)+"px",
      "background-color" : "red"
   });

});
		//snapping
	$('body').panelSnap();

	$(".carousel-caption").animate({
        marginLeft: "+=9999px",
    }, 1000 );

	//scroling menu
	var sections = $('section')
  	, nav = $('nav')
  	, nav_height = 100;
 	//nav.outerHeight()

$(window).on('scroll', function () {
  var cur_pos = $(this).scrollTop();
  sections.each(function() {

    var top = $(this).offset().top - nav_height,
        bottom = top + $(this).outerHeight();
		scolor = rgb2hex($(this).css("background-color"));
		iscolor = getContrast50(scolor);
		iiscolor = getContrast50(iscolor);

    if (cur_pos >= top && cur_pos <= bottom) {

		sections.removeClass('active');
		$(this).addClass('active');

		nav.find('a').parent().removeClass('active');
		nav.find('a[href="#'+$(this).attr('id')+'"]').parent().addClass('active');

		nav.find('a').css("color",iscolor);
		nav.find('a[href="#'+$(this).attr('id')+'"]').css("color",iiscolor);
    }
  });
});
			//menu_click_scroling
	nav.find('a').on("click", function(){
		event.preventDefault();

			$(".navbar-collapse").collapse('hide');//hides mobile menu

		id = $(this).attr("href");
		scrollToID(id, 800);
	});

});

function scrollToID(id, speed){
	var targetOffset = $(id).offset().top;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ?
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

function getContrast50(hexcolor){
    return (parseInt(hexcolor, 16) > 0xffffff/2) ? 'black':'white';
}

$(document).ready(function() {

	for (i=0; i<144; i++){
		$('#game > div')..wrapInner('

'+ i +'

');
	}
});
<commit_msg>.wrapInner<commit_after>$(document).ready(function() {

	$(window).scroll(function () {

   $('#slow').css({
      'top' : -($(this).scrollTop()/3)+"px",
      "background-color" : "red"
   });

});
		//snapping
	$('body').panelSnap();

	$(".carousel-caption").animate({
        marginLeft: "+=9999px",
    }, 1000 );

	//scroling menu
	var sections = $('section')
  	, nav = $('nav')
  	, nav_height = 100;
 	//nav.outerHeight()

$(window).on('scroll', function () {
  var cur_pos = $(this).scrollTop();
  sections.each(function() {

    var top = $(this).offset().top - nav_height,
        bottom = top + $(this).outerHeight();
		scolor = rgb2hex($(this).css("background-color"));
		iscolor = getContrast50(scolor);
		iiscolor = getContrast50(iscolor);

    if (cur_pos >= top && cur_pos <= bottom) {

		sections.removeClass('active');
		$(this).addClass('active');

		nav.find('a').parent().removeClass('active');
		nav.find('a[href="#'+$(this).attr('id')+'"]').parent().addClass('active');

		nav.find('a').css("color",iscolor);
		nav.find('a[href="#'+$(this).attr('id')+'"]').css("color",iiscolor);
    }
  });
});
			//menu_click_scroling
	nav.find('a').on("click", function(){
		event.preventDefault();

			$(".navbar-collapse").collapse('hide');//hides mobile menu

		id = $(this).attr("href");
		scrollToID(id, 800);
	});

});

function scrollToID(id, speed){
	var targetOffset = $(id).offset().top;
	$('html,body').animate({scrollTop:targetOffset}, speed);
}

function rgb2hex(rgb){
 rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
 return (rgb && rgb.length === 4) ?
  ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
  ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}

function getContrast50(hexcolor){
    return (parseInt(hexcolor, 16) > 0xffffff/2) ? 'black':'white';
}

$(document).ready(function() {

	for (i=0; i<144; i++){
		$('#game > div').wrapInner('

'+ i +'

');
	}
});
<|endoftext|>


<commit_before>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 01/07/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic-site

*/

var Webtwic = Webtwic || {};

var browser_name = bowser.name.toLowerCase();

var test_canvas = document.createElement( 'canvas' );
var canvascheck = ( test_canvas.getContext ) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: 'Webtwic',
	description: 'A community focused on code tweaks, articles and tutorials for newbie and professional developers.',
	repo: 'https://github.com/webtwic/webtwic-site',
	author: 'Olaolu Olawuyi',
	version: '1.0.0',

	// Start main functions for the object

	// Function to add browser name and version to body class
	showBrowser: function( b ) {
		b = (typeof b == 'undefined') ? browser_name : b.toLowerCase();
		if ( ! ( bowser.webkit ) )
			$( 'body' ).addClass( b + ' ' + b + parseInt( bowser.version ) );
		else
			$( 'body' ).addClass( 'webkit' + ' ' + b + ' ' + b + parseInt( bowser.version ) );
	},

	// Function to set attributes and values to elements
	setAttr: function( elem, name, val ) {
		$( elem, this ).attr( name, val );
	},

	// Function to push down .site-content
	adjustSiteContent: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).addClass( 'adjustedMargin' );
			$( '#header .logo' ).addClass( 'adjustedTop' );
			$( '.main-menu' ).addClass( 'adjustedMargin' );
			$( '#header' ).addClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.site-content' ).addClass( 'adjustSiteContent' );
			$( '.secondary-header' ).addClass( 'adjustedMargin' );
		}
	},

	// Function to push up .site-content to default state
	undoSiteAdjust: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).removeClass( 'adjustedMargin' );
			$( '#header .logo' ).removeClass( 'adjustedTop' );
			$( '.main-menu' ).removeClass( 'adjustedMargin' );
			$( '#header' ).removeClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.secondary-header' ).removeClass( 'adjustedMargin' );
		}
	},

	// Function to show Notifications before header
	showNotif: function( text ) {
		text = ( typeof text == 'undefined' ) ? notif_text : text;
		Webtwic.adjustSiteContent();
		$( 'body' ).prepend(
			'
'+text+''+close_button+'
'
		);

		$( '.close-button' ).on( 'click', function( e ) {
			e.preventDefault();
			Webtwic.undoReset();
		});
	},

	// Function to hide Notifications
	hideNotif: function() {
		$( '#notifBanner' ).removeClass( 'notif_vis' );
	},

	resetSite: function() {
		Webtwic.showNotif();
		Webtwic.adjustSiteContent();
	},

	undoReset: function() {
		Webtwic.hideNotif();
		Webtwic.undoSiteAdjust();
	},
};

var WBT = Webtwic,
	 $$ = Webtwic,
	 close_button = '',
	 browser_link = ' ' + 'browser.' + ' ',
	 notif_text = 'Whoa. Your browser currently dosen\'t support some important features. Please try refreshing this page or get a better' +browser_link;

// Detect when the DOM is ready

jQuery( document ).ready( function() {
	// Test for HTML5 support
	if ( window.Modernizr )
		if ( !Modernizr.canvas )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else
		if ( canvascheck === false )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;

	// Define Variables
	var $scroll_top = $( 'a.scroll_top' ),
	is_toggle_active = $( '.hamburger' ).hasClass( 'is_active' ),
	height = 200;

	// Performance Fixes

	// Start browser detection
	switch ( browser_name ) {
	   case 'microsoft edge':
	      Webtwic.showBrowser( 'msedge' );
	      break;
		default:
			Webtwic.showBrowser();
	}

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/

	var required_features = [
		Modernizr.flexbox,
		Modernizr.inlinesvg,
		Modernizr.svg,
		Modernizr.svgclippaths,
		Modernizr.fontface,
		Modernizr.boxshadow,
		Modernizr.borderradius,
		Modernizr.csstransforms
	];

	if ( window.Modernizr )
		if ( !( required_features ) )
			Webtwic.showNotif();
		else /* do nothing */ ;
	else /* do nothing */ ;

	// Start Main Page

	$( 'nav li ul.drop-nav' )
	.hide()
	.removeClass( 'dropNavFallback' );

	if ( $( window ).width() > 768 ) {
		$( 'nav li.dropdown' ).hover(function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideDown( 'fast' );
		}, function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideUp( 'fast' );
		});
	}

	$( '.active-item' ).append(
		'<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z"></path></svg>'
	);

	$( 'a.hamburger' ).on('click', function( e ) {
		$( this ).toggleClass( 'is_active' );

		e.preventDefault();
	});
	$( '.mobile-header .mobile-nav' ).hide();

	$( window ).on('scroll', function() {
		( $( this ).scrollTop() > height ) ? $scroll_top.addClass( 'topVisible' ): $scroll_top.removeClass( 'topVisible' );
	});

	// Styles for homepage article-social

	$( '.article .article-social a' ).hover(function() {
		$( 'span', this )
		.eq(1)
		.fadeIn(400);
	}, function() {
		$( 'span', this )
		.eq(1)
		.fadeOut(250);
	});

	// Functions for search-icon and ui-overlay-search

	$( '.header-follow-search .search-wrap' ).on( 'click', function() {
		openUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).on( 'click', function( e ) {
		e.preventDefault();
		closeUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).hover(
		function() {
			$( this ).addClass( 'spin' );
		}, function() {
			$( this ).removeClass( 'spin' );
	});

	function openUiOverlay() {
		$( '.ui-overlay-search' ).addClass( 'is_open' );
	}

	function closeUiOverlay() {
		$( '.ui-overlay-search' ).removeClass( 'is_open' );
	}

	$( '.ui-overlay-search .search-input input' ).on('focus', function() {
		$( '.search-input' ).attr( 'data-focused', 'true' );
		$( '.search-input input' ).addClass( '_is-focused' );
		$( '#__expand' ).addClass( 'visible' );
	});

	$( '.ui-overlay-search .search-input input' ).on('blur', function() {
		$( '.search-input' ).attr( 'data-focused', 'false' );
		$( '.search-input input' ).removeClass( '_is-focused' );
		$( '#__expand' ).removeClass( 'visible' );
	});

	$( '.post-meta .post-meta-inner .cta-btns a.is_inactive' ).on( 'click', function( e ) {
		e.preventDefault();
	});

	$( document ).on('keydown', function( e ) {
		if ( e.keyCode == 27 )
			closeUiOverlay();
		else /* do nothing */ ;
 	});

	$( '.mobile-nav' ).hide();

	// Functions for more-posts button click

	var loadMoreBtn = '.secondary-category-section .category-posts-column [data-clicked="false"]';

	function addLoader() {
		$( loadMoreBtn )
		.attr( 'data-clicked', 'true' )
		.append( '' );
	}

	$( loadMoreBtn ).on( 'click', function( e ) {
		$( this ).css({
			'background': '#50ABF1',
			'color': '#fff'
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on( 'click', function( e ) {
		$( 'body, html' ).animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<commit_msg>Replace .tooltip fadeIn() and fadeOut()<commit_after>/**
 * Author: Olaolu Olawuyi

 * Date Created: 20/08/2015

 * Last Modified: 01/07/2016

 * Twitter: @whizkydee, @webtwic

 * Github: https://github.com/webtwic/webtwic-site

*/

var Webtwic = Webtwic || {};

var browser_name = bowser.name.toLowerCase();

var test_canvas = document.createElement( 'canvas' );
var canvascheck = ( test_canvas.getContext ) ? true : false;

Webtwic = {
	// Basic Information about Webtwic
	name: 'Webtwic',
	description: 'A community focused on code tweaks, articles and tutorials for newbie and professional developers.',
	repo: 'https://github.com/webtwic/webtwic-site',
	author: 'Olaolu Olawuyi',
	version: '1.0.0',

	// Start main functions for the object

	// Function to add browser name and version to body class
	showBrowser: function( b ) {
		b = (typeof b == 'undefined') ? browser_name : b.toLowerCase();
		if ( ! ( bowser.webkit ) )
			$( 'body' ).addClass( b + ' ' + b + parseInt( bowser.version ) );
		else
			$( 'body' ).addClass( 'webkit' + ' ' + b + ' ' + b + parseInt( bowser.version ) );
	},

	// Function to set attributes and values to elements
	setAttr: function( elem, name, val ) {
		$( elem, this ).attr( name, val );
	},

	// Function to push down .site-content
	adjustSiteContent: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).addClass( 'adjustedMargin' );
			$( '#header .logo' ).addClass( 'adjustedTop' );
			$( '.main-menu' ).addClass( 'adjustedMargin' );
			$( '#header' ).addClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.site-content' ).addClass( 'adjustSiteContent' );
			$( '.secondary-header' ).addClass( 'adjustedMargin' );
		}
	},

	// Function to push up .site-content to default state
	undoSiteAdjust: function() {
		if ( $( 'body' ).hasClass( 'default-body' ) ) {
			$( '.top-stripe' ).removeClass( 'adjustedMargin' );
			$( '#header .logo' ).removeClass( 'adjustedTop' );
			$( '.main-menu' ).removeClass( 'adjustedMargin' );
			$( '#header' ).removeClass( 'adjustSiteContent' );
		} else if ( $( 'body' ).hasClass( 'secondary-body' ) ) {
			$( '.secondary-header' ).removeClass( 'adjustedMargin' );
		}
	},

	// Function to show Notifications before header
	showNotif: function( text ) {
		text = ( typeof text == 'undefined' ) ? notif_text : text;
		Webtwic.adjustSiteContent();
		$( 'body' ).prepend(
			'
'+text+''+close_button+'
'
		);

		$( '.close-button' ).on( 'click', function( e ) {
			e.preventDefault();
			Webtwic.undoReset();
		});
	},

	// Function to hide Notifications
	hideNotif: function() {
		$( '#notifBanner' ).removeClass( 'notif_vis' );
	},

	resetSite: function() {
		Webtwic.showNotif();
		Webtwic.adjustSiteContent();
	},

	undoReset: function() {
		Webtwic.hideNotif();
		Webtwic.undoSiteAdjust();
	},
};

var WBT = Webtwic,
	 $$ = Webtwic,
	 close_button = '',
	 browser_link = ' ' + 'browser.' + ' ',
	 notif_text = 'Whoa. Your browser currently dosen\'t support some important features. Please try refreshing this page or get a better' +browser_link;

// Detect when the DOM is ready

jQuery( document ).ready( function() {
	// Test for HTML5 support
	if ( window.Modernizr )
		if ( !Modernizr.canvas )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;
	 else
		if ( canvascheck === false )
			Webtwic.showNotif ( "Oops. Looks like your browser doesn't support HTML5. Please get a better" +browser_link+ "for an awesome experience." );
		 else /* do nothing */ ;

	// Define Variables
	var $scroll_top = $( 'a.scroll_top' ),
	is_toggle_active = $( '.hamburger' ).hasClass( 'is_active' ),
	height = 200;

	// Performance Fixes

	// Start browser detection
	switch ( browser_name ) {
	   case 'microsoft edge':
	      Webtwic.showBrowser( 'msedge' );
	      break;
		default:
			Webtwic.showBrowser();
	}

	/*
		TODO: Rebuild Performance fixes for attributes
		See history of Performance fixes.
		Also, check StackOverflow.
		See Issue #12
	*/

	var required_features = [
		Modernizr.flexbox,
		Modernizr.inlinesvg,
		Modernizr.svg,
		Modernizr.svgclippaths,
		Modernizr.fontface,
		Modernizr.boxshadow,
		Modernizr.borderradius,
		Modernizr.csstransforms
	];

	if ( window.Modernizr )
		if ( !( required_features ) )
			Webtwic.showNotif();
		else /* do nothing */ ;
	else /* do nothing */ ;

	// Start Main Page

	$( 'nav li ul.drop-nav' )
	.hide()
	.removeClass( 'dropNavFallback' );

	if ( $( window ).width() > 768 ) {
		$( 'nav li.dropdown' ).hover(function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideDown( 'fast' );
		}, function() {
			$( 'ul.drop-nav', this )
			.stop()
			.slideUp( 'fast' );
		});
	}

	$( '.active-item' ).append(
		'<svg viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"><path d="M 16.682,19.674c 0.010-0.012, 0.014-0.028, 0.024-0.040l 6.982-7.714c 0.39-0.434, 0.39-1.138,0-1.572 c-0.004-0.004-0.008-0.006-0.012-0.008C 23.496,10.13, 23.244,10, 22.964,10L 8.998,10 c-0.286,0-0.54,0.138-0.722,0.352L 8.272,10.348 c-0.39,0.434-0.39,1.138,0,1.572l 6.998,7.754C 15.66,20.108, 16.292,20.108, 16.682,19.674z"></path></svg>'
	);

	$( 'a.hamburger' ).on('click', function( e ) {
		$( this ).toggleClass( 'is_active' );

		e.preventDefault();
	});
	$( '.mobile-header .mobile-nav' ).hide();

	$( window ).on('scroll', function() {
		( $( this ).scrollTop() > height ) ? $scroll_top.addClass( 'topVisible' ): $scroll_top.removeClass( 'topVisible' );
	});

	// Styles for homepage article-social

	$( '.article .article-social a' ).hover(function() {
		$( 'span', this )
		.find('.tooltip')
		.addClass('visible');
	}, function() {
		$( 'span', this )
		.find('.tooltip')
		.removeClass('visible');
	});

	// Functions for search-icon and ui-overlay-search

	$( '.header-follow-search .search-wrap' ).on( 'click', function() {
		openUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).on( 'click', function( e ) {
		e.preventDefault();
		closeUiOverlay();
	});

	$( '.header-follow-search .close-icon' ).hover(
		function() {
			$( this ).addClass( 'spin' );
		}, function() {
			$( this ).removeClass( 'spin' );
	});

	function openUiOverlay() {
		$( '.ui-overlay-search' ).addClass( 'is_open' );
	}

	function closeUiOverlay() {
		$( '.ui-overlay-search' ).removeClass( 'is_open' );
	}

	$( '.ui-overlay-search .search-input input' ).on('focus', function() {
		$( '.search-input' ).attr( 'data-focused', 'true' );
		$( '.search-input input' ).addClass( '_is-focused' );
		$( '#__expand' ).addClass( 'visible' );
	});

	$( '.ui-overlay-search .search-input input' ).on('blur', function() {
		$( '.search-input' ).attr( 'data-focused', 'false' );
		$( '.search-input input' ).removeClass( '_is-focused' );
		$( '#__expand' ).removeClass( 'visible' );
	});

	$( '.post-meta .post-meta-inner .cta-btns a.is_inactive' ).on( 'click', function( e ) {
		e.preventDefault();
	});

	$( document ).on('keydown', function( e ) {
		if ( e.keyCode == 27 )
			closeUiOverlay();
		else /* do nothing */ ;
 	});

	$( '.mobile-nav' ).hide();

	// Functions for more-posts button click

	var loadMoreBtn = '.secondary-category-section .category-posts-column [data-clicked="false"]';

	function addLoader() {
		$( loadMoreBtn )
		.attr( 'data-clicked', 'true' )
		.append( '' );
	}

	$( loadMoreBtn ).on( 'click', function( e ) {
		$( this ).css({
			'background': '#50ABF1',
			'color': '#fff'
		});
		addLoader();
		e.preventDefault();
	});

	$scroll_top.on( 'click', function( e ) {
		$( 'body, html' ).animate({
			scrollTop: 0
		}, 1000);

		e.preventDefault();
	});

});
<|endoftext|>