<commit_before>'use strict';

var immediate = require('immediate');
var isDefineProp = false;
// prevents deoptimization
(function(){
    try {
        Object.defineProperty({}, 'test', {value:true});
        isDefineProp = true;
    }catch(e){}
}());
function defineNonEnum(obj, name, value){
    if(isDefineProp){
         Object.defineProperty(obj, name, {
            value: value,
            configurable: true,
            writable: true
        });
    }else{
        obj[name] = value;
    }
}
function Promise(resolver) {

     if (!(this instanceof Promise)) {
        return new Promise(resolver);
    }

    defineNonEnum(this, 'successQueue', []);
    defineNonEnum(this, 'failureQueue', []);
    defineNonEnum(this, 'resolved', false);

    if(typeof resolver === 'function'){
        this.resolvePassed(resolver);
    }
}
defineNonEnum(Promise.prototype, 'resolvePassed', function(resolver){
    try{
        resolver(this.fulfillUnwrap.bind(this),this.reject.bind(this));
    }catch(e){
        this.reject(e);
    }
});
defineNonEnum(Promise.prototype, 'reject', function(reason){
    this.resolve(false,reason);
});
defineNonEnum(Promise.prototype, 'fulfill', function(value){
    this.resolve(true,value);
});
defineNonEnum(Promise.prototype, 'fulfillUnwrap', function(value){
    unwrap(this.fulfill.bind(this), this.reject.bind(this), value);
});
Promise.prototype.then = function(onFulfilled, onRejected) {
    if(this.resolved){
        return this.resolved(onFulfilled, onRejected);
    } else {
        return this.pending(onFulfilled, onRejected);
    }
};
(function(){
    try {
        Promise.prototype.catch = function(onRejected) {
            return this.then(null, onRejected);
        };
    } catch(e){}
}());
defineNonEnum(Promise.prototype, 'pending', function(onFulfilled, onRejected){
    var self = this;
    return new Promise(function(success,failure){
        if(typeof onFulfilled === 'function'){
            self.successQueue.push({
                resolve: success,
                reject: failure,
                callback:onFulfilled
            });
        }else{
            self.successQueue.push({
                next: success,
                callback:false
            });
        }

        if(typeof onRejected === 'function'){
            self.failureQueue.push({
                resolve: success,
                reject: failure,
                callback:onRejected
            });
        }else{
            self.failureQueue.push({
                next: failure,
                callback:false
            });
        }
    });
});
defineNonEnum(Promise.prototype, 'resolve', function (success, value){

    if(this.resolved){
        return;
    }

    this.resolved = createResolved(this, value, success?0:1);

    var queue = success ? this.successQueue : this.failureQueue;
    var len = queue.length;
    var i = -1;
    while(++i < len) {

        if (queue[i].callback) {
            immediate(execute,queue[i].callback, value, queue[i].resolve, queue[i].reject);
        }else {
            queue[i].next(value);
        }
    }
});

function unwrap(fulfill, reject, value){
    if(value && typeof value.then==='function'){
        value.then(fulfill,reject);
    }else{
        fulfill(value);
    }
}

function createResolved(scope, value, whichArg) {
    function resolved() {
        var callback = arguments[whichArg];
        if (typeof callback !== 'function') {
            return scope;
        }else{
            return new Promise(function(resolve,reject){
                immediate(execute,callback,value,resolve,reject);
            });
        }
    }
    return resolved;
}

function execute(callback, value, resolve, reject) {
    try {
        unwrap(resolve,reject,callback(value));
    } catch (error) {
        reject(error);
    }
}

module.exports = Promise;
<commit_msg>use bracket notation because old android sucks<commit_after>'use strict';

var immediate = require('immediate');
var isDefineProp = false;
// prevents deoptimization
(function(){
    try {
        Object.defineProperty({}, 'test', {value:true});
        isDefineProp = true;
    }catch(e){}
}());
function defineNonEnum(obj, name, value){
    if(isDefineProp){
         Object.defineProperty(obj, name, {
            value: value,
            configurable: true,
            writable: true
        });
    }else{
        obj[name] = value;
    }
}
function Promise(resolver) {

     if (!(this instanceof Promise)) {
        return new Promise(resolver);
    }

    defineNonEnum(this, 'successQueue', []);
    defineNonEnum(this, 'failureQueue', []);
    defineNonEnum(this, 'resolved', false);

    if(typeof resolver === 'function'){
        this.resolvePassed(resolver);
    }
}
defineNonEnum(Promise.prototype, 'resolvePassed', function(resolver){
    try{
        resolver(this.fulfillUnwrap.bind(this),this.reject.bind(this));
    }catch(e){
        this.reject(e);
    }
});
defineNonEnum(Promise.prototype, 'reject', function(reason){
    this.resolve(false,reason);
});
defineNonEnum(Promise.prototype, 'fulfill', function(value){
    this.resolve(true,value);
});
defineNonEnum(Promise.prototype, 'fulfillUnwrap', function(value){
    unwrap(this.fulfill.bind(this), this.reject.bind(this), value);
});
Promise.prototype.then = function(onFulfilled, onRejected) {
    if(this.resolved){
        return this.resolved(onFulfilled, onRejected);
    } else {
        return this.pending(onFulfilled, onRejected);
    }
};
(function(){
    try {
        Promise.prototype['catch'] = function(onRejected) {
            return this.then(null, onRejected);
        };
    } catch(e){}
}());
defineNonEnum(Promise.prototype, 'pending', function(onFulfilled, onRejected){
    var self = this;
    return new Promise(function(success,failure){
        if(typeof onFulfilled === 'function'){
            self.successQueue.push({
                resolve: success,
                reject: failure,
                callback:onFulfilled
            });
        }else{
            self.successQueue.push({
                next: success,
                callback:false
            });
        }

        if(typeof onRejected === 'function'){
            self.failureQueue.push({
                resolve: success,
                reject: failure,
                callback:onRejected
            });
        }else{
            self.failureQueue.push({
                next: failure,
                callback:false
            });
        }
    });
});
defineNonEnum(Promise.prototype, 'resolve', function (success, value){

    if(this.resolved){
        return;
    }

    this.resolved = createResolved(this, value, success?0:1);

    var queue = success ? this.successQueue : this.failureQueue;
    var len = queue.length;
    var i = -1;
    while(++i < len) {

        if (queue[i].callback) {
            immediate(execute,queue[i].callback, value, queue[i].resolve, queue[i].reject);
        }else {
            queue[i].next(value);
        }
    }
});

function unwrap(fulfill, reject, value){
    if(value && typeof value.then==='function'){
        value.then(fulfill,reject);
    }else{
        fulfill(value);
    }
}

function createResolved(scope, value, whichArg) {
    function resolved() {
        var callback = arguments[whichArg];
        if (typeof callback !== 'function') {
            return scope;
        }else{
            return new Promise(function(resolve,reject){
                immediate(execute,callback,value,resolve,reject);
            });
        }
    }
    return resolved;
}

function execute(callback, value, resolve, reject) {
    try {
        unwrap(resolve,reject,callback(value));
    } catch (error) {
        reject(error);
    }
}

module.exports = Promise;
<|endoftext|>


<commit_before>//Canvassy stuff
var canvas = document.getElementById("canvas");
canvas.width = Math.floor((window.innerWidth-40)/16)*16;
canvas.height = Math.floor((window.innerHeight-40)/16)*16;
var ctx = canvas.getContext("2d");
var char = document.getElementById("char");
var rock = document.getElementById("rock");
var grass = document.getElementById("grass");
var charx = 1.0;
var chary = 0.0;
var chunkx = 0;
var chunky = 0;
var chunkmap = [];
var protomap = [];
var tempmaprow = [];

//Map Gen
function genMap(xlim, ylim) {
	for (k=0; k<ylim; k++) {
		for (l=0; l<xlim; l++) {
			tempmaprow.push(Math.round((Math.random()*3/4)+0.25));
		}
		protomap.push(tempmaprow);
		tempmaprow = [];
	}
}
genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
chunkmap.push([chunkx, chunky, protomap]);
drawMap(protomap);
ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
//Keyboardy stuff
function keys(event) {
	switch (event.keyCode) {
		case 87: //W
			if ((chary > 0) && (protomap[(chary-16)/16][(charx-1)/16] == 1)) {
				chary-=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary > 0) == false) && (chunkExists(chunkx, chunky-1) != false)) {
				chunky-=1;
				chary=(canvas.height-16);
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary > 0) == false) && (chunkExists(chunkx, chunky-1) == false)) {
				chunky-=1;
				chary=(canvas.height-16);
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
		case 65: //A
			if ((charx > 16) && (protomap[chary/16][(charx-17)/16] == 1)) {
				charx-=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx > 16) == false) && (chunkExists(chunkx-1, chunky) != false)) {
				chunkx-=1;
				charx=(canvas.width-15);
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx > 16) == false) && (chunkExists(chunkx-1, chunky) == false)) {
				chunkx-=1;
				charx=(canvas.width-15);
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
		case 83: //S
			if ((chary+16 < canvas.height) && (protomap[(chary+16)/16][(charx-1)/16] == 1)) {
				chary+=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary + 16 < canvas.height) == false) && (chunkExists(chunkx, chunky+1) != false)) {
				chunky+=1;
				chary=0;
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary + 16 < canvas.height) == false) && (chunkExists(chunkx, chunky+1) == false)) {
				chunky+=1;
				chary=0;
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
		case 68: //D
			if ((charx+1 < canvas.width) && (protomap[chary/16][(charx+15)/16] == 1)) {
				charx+=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx + 30 < canvas.width) == false) && (chunkExists(chunkx+1, chunky) != false)) {
				chunkx+=1;
				charx=1;
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx + 30 < canvas.width) == false) && (chunkExists(chunkx+1, chunky) == false)) {
				chunkx+=1;
				charx=1;
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			break;
	}
}
window.addEventListener('keydown', keys, false);

//Map drawing
function drawMap(map) {
	for (var i=0; i<map.length; i++) {
		for (var j=0; j<map[i].length; j++) {
			if (map[i][j] == 0) {
				ctx.drawImage(rock, 0, 0, 16, 16, j*16, i*16, 16, 16);
			}
			if (map[i][j] == 1) {
				ctx.drawImage(grass, 0, 0, 16, 16, j*16, i*16, 16, 16);
			}
		}
	}
}
function chunkExists(x, y) {
	for (var i = 0; i < chunkmap.length; i++) {
		if ((chunkmap[i][0] == x) && (chunkmap[i][1] == y)) {
			return chunkmap[i][2];
		}
	}
	return false;
}<commit_msg>Bug Fixes<commit_after>//Canvassy stuff
var canvas = document.getElementById("canvas");
canvas.width = Math.floor((window.innerWidth-40)/16)*16;
canvas.height = Math.floor((window.innerHeight-40)/16)*16;
var ctx = canvas.getContext("2d");
var char = document.getElementById("char");
var rock = document.getElementById("rock");
var grass = document.getElementById("grass");
var charx = 1.0;
var chary = 0.0;
var chunkx = 0;
var chunky = 0;
var chunkmap = [];
var protomap = [];
var tempmaprow = [];

//Map Gen
function genMap(xlim, ylim) {
	for (k=0; k<ylim; k++) {
		for (l=0; l<xlim; l++) {
			tempmaprow.push(Math.round((Math.random()*3/4)+0.25));
		}
		protomap.push(tempmaprow);
		tempmaprow = [];
	}
}
genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
chunkmap.push([chunkx, chunky, protomap]);
drawMap(protomap);
ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
//Keyboardy stuff
function keys(event) {
	switch (event.keyCode) {
		case 87: //W
			if ((chary > 0) && (protomap[(chary-16)/16][(charx-1)/16] == 1)) {
				chary-=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary > 0) == false) && (chunkExists(chunkx, chunky-1) != false)) {
				chunky-=1;
				chary=(canvas.height-16);
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				if (protomap[chary/16][(charx-1)/16] == 0) {
					chunky+=1;
					chary=0;
					protomap = chunkExists(chunkx, chunky);
					drawMap(protomap);
					ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				}
				break;
			}
			else if (((chary > 0) == false) && (chunkExists(chunkx, chunky-1) == false)) {
				chunky-=1;
				chary=(canvas.height-16);
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				if (protomap[chary/16][(charx-1)/16] == 0) {
					chunky+=1;
					chary=0;
					protomap = chunkExists(chunkx, chunky);
					drawMap(protomap);
					ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				}
				break;
			}
			break;
		case 65: //A
			if ((charx > 16) && (protomap[chary/16][(charx-17)/16] == 1)) {
				charx-=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx > 16) == false) && (chunkExists(chunkx-1, chunky) != false)) {
				chunkx-=1;
				charx=(canvas.width-15);
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				if (protomap[chary/16][(charx-1)/16] == 0) {
					chunkx+=1;
					charx=1;
					protomap = chunkExists(chunkx, chunky);
					drawMap(protomap);
					ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				}
				break;
			}
			else if (((charx > 16) == false) && (chunkExists(chunkx-1, chunky) == false)) {
				chunkx-=1;
				charx=(canvas.width-15);
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				if (protomap[chary/16][(charx-1)/16] == 0) {
					chunkx+=1;
					charx=1;
					protomap = chunkExists(chunkx, chunky);
					drawMap(protomap);
					ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				}
				break;
			}
			break;
		case 83: //S
			if ((chary+16 < canvas.height) && (protomap[(chary+16)/16][(charx-1)/16] == 1)) {
				chary+=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((chary + 16 < canvas.height) == false) && (chunkExists(chunkx, chunky+1) != false)) {
				chunky+=1;
				chary=0;
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				if (protomap[chary/16][(charx-1)/16] == 0) {
					chunky-=1;
					chary=(canvas.height-16);
					protomap = chunkExists(chunkx, chunky);
					drawMap(protomap);
					ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				}
				break;
			}
			else if (((chary + 16 < canvas.height) == false) && (chunkExists(chunkx, chunky+1) == false)) {
				chunky+=1;
				chary=0;
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				if (protomap[chary/16][(charx-1)/16] == 0) {
					chunky-=1;
					chary=(canvas.height-16);
					protomap = chunkExists(chunkx, chunky);
					drawMap(protomap);
					ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				}
				break;
			}
			break;
		case 68: //D
			if ((charx+1 < canvas.width) && (protomap[chary/16][(charx+15)/16] == 1)) {
				charx+=16;
				drawMap(protomap);
				ctx.drawImage(char, 0, 0, 14, 16, charx, chary, 14, 16);
				break;
			}
			else if (((charx + 30 < canvas.width) == false) && (chunkExists(chunkx+1, chunky) != false)) {
				chunkx+=1;
				charx=1;
				protomap = chunkExists(chunkx, chunky);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				if (protomap[chary/16][(charx-1)/16] == 0) {
					chunkx-=1;
					charx=(canvas.width-15);
					protomap = chunkExists(chunkx, chunky);
					drawMap(protomap);
					ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				}
				break;
			}
			else if (((charx + 30 < canvas.width) == false) && (chunkExists(chunkx+1, chunky) == false)) {
				chunkx+=1;
				charx=1;
				protomap = [];
				genMap(Math.floor(canvas.width/16), Math.floor(canvas.height/16));
				chunkmap.push([chunkx, chunky, protomap]);
				drawMap(protomap);
				ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				if (protomap[chary/16][(charx-1)/16] == 0) {
					chunkx-=1;
					charx=(canvas.width-15);
					protomap = chunkExists(chunkx, chunky);
					drawMap(protomap);
					ctx.drawImage(char, 0, 0 , 14, 16, charx, chary, 14, 16);
				}
				break;
			}
			break;
	}
}
window.addEventListener('keydown', keys, false);

//Map drawing
function drawMap(map) {
	for (var i=0; i<map.length; i++) {
		for (var j=0; j<map[i].length; j++) {
			if (map[i][j] == 0) {
				ctx.drawImage(rock, 0, 0, 16, 16, j*16, i*16, 16, 16);
			}
			if (map[i][j] == 1) {
				ctx.drawImage(grass, 0, 0, 16, 16, j*16, i*16, 16, 16);
			}
		}
	}
}
function chunkExists(x, y) {
	for (var i = 0; i < chunkmap.length; i++) {
		if ((chunkmap[i][0] == x) && (chunkmap[i][1] == y)) {
			return chunkmap[i][2];
		}
	}
	return false;
}<|endoftext|>


<commit_before>$(function() {

    function blurElement(el, blur) {
      var filter = 'blur(' + blur + 'px)';
      var $el = $(el);
      $el.css('-webkit-filter', filter);
      $el.css('-moz-filter', filter);
      $el.css('-o-filter', filter);
      $el.css('-ms-filter', filter);
      $el.css('filter', filter);
    }

    function updatePage(date) {
      window.location.replace(getDateLink(date));
    }

    function getDateLink(date) {
      var day = ''  + date.getDate();
      if (day.length <= 1) {
        day = '0' + day;
      }
      var month = '' + (date.getMonth() + 1);
      if (month.length <= 1) {
        month = '0' + month;
      }
      var year = ('' + date.getFullYear()).substring(2);

      var formattedDate = month + '-' + day + '-' + year;
      return '/menu/#' + formattedDate;
    }

    function isScrolledIntoView(elem) {
      var docViewTop = $(window).scrollTop();
      var docViewBottom = docViewTop + $(window).height();

      var elemTop = $(elem).offset().top;
      var elemBottom = elemTop + $(elem).height();

      return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }

    $('#today-menu-link').attr('href', getDateLink(new Date()));

    var pizzaBg = $('.splash-background-container');

    $(document).scroll(function() {
      var scrollTop = $(document).scrollTop();
      var blurAmt = scrollTop * 0.02;
      blurElement(pizzaBg, blurAmt);

      if (isScrolledIntoView($('.menu-date-input'))) {
        $('.menu-date-input').focus();
      }
    });

    $('.menu-form').submit(function(ev) {
      var dateStr = $('.menu-date-input').val();
      var date = chrono.parseDate(dateStr);
      if (!date) {
        $('.menu-date-input').val('');
        $('.menu-date-input').attr('placeholder', "That's not a date. Try " + '"Monday."');
      }
      else {
        updatePage(date);
      }

      return false;
    });
});<commit_msg>menu redirect not workin' on github pages<commit_after>$(function() {

    function blurElement(el, blur) {
      var filter = 'blur(' + blur + 'px)';
      var $el = $(el);
      $el.css('-webkit-filter', filter);
      $el.css('-moz-filter', filter);
      $el.css('-o-filter', filter);
      $el.css('-ms-filter', filter);
      $el.css('filter', filter);
    }

    function updatePage(date) {
      window.location.replace(getDateLink(date));
    }

    function getDateLink(date) {
      var day = ''  + date.getDate();
      if (day.length <= 1) {
        day = '0' + day;
      }
      var month = '' + (date.getMonth() + 1);
      if (month.length <= 1) {
        month = '0' + month;
      }
      var year = ('' + date.getFullYear()).substring(2);

      var formattedDate = month + '-' + day + '-' + year;
      return './menu/#' + formattedDate;
    }

    function isScrolledIntoView(elem) {
      var docViewTop = $(window).scrollTop();
      var docViewBottom = docViewTop + $(window).height();

      var elemTop = $(elem).offset().top;
      var elemBottom = elemTop + $(elem).height();

      return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
    }

    $('#today-menu-link').attr('href', getDateLink(new Date()));

    var pizzaBg = $('.splash-background-container');

    $(document).scroll(function() {
      var scrollTop = $(document).scrollTop();
      var blurAmt = scrollTop * 0.02;
      blurElement(pizzaBg, blurAmt);

      if (isScrolledIntoView($('.menu-date-input'))) {
        $('.menu-date-input').focus();
      }
    });

    $('.menu-form').submit(function(ev) {
      var dateStr = $('.menu-date-input').val();
      var date = chrono.parseDate(dateStr);
      if (!date) {
        $('.menu-date-input').val('');
        $('.menu-date-input').attr('placeholder', "That's not a date. Try " + '"Monday."');
      }
      else {
        updatePage(date);
      }

      return false;
    });
});<|endoftext|>


<commit_before>
var _ = require('underscore');

var log_levels = {
    error: 0,
    warn: 1,
    message: 2,
    debug: 3
};

var log_levels_to_string = {};

_.each(log_levels, function (value, key) {
    log_levels_to_string[value] = key;
});

exports.log_levels = log_levels;

var log_level = log_levels.message;

var log = function (level, msg) {
    var now = new Date();

    if (msg === undefined) {
        //TODO: log the function that gave an empty message
    }

    switch (level) {
        case log_levels.error:
            log_fn = console.error;
        break;
        case log_levels.warn:
            log_fn = console.warn;
        break;
        case log_levels.message:
            log_fn = console.log;
        break;
        case log_levels.debug:
            log_fn = console.log;
        break;
        default:
            console.error("Invalid log level:", level);
            return;
    }

    if (level > log_level) {
        log_fn(log_levels_to_string[log_level], now, msg);
    }
};

exports.log = log;

exports.error = function (msg) {
    log(log_levels.error, msg);
};

exports.warn = function (msg) {
    log(log_levels.warn, msg);
};

exports.message = function (msg) {
    log(log_levels.message, msg);
};

exports.debug = function (msg) {
    log(log_levels.debug, msg);
};
<commit_msg>Better logger<commit_after>
var _ = require('underscore');

var utils = require('./utils');

function_name_regex = /\s*(function\s*\(.*\))/;

var log_levels = {
    error: 0,
    warn: 1,
    log: 2,
    debug: 3
};

var log_levels_to_string = {};

_.each(log_levels, function (value, key) {
    log_levels_to_string[value] = "__" + key + "__";
});

var log_level = log_levels.log;

var set_log_level = function (new_log_level) {
    if (log_levels[new_log_level]) {
        log_level = new_log_level;
    }
    else {
        utils.die(new_log_level, "is not a valid log level");
    }
};

var log = function (level, args) {
    var now = new Date();
    var caller;
    args = Array.prototype.slice.call(args);

    if (args[0] === undefined) {
        caller = arguments.callee.caller.match(function_name_regex);
        caller = caller || caller[0];
        console.error(caller, "called log with no message");
        return;
    }

    switch (level) {
        case log_levels.error:
            log_fn = console.error;
        break;
        case log_levels.warn:
            log_fn = console.warn;
        break;
        case log_levels.log:
            log_fn = console.log;
        break;
        case log_levels.debug:
            log_fn = console.log;
        break;
        default:
            console.error("Invalid log level:", level);
            return;
    }

    if (level >= log_level) {
        args.unshift(log_levels_to_string[log_level], now);
        log_fn.apply(null, args);
    }
};

_.each(log_levels, function (value, key) {
    exports[key] = function () {
        log(log_levels[key], arguments);
    };
});

exports.set_log_level = set_log_level;
<|endoftext|>


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

	twitterFetcher.fetch('398379208813985792', 'example1', 1, true);

  //slideshow + pagination//
	jQuery('#slideshow').cycle({
		fx: 'fade',
		timeout:   0,
        prev:    '#previousbutton',
        next:    '#nextbutton',
        pager:   '#pagenavi',
        pagerAnchorBuilder: pagerFactory
   	});

    //Fetching latest Tweet//
   	function pagerFactory(idx, slide) {
        var s = idx > 3 ? ' style="display:none"' : '';
        return '
'+(idx+1)+'
';
    };

    //prevent submit form//
    jQuery('.submitbutton').on("click", function(event) {
      event.preventDefault();
      var first_name = jQuery("#first_name").val();
      console.log(first_name);
      var last_name = jQuery("#last_name").val();
      console.log(last_name);
      var email_from = jQuery("#email").val();
      console.log(email_from);
      var telephone = jQuery("#telephone").val();
      console.log(telephone);
      var DoB = jQuery("#DoB").val();
      console.log(DoB);
      var address = jQuery("#address").val();
      console.log(address);
      var country = jQuery("#country").val();
      console.log(country);
      var comments = jQuery("#comments").val();
      console.log(comments);
      var terms = jQuery("#terms").attr('checked');
      console.log(terms);
      console.log('the form did not submitted');
    });

});

<commit_msg>new03<commit_after>jQuery(document).ready(function(){

	twitterFetcher.fetch('398379208813985792', 'example1', 1, true);

  //slideshow + pagination//
	jQuery('#slideshow').cycle({
		fx: 'fade',
		timeout:   0,
        prev:    '#previousbutton',
        next:    '#nextbutton',
        pager:   '#pagenavi',
        pagerAnchorBuilder: pagerFactory
   	});

    //Fetching latest Tweet//
   	function pagerFactory(idx, slide) {
        var s = idx > 3 ? ' style="display:none"' : '';
        return '
'+(idx+1)+'
';
    };

    //prevent submit form//
    jQuery('.submitbutton').on("click", function(event) {
      event.preventDefault();
      var first_name = jQuery("#first_name").val();

      var last_name = jQuery("#last_name").val();

      var email_from = jQuery("#email").val();

      var telephone = jQuery("#telephone").val();

      var DoB = jQuery("#DoB").val();

      var address = jQuery("#address").val();

      var country = jQuery("#country").val();

      var comments = jQuery("#comments").val();

      var terms = jQuery("#terms").is(':checked');

      var has_errors = false;

      if (first_name == "") {
        var has_errors = true;
      };

      if (last_name == "") {
        var has_errors = true;
      };

      if (email_from == "") {
        var has_errors = true;
      };

      if (telephone == "") {
        var has_errors = true;
      };

      if (DoB == "") {
        var has_errors = true;
      };

      if (country == "") {
        var has_errors = true;
      };

      if (terms == false) {
        var has_errors = true;
      };

    });

});

<|endoftext|>


<commit_before>'use strict';

var Git = require('nodegit');
var debug = require('debug')('kit:log');

var config = require('./config');

var order = {
    'none': Git.Revwalk.SORT.NONE,
    'topological': Git.Revwalk.SORT.TOPOLOGICAL,
    'time': Git.Revwalk.SORT.TIME,
    'reverse': Git.Revwalk.SORT.REVERSE
};

var map = function(repo, o){
    var abbrev = !!o['abbrev-commit'];

    return Promise.resolve()
    .then(function(){
        if (!abbrev || !!o.abbrev) return o;

        return config.get(repo, 'core.abbrev')
        .then(function(abbrev){
            o.abbrev = abbrev; // immutable!?
            return o;
        });
    })
    .then(function(options){
        return function(commit){
            var author = commit.author();
            var sha = commit.sha();
            if (abbrev){
                sha = sha.slice(0, options.abbrev);
            }

            return {
                'commit': sha,
                'author': {
                    'name': author.name(),
                    'email': author.email()
                },
                'date': commit.date(),
                'message': commit.message().trim()
            };
        };
    });
}

module.exports = function(repo, o){
    o = o || {};

    var options = {
        'sort': o.sort in order ? order[o.sort] : o.sort,
        'abbrev': o.abbrev || null,
        'abbrev-commit': o['abbrev-commit'] || false
    };

    return repo.getBranchCommit('master')
    .then(function(commit){
        return new Promise(function(resolve, reject){
            commit.history(options.sort)
            .on('end', resolve)
            .on('error', reject)
            .start();
        })
        .then(function(commits){
            return map(repo, options)
            .then(function(log){
                return commits.map(log);
            });
        });
        /*
        .then(function(commits){
            if (!options['abbrev-commit']){
                return commits;
            }

            var oid = commits[0].id();

            return Git.Object.lookup(repo, oid, Git.Object.TYPE.COMMIT)
            .then(function(object){
                return object.shortId();
            })
            .then(function(buf){
                console.log('buffer', buf);
                // Use buf
                return commits;
            });

        })*/
        /*
        .then(function(commits){
            return commits.map(function(commit){

                var author = commit.author();
                return {
                    'commit': commit.sha(),
                    'author': {
                        'name': author.name(),
                        'email': author.email()
                    },
                    'date': commit.date(),
                    'message': commit.message().trim()
                };
            });
        });
        */
    });
};
<commit_msg>cleanup<commit_after>'use strict';

var Git = require('nodegit');
var debug = require('debug')('kit:log');

var config = require('./config');

var order = {
    'none': Git.Revwalk.SORT.NONE,
    'topological': Git.Revwalk.SORT.TOPOLOGICAL,
    'time': Git.Revwalk.SORT.TIME,
    'reverse': Git.Revwalk.SORT.REVERSE
};

var map = function(repo, o){
    var abbrev = !!o['abbrev-commit'];

    return Promise.resolve()
    .then(function(){
        if (!abbrev || !!o.abbrev) return o;

        return config.get(repo, 'core.abbrev')
        .then(function(abbrev){
            o.abbrev = abbrev; // immutable!?
            return o;
        });
    })
    .then(function(options){
        return function(commit){
            var author = commit.author();
            var sha = commit.sha();
            if (abbrev){
                sha = sha.slice(0, options.abbrev);
            }

            return {
                'commit': sha,
                'author': {
                    'name': author.name(),
                    'email': author.email()
                },
                'date': commit.date(),
                'message': commit.message().trim()
            };
        };
    });
};

// repo.createRevWalk();
// revwalk.sorting(NodeGit.Revwalk.SORT.TIME);
// revwalk.getCommits(1);

module.exports = function(repo, o){
    o = o || {};

    var options = {
        'sort': o.sort in order ? order[o.sort] : o.sort,
        'abbrev': o.abbrev || null,
        'abbrev-commit': o['abbrev-commit'] || false
    };

    return repo.getBranchCommit('master')
    .then(function(commit){
        return new Promise(function(resolve, reject){
            commit.history(options.sort)
            .on('end', resolve)
            .on('error', reject)
            .start();
        })
        .then(function(commits){
            return map(repo, options)
            .then(function(log){
                return commits.map(log);
            });
        });
    });
};
<|endoftext|>


<commit_before>//take variables from from
function Character() {
  this.name = "idkMyBFFGil";
  this.health = 100;
  this.attack = 10;
  this.defense = 10;
}
var hero = new Character();

//initialize character
function initialize_character() {
  hero.name = document.getElementById('fname');
  hero.health = 100; // Starting health
  hero.attack = document.getElementById('stats'); // document.getElementById("attack").value
  hero.defense = 10 - document.getElementById('stats'); // document.getElementById("defense").value
}

function switch_to_gameplay() {
  document.getElementById('initialForm').style.display = "none";
  document.getElementById('gameplay').style.display = "block";
}

function update_status() {
  document.getElementById("status_health").innerHTML = hero.health;
}

function gameplay() {
  wolvesAttack();
  banditsAttack();
  trollsAttack();
  dragonAttack();
  //pathFunction5();

  //finalBoss();
}

function run () {
  initialize_character();
  switch_to_gameplay();
  gameplay();
}
<commit_msg>Autoscroll to bottom of div "path"<commit_after>//take variables from from
function Character() {
  this.name = "idkMyBFFGil";
  this.health = 100;
  this.attack = 10;
  this.defense = 10;
}
var hero = new Character();

//initialize character
function initialize_character() {
  hero.name = document.getElementById('fname');
  hero.health = 100; // Starting health
  hero.attack = document.getElementById('stats'); // document.getElementById("attack").value
  hero.defense = 10 - document.getElementById('stats'); // document.getElementById("defense").value
}

function switch_to_gameplay() {
  document.getElementById('initialForm').style.display = "none";
  document.getElementById('gameplay').style.display = "block";
}

function update_status() {
  document.getElementById("status_health").innerHTML = hero.health;
  document.getElementById("path").scrollTop = document.getElementById("path").scrollHeight;
}

function gameplay() {
  wolvesAttack();
  banditsAttack();
  trollsAttack();
  dragonAttack();
  //pathFunction5();

  //finalBoss();
}

function run () {
  initialize_character();
  switch_to_gameplay();
  gameplay();
}
<|endoftext|>


<commit_before>import Progress from 'progress';
import assert from 'assert';
import chalk from 'chalk';

class Log {
  info (text) {
    console.log(`> ${text}`);
  }

  warn (text) {
    console.log(`> ${chalk.blue('WARN')} ${text}`);
  }

  error (text) {
    if (text.stack) text = text.stack;
    console.log(`> ${chalk.red('ERR!')} ${text}`);
  }

  enableProgress (text) {
    assert(!this.bar);
    this.bar = new Progress(`    ${text} [:bar] :percent`, {
      width: 20,
      complete: '=',
      incomplete: ' ',
      total: 100
    });
  }

  showProgress (percentage) {
    this.bar.update(percentage / 100);
  }

  disableProgress () {
    assert(this.bar);
    this.bar.update(1);
    this.bar.terminate();
    delete this.bar;
  }
}

export const log = new Log();
<commit_msg>improvements to `log`<commit_after>import Progress from 'progress';
import assert from 'assert';
import chalk from 'chalk';

class Log {
  _lines (lines) {
    for (const line of lines) {
      console.log(`  ${line}`);
    }
  }

  debug (text, lines) {
    if (!this.debugMode) return;
    console.log(`> ${chalk.green('[debug]')} ${text}`);
    if (lines) this._lines(lines);
  }

  info (text, lines) {
    console.log(`> ${text}`);
    if (lines) this._lines(lines);
  }

  warn (text, lines) {
    console.log(`> ${chalk.blue('Warning')} ${text}`);
    if (lines) this._lines(lines);
  }

  error (text, lines) {
    if (text.message && text.noStack) text = text.message;
    if (text.stack) text = text.stack;
    console.log(`> ${chalk.red('Error!')} ${text}`);
    if (lines) this._lines(lines);
  }

  enableProgress (text) {
    assert(!this.bar);
    this.bar = new Progress(`    ${text} [:bar] :percent`, {
      width: 20,
      complete: '=',
      incomplete: ' ',
      total: 100
    });
  }

  showProgress (percentage) {
    this.bar.update(percentage / 100);
  }

  disableProgress () {
    assert(this.bar);
    this.bar.update(1);
    this.bar.terminate();
    delete this.bar;
  }
}

export function noStack (error) {
  if (typeof error === 'string') {
    error = new Error(error);
  }
  error.noStack = true;
}

export const log = new Log();
<|endoftext|>


<commit_before>/* Normalized hide address bar for iOS & Android (c) Scott Jehl, scottjehl.com MIT License */
(function(a){var b=a.document;if(!location.hash&&a.addEventListener){window.scrollTo(0,1);var c=1,d=function(){return a.pageYOffset||b.compatMode==="CSS1Compat"&&b.documentElement.scrollTop||b.body.scrollTop||0},e=setInterval(function(){if(b.body){clearInterval(e);c=d();a.scrollTo(0,c===1?0:1)}},15);a.addEventListener("load",function(){setTimeout(function(){if(d()<20){a.scrollTo(0,c===1?0:1)}},0)})}})(this);

/*! A fix for the iOS orientationchange zoom bug. Script by @scottjehl, rebound by @wilto.MIT License.*/
(function(m){var l=m.document;if(!l.querySelector){return}var n=l.querySelector("meta[name=viewport]"),a=n&&n.getAttribute("content"),k=a+",maximum-scale=1",d=a+",maximum-scale=10",g=true,j,i,h,c;if(!n){return}function f(){n.setAttribute("content",d);g=true}function b(){n.setAttribute("content",k);g=false}function e(o){c=o.accelerationIncludingGravity;j=Math.abs(c.x);i=Math.abs(c.y);h=Math.abs(c.z);if(!m.orientation&&(j>7||((h>6&&i<8||h<8&&i>6)&&j>5))){if(g){b()}}else{if(!g){f()}}}m.addEventListener("orientationchange",f,false);m.addEventListener("devicemotion",e,false)})(this);

(function(w){
	var sw = document.body.clientWidth,
		sh = document.body.clientHeight,
		breakpoint = 650,
		speed = 800,
		mobile = true;

	$(document).ready(function() {
		checkMobile();
		setNav();
		setImg();
	});

	$(w).resize(function(){ //Update dimensions on resize
		sw = document.body.clientWidth;
		sh = document.body.clientHeight;
		checkMobile();
	});

	//Check if Mobile
	function checkMobile() {
		mobile = (sw > breakpoint) ? false : true;
		if (!mobile) { //If Not Mobile
			loadAux();
			$('.aux header a').addClass('disabled').addClass('open');
			$('[role="tabpanel"],#nav,#search').show(); //Show full navigation and search
		} else { //Hide
			if(!$('#nav-anchors a').hasClass('active')) {
				$('#nav,#search').hide();
			}
		}
	}

	//Toggle navigation for small screens
	function setNav() {
		var $anchorLinks = $('#nav-anchors').find('a');
		$anchorLinks.click(function(e){
			e.preventDefault();
			var $this = $(this),
				thisHref = $this.attr('href');
			$('.reveal').hide();
			if($this.hasClass('active')) {
				$this.removeClass('active');
				$(thisHref).hide();
			} else {
				$anchorLinks.removeClass('active');
				$this.addClass('active');
				$(thisHref).show();
			}
		});
	}

	//Set up Image Carousel
	function setImg() {
		var container = $('#img-container'),
			nav = $('#product-img').find('nav'),
			imgList = Object,
			current = 0,
			swipeEnabled = false;

		function buildGallery() {
			container.html('

');
			imgList = $('#img-list');
			nav.find('li:first').addClass('active');

			var arr = '';

			//For Each Navigation Link
			nav.find('a').each(function() {
				var $this = $(this),
					href = $this.attr('href');

				//Prepare list item with image source in data attribute
				arr += '

';
			});

			//Append to #img-list
			imgList.find('ul').append(arr);

			//Nav Thumbnail Click
			nav.on('click','a',function(e) {
				var pos = $(this).parent().index();
				e.preventDefault();
				loadImg(pos);
				if(swipeEnabled) {
					mySwipe.slide(pos,300);
				}
				updateNav(pos);
			});

			Modernizr.load({
			  test: Modernizr.touch && Modernizr.csstransitions,
			  yep : 'js/swipe.js',
			  complete : function() {
					if(w.Swipe) {
						swipeEnabled = true;
						buildSwipe();
					}
			  }
			});
			loadImg(0); //Load initial image
		}

		//Build Swipe Carousel
		function buildSwipe() {
			//Initialize Swipe.js
			var imgList = document.getElementById('img-list');
			w.mySwipe = new Swipe(imgList, {
				callback: function(event, index, elem) {
					updateNav(index);
					loadImg(index+1);
				}
			});
			imgList.addEventListener('touchstart', function(event) {
    			loadImg(w.mySwipe.getPos()+1);
			}, false);
		}

		//Dynamically Load Images
		function loadImg(index) {
			var lis = imgList.find('li'),
				li = lis.eq(index),
				imgSrc = li.attr('data-imgsrc');
			if(!swipeEnabled) {
				lis.hide();
				li.show();
			}

			if(li.html() === "") { //If li is empty
				var img = new Image();
				imgList.addClass('loading');
				$(img).load(function () { //Load image
					$(this).hide();
					li.removeClass('loading');
					$(this).fadeIn();
				}).error(function () {
					// notify the user that the image could not be loaded
				}).attr('src', imgSrc);
				$('').attr('src',imgSrc).appendTo(li);
			}
		}

		//Update Image Thumbnail Navigation
		function updateNav(pos) {
			nav.find('li').removeClass('active');
			nav.find('li:eq('+pos+')').addClass('active');
		}

		buildGallery();
	}

})(this);		<commit_msg>added auxilary contect function<commit_after>/* Normalized hide address bar for iOS & Android (c) Scott Jehl, scottjehl.com MIT License */
(function(a){var b=a.document;if(!location.hash&&a.addEventListener){window.scrollTo(0,1);var c=1,d=function(){return a.pageYOffset||b.compatMode==="CSS1Compat"&&b.documentElement.scrollTop||b.body.scrollTop||0},e=setInterval(function(){if(b.body){clearInterval(e);c=d();a.scrollTo(0,c===1?0:1)}},15);a.addEventListener("load",function(){setTimeout(function(){if(d()<20){a.scrollTo(0,c===1?0:1)}},0)})}})(this);

/*! A fix for the iOS orientationchange zoom bug. Script by @scottjehl, rebound by @wilto.MIT License.*/
(function(m){var l=m.document;if(!l.querySelector){return}var n=l.querySelector("meta[name=viewport]"),a=n&&n.getAttribute("content"),k=a+",maximum-scale=1",d=a+",maximum-scale=10",g=true,j,i,h,c;if(!n){return}function f(){n.setAttribute("content",d);g=true}function b(){n.setAttribute("content",k);g=false}function e(o){c=o.accelerationIncludingGravity;j=Math.abs(c.x);i=Math.abs(c.y);h=Math.abs(c.z);if(!m.orientation&&(j>7||((h>6&&i<8||h<8&&i>6)&&j>5))){if(g){b()}}else{if(!g){f()}}}m.addEventListener("orientationchange",f,false);m.addEventListener("devicemotion",e,false)})(this);

(function(w){
	var sw = document.body.clientWidth,
		sh = document.body.clientHeight,
		breakpoint = 650,
		speed = 800,
		mobile = true;

	$(document).ready(function() {
		checkMobile();
		setNav();
		setImg();
	});

	$(w).resize(function(){ //Update dimensions on resize
		sw = document.body.clientWidth;
		sh = document.body.clientHeight;
		checkMobile();
	});

	//Check if Mobile
	function checkMobile() {
		mobile = (sw > breakpoint) ? false : true;
		if (!mobile) { //If Not Mobile
			loadAux();
			$('.aux header a').addClass('disabled').addClass('open');
			$('[role="tabpanel"],#nav,#search').show(); //Show full navigation and search
		} else { //Hide
			if(!$('#nav-anchors a').hasClass('active')) {
				$('#nav,#search').hide();
			}
		}
	}

	//Toggle navigation for small screens
	function setNav() {
		var $anchorLinks = $('#nav-anchors').find('a');
		$anchorLinks.click(function(e){
			e.preventDefault();
			var $this = $(this),
				thisHref = $this.attr('href');
			$('.reveal').hide();
			if($this.hasClass('active')) {
				$this.removeClass('active');
				$(thisHref).hide();
			} else {
				$anchorLinks.removeClass('active');
				$this.addClass('active');
				$(thisHref).show();
			}
		});
	}

	//Set up Image Carousel
	function setImg() {
		var container = $('#img-container'),
			nav = $('#product-img').find('nav'),
			imgList = Object,
			current = 0,
			swipeEnabled = false;

		function buildGallery() {
			container.html('

');
			imgList = $('#img-list');
			nav.find('li:first').addClass('active');

			var arr = '';

			//For Each Navigation Link
			nav.find('a').each(function() {
				var $this = $(this),
					href = $this.attr('href');

				//Prepare list item with image source in data attribute
				arr += '

';
			});

			//Append to #img-list
			imgList.find('ul').append(arr);

			//Nav Thumbnail Click
			nav.on('click','a',function(e) {
				var pos = $(this).parent().index();
				e.preventDefault();
				loadImg(pos);
				if(swipeEnabled) {
					mySwipe.slide(pos,300);
				}
				updateNav(pos);
			});

			Modernizr.load({
			  test: Modernizr.touch && Modernizr.csstransitions,
			  yep : 'js/swipe.js',
			  complete : function() {
					if(w.Swipe) {
						swipeEnabled = true;
						buildSwipe();
					}
			  }
			});
			loadImg(0); //Load initial image
		}

		//Build Swipe Carousel
		function buildSwipe() {
			//Initialize Swipe.js
			var imgList = document.getElementById('img-list');
			w.mySwipe = new Swipe(imgList, {
				callback: function(event, index, elem) {
					updateNav(index);
					loadImg(index+1);
				}
			});
			imgList.addEventListener('touchstart', function(event) {
    			loadImg(w.mySwipe.getPos()+1);
			}, false);
		}

		//Dynamically Load Images
		function loadImg(index) {
			var lis = imgList.find('li'),
				li = lis.eq(index),
				imgSrc = li.attr('data-imgsrc');
			if(!swipeEnabled) {
				lis.hide();
				li.show();
			}

			if(li.html() === "") { //If li is empty
				var img = new Image();
				imgList.addClass('loading');
				$(img).load(function () { //Load image
					$(this).hide();
					li.removeClass('loading');
					$(this).fadeIn();
				}).error(function () {
					// notify the user that the image could not be loaded
				}).attr('src', imgSrc);
				$('').attr('src',imgSrc).appendTo(li);
			}
		}

		//Update Image Thumbnail Navigation
		function updateNav(pos) {
			nav.find('li').removeClass('active');
			nav.find('li:eq('+pos+')').addClass('active');
		}

		buildGallery();
	}

	//Set up Auxiliary content
	$('.aux header a').addClass('disabled');

	function loadAux() {
		var $aux = $('.aux');
		$aux.each(function(index) {
			var $this = $(this),
				auxLink = $this.find('a'),
				auxFragment = auxLink.attr('href'),
				auxContent = $this.find('[role=tabpanel]');
			if(auxContent.size()===0 && $this.hasClass('loaded')===false){
				loadContent(auxFragment,$this);
			}
		});
	}

})(this);		<|endoftext|>


<commit_before>var sys = require('sys');

function log(level, args) {
    if (level >= exports.level) {
        sys.print((new Date()).toUTCString() + ": ");
        sys.puts(join(args));
    }
}

exports.levels = levels = {
    "DEBUG" : 0,
    "INFO" : 1,
    "WARN" : 2,
    "ERROR" : 3
}

exports.level = levels.warn;

exports.debug = function() {
    log(levels.DEBUG, arguments);
}
exports.warn = function() {
    log(levels.WARN, arguments);
}
exports.info = function() {
    log(levels.INFO, arguments);
}
exports.error = function() {
    log(levels.ERROR, arguments);
}

/* Utility functions */
function slice(array,start) {
	return Array.prototype.slice.call(array,start);
}
function isString(s) {
	return typeof s === "string" || s instanceof String;
}
function flatten(array) {
	var result = [], i, len = array && array.length;
	if(len && !isString(array)) {
		for(i = 0; i < len; i++) {
			result = result.concat(flatten(array[i]));
		}
	} else if(len !== 0) {
		result.push(array);
	}
	return result;
}
function join() {
	return flatten(slice(arguments,0)).join(" ");
}
<commit_msg>started using underscore.js<commit_after>var sys = require('sys');
require('./underscore/underscore');

function log(level, args) {
    if (level >= exports.level) {
        sys.print((new Date()).toUTCString() + ": ");
        sys.puts(_(args).toArray().join(' '));
    }
}

exports.levels = levels = {
    "DEBUG" : 0,
    "INFO" : 1,
    "WARN" : 2,
    "ERROR" : 3
}

exports.level = levels.warn;

exports.debug = function() {
    log(levels.DEBUG, arguments);
}
exports.warn = function() {
    log(levels.WARN, arguments);
}
exports.info = function() {
    log(levels.INFO, arguments);
}
exports.error = function() {
    log(levels.ERROR, arguments);
}
<|endoftext|>


<commit_before>'use strict';

function repo_drawlogic(){
    canvas_buffer.save();
    canvas_buffer.translate(
      canvas_properties['width-half'],
      canvas_properties['height-half']
    );
    canvas_buffer.rotate(math_degrees_to_radians({
      'degrees': rotation,
    }));

    let loop_counter = 3;
    do{
        canvas_draw_path({
          'properties': {
            'fillStyle': colors[0][loop_counter],
          },
          'vertices': [
            {
              'type': 'moveTo',
            },
            {
              'x': wall_splits[[0,0,2,4,][loop_counter]],
              'y': wall_splits[[1,1,3,5,][loop_counter]],
            },
            {
              'x': wall_splits[[2,4,6,6,][loop_counter]],
              'y': wall_splits[[3,5,7,7,][loop_counter]],
            },
          ],
        });
    }while(loop_counter--);

    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][0],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_properties['width-half'],
          'y': -canvas_properties['width-half'],
        },
        {
          'x': wall_splits[0],
          'y': wall_splits[1],
        },
        {
          'x': wall_splits[2],
          'y': wall_splits[3],
        },
        {
          'x': canvas_properties['width-half'],
          'y': -canvas_properties['width-half'],
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][1],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_properties['width-half'],
          'y': -canvas_properties['width-half'],
        },
        {
          'x': wall_splits[0],
          'y': wall_splits[1],
        },
        {
          'x': wall_splits[4],
          'y': wall_splits[5],
        },
        {
          'x': -canvas_properties['width-half'],
          'y': canvas_properties['width-half'],
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][2],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': canvas_properties['width-half'],
          'y': -canvas_properties['width-half'],
        },
        {
          'x': wall_splits[2],
          'y': wall_splits[3],
        },
        {
          'x': wall_splits[6],
          'y': wall_splits[7],
        },
        {
          'x': canvas_properties['width-half'],
          'y': canvas_properties['width-half'],
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][3],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_properties['width-half'],
          'y': canvas_properties['width-half'],
        },
        {
          'x': wall_splits[4],
          'y': wall_splits[5],
        },
        {
          'x': wall_splits[6],
          'y': wall_splits[7],
        },
        {
          'x': canvas_properties['width-half'],
          'y': canvas_properties['width-half'],
        },
      ],
    });

    canvas_buffer.restore();
}

function repo_logic(){
    if(core_keys[core_storage_data['move-←']]['state']){
        rotation -= speed / 10 + 1;
    }
    if(core_keys[core_storage_data['move-→']]['state']){
        rotation += speed / 10 + 1;
    }
    if(core_keys[core_storage_data['move-↓']]['state']
      && speed > 0){
        speed -= 1;
    }
    if(core_keys[core_storage_data['move-↑']]['state']){
        speed += 1;
    }

    let do_split = false;

    let loop_counter = 3;
    do{
        const double = loop_counter * 2;

        wall_splits[double] += wall_splits[double] >= 0
          ? speed
          : -speed;
        wall_splits[double + 1] += wall_splits[double + 1] >= 0
          ? speed
          : -speed;

        if(wall_splits[double] < -canvas_properties['width-half']
          || wall_splits[double] > canvas_properties['width-half']){
            wall_splits[double] = [
              -2,
              -2,
              2,
              -2,
              -2,
              2,
              2,
              2,
            ][double];
            wall_splits[double + 1] = [
              -2,
              -2,
              2,
              -2,
              -2,
              2,
              2,
              2,
            ][double + 1];

            do_split = true;
        }
    }while(loop_counter--);

    if(do_split){
        colors[1] = colors[0];
        colors[0] = [
          '#' + core_random_hex(),
          '#' + core_random_hex(),
          '#' + core_random_hex(),
          '#' + core_random_hex(),
        ];
    }

    core_ui_update({
      'ids': {
        'speed': speed,
      },
    });
}

function repo_escape(){
    if(wall_splits.length === 0
      && !core_menu_open){
        core_repo_reset();
    }
}

function repo_init(){
    core_repo_init({
      'events': {
        'enter': {
          'onclick': core_repo_reset,
        },
      },
      'globals': {
        'colors': [],
        'rotation': 0,
        'speed': 0,
        'wall_splits': [],
      },
      'info': '<input id=enter type=button value="Enter the Tubes">',
      'menu': true,
      'reset': canvas_setmode,
      'title': 'Tubes-2D3D.htm',
      'ui': ' m/s',
    });
    canvas_init();
}
<commit_msg>added colors check<commit_after>'use strict';

function repo_drawlogic(){
    if(!colors[0]){
        return;
    }

    canvas_buffer.save();
    canvas_buffer.translate(
      canvas_properties['width-half'],
      canvas_properties['height-half']
    );
    canvas_buffer.rotate(math_degrees_to_radians({
      'degrees': rotation,
    }));

    let loop_counter = 3;
    do{
        canvas_draw_path({
          'properties': {
            'fillStyle': colors[0][loop_counter],
          },
          'vertices': [
            {
              'type': 'moveTo',
            },
            {
              'x': wall_splits[[0,0,2,4,][loop_counter]],
              'y': wall_splits[[1,1,3,5,][loop_counter]],
            },
            {
              'x': wall_splits[[2,4,6,6,][loop_counter]],
              'y': wall_splits[[3,5,7,7,][loop_counter]],
            },
          ],
        });
    }while(loop_counter--);

    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][0],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_properties['width-half'],
          'y': -canvas_properties['width-half'],
        },
        {
          'x': wall_splits[0],
          'y': wall_splits[1],
        },
        {
          'x': wall_splits[2],
          'y': wall_splits[3],
        },
        {
          'x': canvas_properties['width-half'],
          'y': -canvas_properties['width-half'],
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][1],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_properties['width-half'],
          'y': -canvas_properties['width-half'],
        },
        {
          'x': wall_splits[0],
          'y': wall_splits[1],
        },
        {
          'x': wall_splits[4],
          'y': wall_splits[5],
        },
        {
          'x': -canvas_properties['width-half'],
          'y': canvas_properties['width-half'],
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][2],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': canvas_properties['width-half'],
          'y': -canvas_properties['width-half'],
        },
        {
          'x': wall_splits[2],
          'y': wall_splits[3],
        },
        {
          'x': wall_splits[6],
          'y': wall_splits[7],
        },
        {
          'x': canvas_properties['width-half'],
          'y': canvas_properties['width-half'],
        },
      ],
    });
    canvas_draw_path({
      'properties': {
        'fillStyle': colors[1][3],
      },
      'vertices': [
        {
          'type': 'moveTo',
          'x': -canvas_properties['width-half'],
          'y': canvas_properties['width-half'],
        },
        {
          'x': wall_splits[4],
          'y': wall_splits[5],
        },
        {
          'x': wall_splits[6],
          'y': wall_splits[7],
        },
        {
          'x': canvas_properties['width-half'],
          'y': canvas_properties['width-half'],
        },
      ],
    });

    canvas_buffer.restore();
}

function repo_logic(){
    if(core_keys[core_storage_data['move-←']]['state']){
        rotation -= speed / 10 + 1;
    }
    if(core_keys[core_storage_data['move-→']]['state']){
        rotation += speed / 10 + 1;
    }
    if(core_keys[core_storage_data['move-↓']]['state']
      && speed > 0){
        speed -= 1;
    }
    if(core_keys[core_storage_data['move-↑']]['state']){
        speed += 1;
    }

    let do_split = false;

    let loop_counter = 3;
    do{
        const double = loop_counter * 2;

        wall_splits[double] += wall_splits[double] >= 0
          ? speed
          : -speed;
        wall_splits[double + 1] += wall_splits[double + 1] >= 0
          ? speed
          : -speed;

        if(wall_splits[double] < -canvas_properties['width-half']
          || wall_splits[double] > canvas_properties['width-half']){
            wall_splits[double] = [
              -2,
              -2,
              2,
              -2,
              -2,
              2,
              2,
              2,
            ][double];
            wall_splits[double + 1] = [
              -2,
              -2,
              2,
              -2,
              -2,
              2,
              2,
              2,
            ][double + 1];

            do_split = true;
        }
    }while(loop_counter--);

    if(do_split){
        colors[1] = colors[0];
        colors[0] = [
          '#' + core_random_hex(),
          '#' + core_random_hex(),
          '#' + core_random_hex(),
          '#' + core_random_hex(),
        ];
    }

    core_ui_update({
      'ids': {
        'speed': speed,
      },
    });
}

function repo_escape(){
    if(wall_splits.length === 0
      && !core_menu_open){
        core_repo_reset();
    }
}

function repo_init(){
    core_repo_init({
      'events': {
        'enter': {
          'onclick': core_repo_reset,
        },
      },
      'globals': {
        'colors': [],
        'rotation': 0,
        'speed': 0,
        'wall_splits': [],
      },
      'info': '<input id=enter type=button value="Enter the Tubes">',
      'menu': true,
      'reset': canvas_setmode,
      'title': 'Tubes-2D3D.htm',
      'ui': ' m/s',
    });
    canvas_init();
}
<|endoftext|>


<commit_before>var Message = Backbone.Model.extend({
    initialize:function(){
        this.listenTo(this, "remove",this.destroy);
        this.listenTo(this, "media", this.showmedia);
        this.set('media', false);
    }
});
var MessageList = Backbone.Collection.extend({
   model: Message,
   localStorage: new Backbone.LocalStorage("conversa"),
   clear: function(){
       this.remove(this.models);
   },
   ismedia: function(){
       return this.filter(function(msg){return msg.get('media')});
   }
});
var MessageView = Backbone.View.extend({
    tagName: "p",
    initialize: function(){
        this.listenTo(this.model,"change", this.render);
        this.listenTo(this.model,"destroy", this.remove);
        this.listenTo(this.model, "change:media", this.rendermedia)
    },
    render: function(){
        this.$el.addClass("message").addClass(this.model.get('from'));
        this.$el.html(this.model.get('body'));
        var t = new Date(this.model.get('time'));
        var date = (t.getHours()<10 ? '0'+t.getHours() : t.getHours());
        date += ':'+(t.getMinutes()<10 ? '0'+t.getMinutes() : t.getMinutes());
        $('
'+date+'
').appendTo(this.$el);
        if(this.model.get('from')=='you') $('

').appendTo(this.$el);
        if(this.model.get('body').match(/<img/g)!=null)
            _.defer(function(){$("a.image").photoSwipe()});
        if(this.model.get('body').match(/<img/g)!=null || this.model.get('body').match(/<video/g)!=null)
            this.model.set('media', true).save();
        return this;
    },
    rendermedia: function(){
        console.log('Rendering media');
        var id = this.model.get('body').match(/<[^>]*src=["|\']([^"|\']+)/i)[1].replace(/\"/g,'').split('/').pop().split('.')[0];
        if($("#"+id).length==0)
            $('
'+this.model.get('body')+'
').appendTo('#mediacont');
        $(window).trigger('newmedia');
    },
    save: function(){
        this.model.save();
    },
    clear: function(){
        console.log('cleaning up');
        this.model.destroy();
    }
});
var User = Backbone.Model.extend({
    idAttribute: "id",
    localStorage: new Backbone.LocalStorage("user")
});
var AppView = Backbone.View.extend({
   el: $("#whatsfake"),
   events:{
       "click #send":"say",
       "keypress #input":"saypress",
       "click #clear":"clearconv",
       "click #media":"showmedia",
       "click #anonim":"anonim"
   },
   initialize: function(){
       var view = this;
       this.user = new User();
       this.user.fetch({
           success: function(){
                console.log('Fetch success');
                if(view.user.id===undefined){
                    console.log('Fake success');
                    view.newUser();
                }else{
                    view.setup();
                }
           },
           error: function(){
               console.log('Fetch fail');
               view.newUser();
           }
       });

   },
   showmedia: function(){
        if($("#mediacont .media").length==0) $("#mediacont").append('
No hay contenido multimedia
');
        $("#container").addClass('flip');
        $('').appendTo('#title');
        $("#back").click(function(){
            $("#container").removeClass('flip');
            $(this).remove();
        })
   },
   clearconv: function(){
       this.Conversa.clear();
   },
   anonim: function(){
       if($("#name").val()!=""){
           var name = $("#name").val();
           var firstname = name.split(' ')[0];
           window.user = {
                    "identifier": "",
                    "webSiteURL": "",
                    "profileURL": "",
                    "photoURL": "",
                    "displayName": name,
                    "description": "",
                    "firstName": firstname,
                    "lastName": "",
                    "gender": "",
                    "language": "",
                    "age": "",
                    "birthDay": "",
                    "birthMonth": "",
                    "birthYear": "",
                    "email": "",
                    "emailVerified": "",
                    "phone": "",
                    "address": "",
                    "country": "",
                    "region": "",
                    "city": "",
                    "zip": ""
           };
           window.provider = "none";
           this.newUser();
       }
   },
   newUser: function(){
        var view = this;
        if(window.user!=null){
            console.log(window.user);
            $.post("newuser.php", {"user":window.user, "provider":window.provider}, function(r){
                eval("var data = "+r);
                if(data.user && data.body){
                    console.log('New user');
                    view.user.set(data.user);
                    view.user.save();
                    var msg = new Message({from:'you',body:data.body,time:new Date(), id:new Date().getTime()});
                    view.setup(msg);
                }else if(data.error){
                    console.log(data.error);
                }else{
                    console.log(r);
                }
            })
            .fail(function(xhr,str){
                alert('Parece que no tienes conexión, no puedo registrarte como nuevo usuario.');
            });
        }else{
            console.log('No user: '+ window.user);
        }
   },
   setup: function(msg){
        this.id = this.user.get('id');

        this.Conversa = new MessageList;
        this.listenTo(this.Conversa, 'add', this.addOneSave);
        this.listenTo(this.Conversa, 'reset', this.addAll);
        this.Conversa.fetch();
        this.input = this.$('#input');
        this.send = this.$("#send");
        this.media = this.$('#mediacont');
        this.register = this.$("#registre");
        if(msg) this.Conversa.add(msg);
        this.register.hide();
   },
   render: function(){

   },
   addOne: function(msg){
       this.Conversa.add(msg);
       var view = new MessageView({model:msg});
       this.$("#bubbles").append(view.render().el);
   },
   addOneSave: function(msg){
       var view = new MessageView({model:msg});
       view.save();
       this.$("#bubbles").append(view.render().el);
   },
   addAll: function(){
       this.Conversa.each(this.addOne,this);
       _.defer(this.createScroll);
   },
   saypress: function(e){
       if (e.keyCode != 13) return;
       if (!this.input.val()) return;
       this.say();
   },
   say: function(){
       var val = this.input.val();
       var view = this;
       if(val!=''){
            // Strip tags
            val = val.replace(/(<([^>]+)>)/ig,"");
            var msg = new Message({from:'me',body:val, time:new Date(), id:new Date().getTime()})
            this.Conversa.add(msg);
            $.post('talk.php',{input:val,user:this.id}, function(r){
                    var msg = new Message({from:'you',body:r, time:new Date(), id:new Date().getTime()})
                    view.Conversa.add(msg);
                    view.input.val('');
                    _.defer(view.scrollDown);
            }).error(function(){
                    var msg = new Message({from:'you',body:'Lo siento, pero parece que no hay conexión, así que tendremos que dejar la charla para más tarde :(', time:new Date(), id:new Date().getTime()})
                    view.Conversa.add(msg);
                    view.input.val('');
                    _.defer(view.scrollDown);
            });
       }
   },
   createScroll: function(){
       setTimeout(function () {
            window.scroller = new iScroll('conversation', {hScrollbar:false, bounce:false})
                window.mscroller = new iScroll('mediadiv', {hScrollbar:false, bounce:false})
                window.scroller.scrollTo(0,-$("#bubbles").height(),0);
                $(window).bind('newmedia', window.refreshmedia);
	}, 0);
   },
   scrollDown: function(){
       setTimeout(function () {
		window.scroller.refresh();
                var lasth = parseInt($("#bubbles p").last().outerHeight())+10;
                lasth += parseInt($("#bubbles p").last().prev().outerHeight())+10;
                console.log(lasth);
                window.scroller.scrollTo(0,lasth,0, true);
                //$("#conversation").scrollTop($("#bubbles").height());
	}, 0);
   }
});
var scroller = false;
var mscroller = false;
function refreshmedia(){
   console.log('refreshing media');
   setTimeout(function () {
            window.mscroller.refresh();
    }, 0);
}
function c(str){
   console.log(str);
}<commit_msg>Added strip dots (.) from string before sending to bot, if not done is parsed as 2 phrases resulting on unexpected results<commit_after>var Message = Backbone.Model.extend({
    initialize:function(){
        this.listenTo(this, "remove",this.destroy);
        this.listenTo(this, "media", this.showmedia);
        this.set('media', false);
    }
});
var MessageList = Backbone.Collection.extend({
   model: Message,
   localStorage: new Backbone.LocalStorage("conversa"),
   clear: function(){
       this.remove(this.models);
   },
   ismedia: function(){
       return this.filter(function(msg){return msg.get('media')});
   }
});
var MessageView = Backbone.View.extend({
    tagName: "p",
    initialize: function(){
        this.listenTo(this.model,"change", this.render);
        this.listenTo(this.model,"destroy", this.remove);
        this.listenTo(this.model, "change:media", this.rendermedia)
    },
    render: function(){
        this.$el.addClass("message").addClass(this.model.get('from'));
        this.$el.html(this.model.get('body'));
        var t = new Date(this.model.get('time'));
        var date = (t.getHours()<10 ? '0'+t.getHours() : t.getHours());
        date += ':'+(t.getMinutes()<10 ? '0'+t.getMinutes() : t.getMinutes());
        $('
'+date+'
').appendTo(this.$el);
        if(this.model.get('from')=='you') $('

').appendTo(this.$el);
        if(this.model.get('body').match(/<img/g)!=null)
            _.defer(function(){$("a.image").photoSwipe()});
        if(this.model.get('body').match(/<img/g)!=null || this.model.get('body').match(/<video/g)!=null)
            this.model.set('media', true).save();
        return this;
    },
    rendermedia: function(){
        console.log('Rendering media');
        var id = this.model.get('body').match(/<[^>]*src=["|\']([^"|\']+)/i)[1].replace(/\"/g,'').split('/').pop().split('.')[0];
        if($("#"+id).length==0)
            $('
'+this.model.get('body')+'
').appendTo('#mediacont');
        $(window).trigger('newmedia');
    },
    save: function(){
        this.model.save();
    },
    clear: function(){
        console.log('cleaning up');
        this.model.destroy();
    }
});
var User = Backbone.Model.extend({
    idAttribute: "id",
    localStorage: new Backbone.LocalStorage("user")
});
var AppView = Backbone.View.extend({
   el: $("#whatsfake"),
   events:{
       "click #send":"say",
       "keypress #input":"saypress",
       "click #clear":"clearconv",
       "click #media":"showmedia",
       "click #anonim":"anonim"
   },
   initialize: function(){
       var view = this;
       this.user = new User();
       this.user.fetch({
           success: function(){
                console.log('Fetch success');
                if(view.user.id===undefined){
                    console.log('Fake success');
                    view.newUser();
                }else{
                    view.setup();
                }
           },
           error: function(){
               console.log('Fetch fail');
               view.newUser();
           }
       });

   },
   showmedia: function(){
        if($("#mediacont .media").length==0) $("#mediacont").append('
No hay contenido multimedia
');
        $("#container").addClass('flip');
        $('').appendTo('#title');
        $("#back").click(function(){
            $("#container").removeClass('flip');
            $(this).remove();
        })
   },
   clearconv: function(){
       this.Conversa.clear();
   },
   anonim: function(){
       if($("#name").val()!=""){
           var name = $("#name").val();
           var firstname = name.split(' ')[0];
           window.user = {
                    "identifier": "",
                    "webSiteURL": "",
                    "profileURL": "",
                    "photoURL": "",
                    "displayName": name,
                    "description": "",
                    "firstName": firstname,
                    "lastName": "",
                    "gender": "",
                    "language": "",
                    "age": "",
                    "birthDay": "",
                    "birthMonth": "",
                    "birthYear": "",
                    "email": "",
                    "emailVerified": "",
                    "phone": "",
                    "address": "",
                    "country": "",
                    "region": "",
                    "city": "",
                    "zip": ""
           };
           window.provider = "none";
           this.newUser();
       }
   },
   newUser: function(){
        var view = this;
        if(window.user!=null){
            console.log(window.user);
            $.post("newuser.php", {"user":window.user, "provider":window.provider}, function(r){
                eval("var data = "+r);
                if(data.user && data.body){
                    console.log('New user');
                    view.user.set(data.user);
                    view.user.save();
                    var msg = new Message({from:'you',body:data.body,time:new Date(), id:new Date().getTime()});
                    view.setup(msg);
                }else if(data.error){
                    console.log(data.error);
                }else{
                    console.log(r);
                }
            })
            .fail(function(xhr,str){
                alert('Parece que no tienes conexión, no puedo registrarte como nuevo usuario.');
            });
        }else{
            console.log('No user: '+ window.user);
        }
   },
   setup: function(msg){
        this.id = this.user.get('id');

        this.Conversa = new MessageList;
        this.listenTo(this.Conversa, 'add', this.addOneSave);
        this.listenTo(this.Conversa, 'reset', this.addAll);
        this.Conversa.fetch();
        this.input = this.$('#input');
        this.send = this.$("#send");
        this.media = this.$('#mediacont');
        this.register = this.$("#registre");
        if(msg) this.Conversa.add(msg);
        this.register.hide();
   },
   render: function(){

   },
   addOne: function(msg){
       this.Conversa.add(msg);
       var view = new MessageView({model:msg});
       this.$("#bubbles").append(view.render().el);
   },
   addOneSave: function(msg){
       var view = new MessageView({model:msg});
       view.save();
       this.$("#bubbles").append(view.render().el);
   },
   addAll: function(){
       this.Conversa.each(this.addOne,this);
       _.defer(this.createScroll);
   },
   saypress: function(e){
       if (e.keyCode != 13) return;
       if (!this.input.val()) return;
       this.say();
   },
   say: function(){
       var val = this.input.val();
       var view = this;
       if(val!=''){
            // Strip tags
            val = val.replace(/(<([^>]+)>)/ig,"");
            var msg = new Message({from:'me',body:val, time:new Date(), id:new Date().getTime()})
            this.Conversa.add(msg);
            val = val.replace(/\./ig,"");
            $.post('talk.php',{input:val,user:this.id}, function(r){
                    var msg = new Message({from:'you',body:r, time:new Date(), id:new Date().getTime()})
                    view.Conversa.add(msg);
                    view.input.val('');
                    _.defer(view.scrollDown);
            }).error(function(){
                    var msg = new Message({from:'you',body:'Lo siento, pero parece que no hay conexión, así que tendremos que dejar la charla para más tarde :(', time:new Date(), id:new Date().getTime()})
                    view.Conversa.add(msg);
                    view.input.val('');
                    _.defer(view.scrollDown);
            });
       }
   },
   createScroll: function(){
       setTimeout(function () {
            window.scroller = new iScroll('conversation', {hScrollbar:false, bounce:false})
                window.mscroller = new iScroll('mediadiv', {hScrollbar:false, bounce:false})
                window.scroller.scrollTo(0,-$("#bubbles").height(),0);
                $(window).bind('newmedia', window.refreshmedia);
	}, 0);
   },
   scrollDown: function(){
       setTimeout(function () {
		window.scroller.refresh();
                var lasth = parseInt($("#bubbles p").last().outerHeight())+10;
                lasth += parseInt($("#bubbles p").last().prev().outerHeight())+10;
                console.log(lasth);
                window.scroller.scrollTo(0,lasth,0, true);
                //$("#conversation").scrollTop($("#bubbles").height());
	}, 0);
   }
});
var scroller = false;
var mscroller = false;
function refreshmedia(){
   console.log('refreshing media');
   setTimeout(function () {
            window.mscroller.refresh();
    }, 0);
}
function c(str){
   console.log(str);
}<|endoftext|>


<commit_before>define(['map/clientlayer', 'map/labellayer', 'map/button', 'leaflet', 'map/activearea'],
  function (ClientLayer, LabelLayer, Button, L) {
    'use strict';

    var options = {
      worldCopyJump: true,
      zoomControl: true,
      minZoom: 0
    };

    return function (linkScale, sidebar, buttons) {
      var self = this;
      var savedView;

      var map;
      var layerControl;
      var baseLayers = {};

      function saveView() {
        savedView = {
          center: map.getCenter(),
          zoom: map.getZoom()
        };
      }

      function contextMenuOpenLayerMenu() {
        document.querySelector('.leaflet-control-layers').classList.add('leaflet-control-layers-expanded');
      }

      function mapActiveArea() {
        map.setActiveArea({
          position: 'absolute',
          left: sidebar.getWidth() + 'px',
          right: 0,
          top: 0,
          bottom: 0
        });
      }

      function setActiveArea() {
        setTimeout(mapActiveArea, 300);
      }

      var el = document.createElement('div');
      el.classList.add('map');

      map = L.map(el, options);
      mapActiveArea();

      var now = new Date();
      config.mapLayers.forEach(function (item, i) {
        if ((typeof item.config.start === 'number' && item.config.start <= now.getHours()) || (typeof item.config.end === 'number' && item.config.end > now.getHours())) {
          item.config.order = item.config.start * -1;
        } else {
          item.config.order = i;
        }
      });

      config.mapLayers = config.mapLayers.sort(function (a, b) {
        return a.config.order - b.config.order;
      });

      var layers = config.mapLayers.map(function (d) {
        return {
          'name': d.name,
          'layer': L.tileLayer(d.url, d.config)
        };
      });

      map.addLayer(layers[0].layer);

      layers.forEach(function (d) {
        baseLayers[d.name] = d.layer;
      });

      var button = new Button(map, buttons);

      map.on('locationfound', button.locationFound);
      map.on('locationerror', button.locationError);
      map.on('dragend', saveView);
      map.on('contextmenu', contextMenuOpenLayerMenu);

      if (config.geo) {
        [].forEach.call(config.geo, function (geo) {
          geo.json().then(function (result) {
            if (result) {
              L.geoJSON(result, geo.option).addTo(map);
            }
          });
        });
      }

      button.init();

      layerControl = L.control.layers(baseLayers, [], { position: 'bottomright' });
      layerControl.addTo(map);

      map.zoomControl.setPosition('topright');

      var clientLayer = new ClientLayer({ minZoom: config.clientZoom });
      clientLayer.addTo(map);
      clientLayer.setZIndex(5);

      var labelLayer = new LabelLayer({ minZoom: config.labelZoom });
      labelLayer.addTo(map);
      labelLayer.setZIndex(6);

      sidebar.button.addEventListener('visibility', setActiveArea);

      map.on('zoom', function () {
        clientLayer.redraw();
        labelLayer.redraw();
      });

      map.on('baselayerchange', function (e) {
        map.options.maxZoom = e.layer.options.maxZoom;
        clientLayer.options.maxZoom = map.options.maxZoom;
        labelLayer.options.maxZoom = map.options.maxZoom;
        if (map.getZoom() > map.options.maxZoom) {
          map.setZoom(map.options.maxZoom);
        }

        var style = document.querySelector('.css-mode:not([media="not"])');
        if (style && e.layer.options.mode !== '' && !style.classList.contains(e.layer.options.mode)) {
          style.media = 'not';
          labelLayer.updateLayer();
        }
        if (e.layer.options.mode) {
          var newStyle = document.querySelector('.css-mode.' + e.layer.options.mode);
          newStyle.media = '';
          newStyle.appendChild(document.createTextNode(''));
          labelLayer.updateLayer();
        }
      });

      map.on('load', function () {
        var inputs = document.querySelectorAll('.leaflet-control-layers-selector');
        [].forEach.call(inputs, function (input) {
          input.setAttribute('role', 'radiogroup');
          input.setAttribute('aria-label', input.nextSibling.innerHTML.trim());
        });
      });

      var nodeDict = {};
      var linkDict = {};
      var highlight;

      function resetMarkerStyles(nodes, links) {
        Object.keys(nodes).forEach(function (d) {
          nodes[d].resetStyle();
        });

        Object.keys(links).forEach(function (d) {
          links[d].resetStyle();
        });
      }

      function setView(bounds, zoom) {
        map.fitBounds(bounds, { maxZoom: (zoom ? zoom : config.nodeZoom) });
      }

      function goto(m) {
        var bounds;

        if ('getBounds' in m) {
          bounds = m.getBounds();
        } else {
          bounds = L.latLngBounds([m.getLatLng()]);
        }

        setView(bounds);

        return m;
      }

      function updateView(nopanzoom) {
        resetMarkerStyles(nodeDict, linkDict);
        var m;

        if (highlight !== undefined) {
          if (highlight.type === 'node' && nodeDict[highlight.o.node_id]) {
            m = nodeDict[highlight.o.node_id];
            m.setStyle(config.map.highlightNode);
          } else if (highlight.type === 'link' && linkDict[highlight.o.id]) {
            m = linkDict[highlight.o.id];
            m.setStyle(config.map.highlightLink);
          }
        }

        if (!nopanzoom) {
          if (m) {
            goto(m);
          } else if (savedView) {
            map.setView(savedView.center, savedView.zoom);
          } else {
            setView(config.fixedCenter);
          }
        }
      }

      self.setData = function setData(data) {
        nodeDict = {};
        linkDict = {};

        clientLayer.setData(data);
        labelLayer.setData(data, map, nodeDict, linkDict, linkScale);

        updateView(true);
      };

      self.resetView = function resetView() {
        button.disableTracking();
        highlight = undefined;
        updateView();
      };

      self.gotoNode = function gotoNode(d) {
        button.disableTracking();
        highlight = { type: 'node', o: d };
        updateView();
      };

      self.gotoLink = function gotoLink(d) {
        button.disableTracking();
        highlight = { type: 'link', o: d[0] };
        updateView();
      };

      self.gotoLocation = function gotoLocation(d) {
        button.disableTracking();
        map.setView([d.lat, d.lng], d.zoom);
      };

      self.destroy = function destroy() {
        button.clearButtons();
        sidebar.button.removeEventListener('visibility', setActiveArea);
        map.remove();

        if (el.parentNode) {
          el.parentNode.removeChild(el);
        }
      };

      self.render = function render(d) {
        d.appendChild(el);
        map.invalidateSize();
      };

      return self;
    };
  });
<commit_msg>Add {format} for webp support<commit_after>define(['map/clientlayer', 'map/labellayer', 'map/button', 'leaflet', 'map/activearea'],
  function (ClientLayer, LabelLayer, Button, L) {
    'use strict';

    var options = {
      worldCopyJump: true,
      zoomControl: true,
      minZoom: 0
    };

    return function (linkScale, sidebar, buttons) {
      var self = this;
      var savedView;

      var map;
      var layerControl;
      var baseLayers = {};

      function saveView() {
        savedView = {
          center: map.getCenter(),
          zoom: map.getZoom()
        };
      }

      function contextMenuOpenLayerMenu() {
        document.querySelector('.leaflet-control-layers').classList.add('leaflet-control-layers-expanded');
      }

      function mapActiveArea() {
        map.setActiveArea({
          position: 'absolute',
          left: sidebar.getWidth() + 'px',
          right: 0,
          top: 0,
          bottom: 0
        });
      }

      function setActiveArea() {
        setTimeout(mapActiveArea, 300);
      }

      var el = document.createElement('div');
      el.classList.add('map');

      map = L.map(el, options);
      mapActiveArea();

      var now = new Date();
      config.mapLayers.forEach(function (item, i) {
        if ((typeof item.config.start === 'number' && item.config.start <= now.getHours()) || (typeof item.config.end === 'number' && item.config.end > now.getHours())) {
          item.config.order = item.config.start * -1;
        } else {
          item.config.order = i;
        }
      });

      config.mapLayers = config.mapLayers.sort(function (a, b) {
        return a.config.order - b.config.order;
      });

      var layers = config.mapLayers.map(function (d) {
        return {
          'name': d.name,
          'layer': L.tileLayer(d.url.replace('{format}', document.createElement('canvas').toDataURL('image/webp').indexOf('data:image/webp') === 0 ? 'webp' : 'png'), d.config)
        };
      });

      map.addLayer(layers[0].layer);

      layers.forEach(function (d) {
        baseLayers[d.name] = d.layer;
      });

      var button = new Button(map, buttons);

      map.on('locationfound', button.locationFound);
      map.on('locationerror', button.locationError);
      map.on('dragend', saveView);
      map.on('contextmenu', contextMenuOpenLayerMenu);

      if (config.geo) {
        [].forEach.call(config.geo, function (geo) {
          geo.json().then(function (result) {
            if (result) {
              L.geoJSON(result, geo.option).addTo(map);
            }
          });
        });
      }

      button.init();

      layerControl = L.control.layers(baseLayers, [], { position: 'bottomright' });
      layerControl.addTo(map);

      map.zoomControl.setPosition('topright');

      var clientLayer = new ClientLayer({ minZoom: config.clientZoom });
      clientLayer.addTo(map);
      clientLayer.setZIndex(5);

      var labelLayer = new LabelLayer({ minZoom: config.labelZoom });
      labelLayer.addTo(map);
      labelLayer.setZIndex(6);

      sidebar.button.addEventListener('visibility', setActiveArea);

      map.on('zoom', function () {
        clientLayer.redraw();
        labelLayer.redraw();
      });

      map.on('baselayerchange', function (e) {
        map.options.maxZoom = e.layer.options.maxZoom;
        clientLayer.options.maxZoom = map.options.maxZoom;
        labelLayer.options.maxZoom = map.options.maxZoom;
        if (map.getZoom() > map.options.maxZoom) {
          map.setZoom(map.options.maxZoom);
        }

        var style = document.querySelector('.css-mode:not([media="not"])');
        if (style && e.layer.options.mode !== '' && !style.classList.contains(e.layer.options.mode)) {
          style.media = 'not';
          labelLayer.updateLayer();
        }
        if (e.layer.options.mode) {
          var newStyle = document.querySelector('.css-mode.' + e.layer.options.mode);
          newStyle.media = '';
          newStyle.appendChild(document.createTextNode(''));
          labelLayer.updateLayer();
        }
      });

      map.on('load', function () {
        var inputs = document.querySelectorAll('.leaflet-control-layers-selector');
        [].forEach.call(inputs, function (input) {
          input.setAttribute('role', 'radiogroup');
          input.setAttribute('aria-label', input.nextSibling.innerHTML.trim());
        });
      });

      var nodeDict = {};
      var linkDict = {};
      var highlight;

      function resetMarkerStyles(nodes, links) {
        Object.keys(nodes).forEach(function (d) {
          nodes[d].resetStyle();
        });

        Object.keys(links).forEach(function (d) {
          links[d].resetStyle();
        });
      }

      function setView(bounds, zoom) {
        map.fitBounds(bounds, { maxZoom: (zoom ? zoom : config.nodeZoom) });
      }

      function goto(m) {
        var bounds;

        if ('getBounds' in m) {
          bounds = m.getBounds();
        } else {
          bounds = L.latLngBounds([m.getLatLng()]);
        }

        setView(bounds);

        return m;
      }

      function updateView(nopanzoom) {
        resetMarkerStyles(nodeDict, linkDict);
        var m;

        if (highlight !== undefined) {
          if (highlight.type === 'node' && nodeDict[highlight.o.node_id]) {
            m = nodeDict[highlight.o.node_id];
            m.setStyle(config.map.highlightNode);
          } else if (highlight.type === 'link' && linkDict[highlight.o.id]) {
            m = linkDict[highlight.o.id];
            m.setStyle(config.map.highlightLink);
          }
        }

        if (!nopanzoom) {
          if (m) {
            goto(m);
          } else if (savedView) {
            map.setView(savedView.center, savedView.zoom);
          } else {
            setView(config.fixedCenter);
          }
        }
      }

      self.setData = function setData(data) {
        nodeDict = {};
        linkDict = {};

        clientLayer.setData(data);
        labelLayer.setData(data, map, nodeDict, linkDict, linkScale);

        updateView(true);
      };

      self.resetView = function resetView() {
        button.disableTracking();
        highlight = undefined;
        updateView();
      };

      self.gotoNode = function gotoNode(d) {
        button.disableTracking();
        highlight = { type: 'node', o: d };
        updateView();
      };

      self.gotoLink = function gotoLink(d) {
        button.disableTracking();
        highlight = { type: 'link', o: d[0] };
        updateView();
      };

      self.gotoLocation = function gotoLocation(d) {
        button.disableTracking();
        map.setView([d.lat, d.lng], d.zoom);
      };

      self.destroy = function destroy() {
        button.clearButtons();
        sidebar.button.removeEventListener('visibility', setActiveArea);
        map.remove();

        if (el.parentNode) {
          el.parentNode.removeChild(el);
        }
      };

      self.render = function render(d) {
        d.appendChild(el);
        map.invalidateSize();
      };

      return self;
    };
  });
<|endoftext|>