<commit_before>//========================================================================//
//======================== :: DF :: ======================================//
//========================================================================//
var DF = {
    M: {
        //types: ['Coin', 'Badminton', 'Baseball', 'Basketball', 'Soccer', 'Tennis', 'Volleyball'],
        types: ['shou', 'zuqiu', 'langan', 'lanqiu', 'feibiao'],
        moveSpeed: 0,
        maxPath: 0,
        scale: 0.2,
        maxPathMile: 0,
        scaleMile: 0.4,
        cutImgTimeFinal: 15,
        cutImgTime: 15,
        cutImgIndex: 0
    },
    P: {
        pathWidth: 0,
        moveSpeed: 0,
        jumpSpeedFinal: 5,
        jumpSpeed: 5,
        gravity: 0.25,
        cutImgTimeFinal: 25,
        cutImgTime: 4,
        cutImgIndex: 0
    },
    Miles: ['05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55', '60', '65', '70', '75', '80', '85', '90', '95', '100'],
    AddTime: 1
};
//========================================================================//
//======================== :: Player :: ==================================//
//========================================================================//
// 创建
var Player = function() {
    GAME.Sprite.apply(this, ['player', 'images/player0.png', DF.P.pathWidth, DF.P.pathWidth * 2, 3]);
    var x = winWidth / 2;
    var y = winHeight - DF.M.maxPath / 10 * 7;
    this.setAnchorPoint(0.5, 1);
    this.setPosition(x, y);
    this.last = {
        x: this.getPositionX(),
        y: this.getPositionY()
    };
    this.first = {
        x: this.getPositionX(),
        y: this.getPositionY()
    };
    this.images = [];
    var imageLength = 2,
        imageName = 'player';
    for (var i = 0; i < imageLength; i++) {
        var image = new Image();
        image.width = this.width;
        image.height = this.height;
        image.src = 'images/' + imageName + i + '.png';
        this.images.push(image);
    }
    var jImage = new Image();
    jImage.width = this.width;
    jImage.height = this.height;
    jImage.src = 'images/player_jump.png';
    this.images.push(jImage);
    this.moving = false;
    this.moveDirect = 0;
    this.jumping = false;
    this.jumpDirect = 0;
    this.hurt = false;
    this.pathIndex = 2;
};
// 更新位置
Player.prototype.update = function() {
    if (this.moving) {
        this.move();
    }
    if (this.jumping) {
        this.image = this.images[2];
        this.jump();
    }
    if (!this.jumping && !this.hurt) {
        this.image = this.cutImg();
    }
};
// 切图
Player.prototype.cutImg = function() {
    if (DF.P.cutImgTime === 0) {
        DF.P.cutImgIndex++;
        if (DF.P.cutImgIndex >= 2) {
            DF.P.cutImgIndex = 0;
        }
        DF.P.cutImgTime = DF.P.cutImgTimeFinal;
    }
    DF.P.cutImgTime--;
    return this.images[DF.P.cutImgIndex];
};
// Jump
Player.prototype.jump = function() {
    if (this.jumpDirect == 1) {
        this.setPositionY(this.getPositionY() - DF.P.jumpSpeed);
        DF.P.jumpSpeed -= DF.P.gravity;
        if (DF.P.jumpSpeed <= 0) {
            this.jumpDirect = -1;
        }
    } else if (this.jumpDirect == -1) {
        DF.P.jumpSpeed += DF.P.gravity;
        this.setPositionY(this.getPositionY() + DF.P.jumpSpeed);
        if (DF.P.jumpSpeed >= DF.P.jumpSpeedFinal) {
            this.jumpDirect = 0;
        }
    } else {
        DF.P.cutImgTime = DF.P.cutImgTimeFinal; //fix cutImage
        this.jumping = false;
        DF.P.jumpSpeed = DF.P.jumpSpeedFinal;
        this.setPosition(this.last.x, this.last.y);
    }
};
// Move
Player.prototype.move = function() {
    if (Math.abs(this.getPositionX() - this.last.x) >= DF.P.pathWidth) {
        this.moveDirect = 0;
        this.moving = false;
        this.last.x = this.getPositionX();
        if (this.last.x < this.first.x && Math.abs(this.last.x - this.first.x) > 0.01) {
            this.pathIndex = 1;
        } else if (this.last.x > this.first.x && Math.abs(this.last.x - this.first.x) > 0.01) {
            this.pathIndex = 3;
        } else {
            this.pathIndex = 2;
        }
    }
    if (this.moveDirect > 0 && this.pathIndex < 3) {
        this.setPositionX(this.getPositionX() + DF.P.moveSpeed);
    } else if (this.moveDirect < 0 && this.pathIndex > 1) {
        this.setPositionX(this.getPositionX() - DF.P.moveSpeed);
    } else {
        this.moving = false;
    }
};
//========================================================================//
//======================== :: Shadow :: ==================================//
//========================================================================//
var Shadow = function() {
    GAME.Sprite.apply(this, ['shadow', 'images/shadow.png', DF.P.pathWidth + 10, DF.P.pathWidth + 10, 1]);
    var x = winWidth / 2;
    var y = winHeight - DF.M.maxPath / 10 * 7 + 40;
    this.setAnchorPoint(0.5, 1);
    this.setPosition(x, y);
    this.last = {
        x: this.getPositionX(),
        y: this.getPositionY()
    };
    this.first = {
        x: this.getPositionX(),
        y: this.getPositionY()
    };
    this.moving = false;
    this.moveDirect = 0;
    this.pathIndex = 2;
};
// 更新位置
Shadow.prototype.update = function() {
    if (this.moving) {
        this.move();
    }
};
// Move
Shadow.prototype.move = function() {
    if (Math.abs(this.getPositionX() - this.last.x) >= DF.P.pathWidth) {
        this.moveDirect = 0;
        this.moving = false;
        this.last.x = this.getPositionX();
        if (this.last.x < this.first.x && Math.abs(this.last.x - this.first.x) > 0.01) {
            this.pathIndex = 1;
        } else if (this.last.x > this.first.x && Math.abs(this.last.x - this.first.x) > 0.01) {
            this.pathIndex = 3;
        } else {
            this.pathIndex = 2;
        }
    }
    if (this.moveDirect > 0 && this.pathIndex < 3) {
        this.setPositionX(this.getPositionX() + DF.P.moveSpeed);
    } else if (this.moveDirect < 0 && this.pathIndex > 1) {
        this.setPositionX(this.getPositionX() - DF.P.moveSpeed);
    } else {
        this.moving = false;
    }
};
//========================================================================//
//======================== :: Monster :: =================================//
//========================================================================//
// 创建
var Monster = function(type, pathIndex, width, height, index) {
    var zindex = 2;
    if (type === DF.M.types[4] || type === 'zhongdian') {
        zindex = 4;
    }
    GAME.Sprite.apply(this, [type + index, 'images/' + type + '0.png', width, height, zindex]);
    var x = pathIndex == 1 ? getScaleX(xd1) : (pathIndex == 3 ? getScaleX(xd2) : winWidth / 2);
    if (type === DF.M.types[2]) {
        x = pathIndex == 1 ? winWidth / 3 : winWidth / 3 * 2;
    }
    var y = winHeight;
    this.setPosition(x, y);
    this.images = [];
    var imageLength = 1;
    if (type === DF.M.types[1] || type === DF.M.types[3]) {
        imageLength = 4;
    }
    for (var i = 0; i < imageLength; i++) {
        var image = new Image();
        image.width = this.width;
        image.height = this.height;
        image.src = 'images/' + type + i + '.png';
        this.images.push(image);
    }
    this.image = this.images[0];
    this.type = type;
    this.pathIndex = pathIndex;
    this.index = index;
    this.alive = true;
};
//更新位置
Monster.prototype.update = function(target) {
    var distH = (this.getCurrentHeight()) * 0.5,
        distW = (this.getCurrentWidth()) * 0.5;
    if (target.jumping) {
        if (this.type === DF.M.types[4]) {
            if (this.getPositionY() - target.getPositionY() < distH && this.getPositionY() - target.getPositionY() > 0) {
                if (Math.abs(this.getPositionX() - target.getPositionX()) < distW) {
                    this.crash();
                }
            }
        }
    } else {
        if (this.getPositionY() - target.getPositionY() < distH && this.getPositionY() - target.getPositionY() > 0) {
            if (Math.abs(this.getPositionX() - target.getPositionX()) < distW) {
                this.crash();
            }
        }
    }
    this.move();
};
//MOVE
Monster.prototype.move = function() {
    if (!this.alive) {
        return false;
        delete monsters[this.index];
        this.removeFromGlobal();
    }
    var x, y;
    switch (this.pathIndex) {
        case 1:
            x = this.getPositionX() + DF.M.moveSpeed * this.k;
            break;
        case 2:
            x = this.getPositionX();
            break;
        case 3:
            x = this.getPositionX() - DF.M.moveSpeed * this.k;
            break;
    }
    y = this.getPositionY() - DF.M.moveSpeed;
    if (winHeight - this.getPositionY() > DF.M.maxPath) {
        this.alive = false;
        delete monsters[this.index];
        this.removeFromGlobal();
    } else {
        this.image = this.cutImg();
        var ks = DF.M.scale + (this.getPositionY() - getScaleY(yl)) * (1 - DF.M.scale) / getScaleY(HEIGHT - yl);
        this.setScale(ks, ks);
        this.setPosition(x, y);
    }
};
// 切图
Monster.prototype.cutImg = function() {
    if (this.type === DF.M.types[1] || this.type === DF.M.types[3]) {
        if (DF.M.cutImgTime === 0) {
            DF.M.cutImgIndex++;
            if (DF.M.cutImgIndex >= 3) {
                DF.M.cutImgIndex = 0;
            }
            DF.M.cutImgTime = DF.M.cutImgTimeFinal;
        }
        DF.M.cutImgTime--;
        return this.images[DF.M.cutImgIndex];
    } else {
        return this.images[0];
    }
};
//crash
Monster.prototype.crash = function() {
    if (this.type != 'zhongdian') {
        this.alive = false;
        delete monsters[this.index];
        this.removeFromGlobal();
        if (this.type === DF.M.types[0]) {
            popupTip('gmf+1', 'fc_or');
            gmfCounts++;
            DF.AddTime = 1;
            if (isPlayMusic) {
                musicGmf.play();
            }
        } else {
            popupTip('+' + DF.AddTime.toFixed(1) + 's');
            DF.AddTime += 0.1;
            startTime -= 1000 * DF.AddTime;
            if (isPlayMusic) {
                musicCrash.play();
            }
        }
    } else {
        setTimeout(function() {
            FinishedGame = true;
        }, 100);
    }
};
//========================================================================//
//======================== :: AsideMile :: ===============================//
//========================================================================//
// 创建
var AsideMile = function(type, width, height, index) {
    GAME.Sprite.apply(this, [type + index, 'images/number/' + type + '.png', width, height, 0]);
    this.k = Math.abs((getScaleX(xA) - getScaleX(3)) / (winHeight - getScaleY(yl)));
    this.index = index;
};
//更新位置
AsideMile.prototype.update = function(target) {
    this.move();
};
//MOVE
AsideMile.prototype.move = function() {
    var x, y;
    x = this.getPositionX() + DF.M.moveSpeed * this.k;
    y = this.getPositionY() - DF.M.moveSpeed;
    if (winHeight - this.getPositionY() > DF.M.maxPathMile) {
        delete asideMiles[this.index];
        this.removeFromGlobal();
    } else {
        var ks = DF.M.scaleMile + (this.getPositionY() - getScaleY(yl)) * (1 - DF.M.scaleMile) / getScaleY(HEIGHT - yl);
        this.setScale(ks, ks);
        this.setPosition(x, y);
    }
};<commit_msg>fix ending bug<commit_after>//========================================================================//
//======================== :: DF :: ======================================//
//========================================================================//
var DF = {
    M: {
        //types: ['Coin', 'Badminton', 'Baseball', 'Basketball', 'Soccer', 'Tennis', 'Volleyball'],
        types: ['shou', 'zuqiu', 'langan', 'lanqiu', 'feibiao'],
        moveSpeed: 0,
        maxPath: 0,
        scale: 0.2,
        maxPathMile: 0,
        scaleMile: 0.4,
        cutImgTimeFinal: 15,
        cutImgTime: 15,
        cutImgIndex: 0
    },
    P: {
        pathWidth: 0,
        moveSpeed: 0,
        jumpSpeedFinal: 5,
        jumpSpeed: 5,
        gravity: 0.25,
        cutImgTimeFinal: 25,
        cutImgTime: 4,
        cutImgIndex: 0
    },
    Miles: ['05', '10', '15', '20', '25', '30', '35', '40', '45', '50', '55', '60', '65', '70', '75', '80', '85', '90', '95', '100'],
    AddTime: 1
};
//========================================================================//
//======================== :: Player :: ==================================//
//========================================================================//
// 创建
var Player = function() {
    GAME.Sprite.apply(this, ['player', 'images/player0.png', DF.P.pathWidth, DF.P.pathWidth * 2, 3]);
    var x = winWidth / 2;
    var y = winHeight - DF.M.maxPath / 10 * 7;
    this.setAnchorPoint(0.5, 1);
    this.setPosition(x, y);
    this.last = {
        x: this.getPositionX(),
        y: this.getPositionY()
    };
    this.first = {
        x: this.getPositionX(),
        y: this.getPositionY()
    };
    this.images = [];
    var imageLength = 2,
        imageName = 'player';
    for (var i = 0; i < imageLength; i++) {
        var image = new Image();
        image.width = this.width;
        image.height = this.height;
        image.src = 'images/' + imageName + i + '.png';
        this.images.push(image);
    }
    var jImage = new Image();
    jImage.width = this.width;
    jImage.height = this.height;
    jImage.src = 'images/player_jump.png';
    this.images.push(jImage);
    this.moving = false;
    this.moveDirect = 0;
    this.jumping = false;
    this.jumpDirect = 0;
    this.hurt = false;
    this.pathIndex = 2;
};
// 更新位置
Player.prototype.update = function() {
    if (this.moving) {
        this.move();
    }
    if (this.jumping) {
        this.image = this.images[2];
        this.jump();
    }
    if (!this.jumping && !this.hurt) {
        this.image = this.cutImg();
    }
};
// 切图
Player.prototype.cutImg = function() {
    if (DF.P.cutImgTime === 0) {
        DF.P.cutImgIndex++;
        if (DF.P.cutImgIndex >= 2) {
            DF.P.cutImgIndex = 0;
        }
        DF.P.cutImgTime = DF.P.cutImgTimeFinal;
    }
    DF.P.cutImgTime--;
    return this.images[DF.P.cutImgIndex];
};
// Jump
Player.prototype.jump = function() {
    if (this.jumpDirect == 1) {
        this.setPositionY(this.getPositionY() - DF.P.jumpSpeed);
        DF.P.jumpSpeed -= DF.P.gravity;
        if (DF.P.jumpSpeed <= 0) {
            this.jumpDirect = -1;
        }
    } else if (this.jumpDirect == -1) {
        DF.P.jumpSpeed += DF.P.gravity;
        this.setPositionY(this.getPositionY() + DF.P.jumpSpeed);
        if (DF.P.jumpSpeed >= DF.P.jumpSpeedFinal) {
            this.jumpDirect = 0;
        }
    } else {
        DF.P.cutImgTime = DF.P.cutImgTimeFinal; //fix cutImage
        this.jumping = false;
        DF.P.jumpSpeed = DF.P.jumpSpeedFinal;
        this.setPosition(this.last.x, this.last.y);
    }
};
// Move
Player.prototype.move = function() {
    if (Math.abs(this.getPositionX() - this.last.x) >= DF.P.pathWidth) {
        this.moveDirect = 0;
        this.moving = false;
        this.last.x = this.getPositionX();
        if (this.last.x < this.first.x && Math.abs(this.last.x - this.first.x) > 0.01) {
            this.pathIndex = 1;
        } else if (this.last.x > this.first.x && Math.abs(this.last.x - this.first.x) > 0.01) {
            this.pathIndex = 3;
        } else {
            this.pathIndex = 2;
        }
    }
    if (this.moveDirect > 0 && this.pathIndex < 3) {
        this.setPositionX(this.getPositionX() + DF.P.moveSpeed);
    } else if (this.moveDirect < 0 && this.pathIndex > 1) {
        this.setPositionX(this.getPositionX() - DF.P.moveSpeed);
    } else {
        this.moving = false;
    }
};
//========================================================================//
//======================== :: Shadow :: ==================================//
//========================================================================//
var Shadow = function() {
    GAME.Sprite.apply(this, ['shadow', 'images/shadow.png', DF.P.pathWidth + 10, DF.P.pathWidth + 10, 1]);
    var x = winWidth / 2;
    var y = winHeight - DF.M.maxPath / 10 * 7 + 40;
    this.setAnchorPoint(0.5, 1);
    this.setPosition(x, y);
    this.last = {
        x: this.getPositionX(),
        y: this.getPositionY()
    };
    this.first = {
        x: this.getPositionX(),
        y: this.getPositionY()
    };
    this.moving = false;
    this.moveDirect = 0;
    this.pathIndex = 2;
};
// 更新位置
Shadow.prototype.update = function() {
    if (this.moving) {
        this.move();
    }
};
// Move
Shadow.prototype.move = function() {
    if (Math.abs(this.getPositionX() - this.last.x) >= DF.P.pathWidth) {
        this.moveDirect = 0;
        this.moving = false;
        this.last.x = this.getPositionX();
        if (this.last.x < this.first.x && Math.abs(this.last.x - this.first.x) > 0.01) {
            this.pathIndex = 1;
        } else if (this.last.x > this.first.x && Math.abs(this.last.x - this.first.x) > 0.01) {
            this.pathIndex = 3;
        } else {
            this.pathIndex = 2;
        }
    }
    if (this.moveDirect > 0 && this.pathIndex < 3) {
        this.setPositionX(this.getPositionX() + DF.P.moveSpeed);
    } else if (this.moveDirect < 0 && this.pathIndex > 1) {
        this.setPositionX(this.getPositionX() - DF.P.moveSpeed);
    } else {
        this.moving = false;
    }
};
//========================================================================//
//======================== :: Monster :: =================================//
//========================================================================//
// 创建
var Monster = function(type, pathIndex, width, height, index) {
    var zindex = 2;
    if (type === DF.M.types[4] || type === 'zhongdian') {
        zindex = 4;
    }
    GAME.Sprite.apply(this, [type + index, 'images/' + type + '0.png', width, height, zindex]);
    var x = pathIndex == 1 ? getScaleX(xd1) : (pathIndex == 3 ? getScaleX(xd2) : winWidth / 2);
    if (type === DF.M.types[2]) {
        x = pathIndex == 1 ? winWidth / 3 : winWidth / 3 * 2;
    }
    var y = winHeight;
    this.setPosition(x, y);
    this.images = [];
    var imageLength = 1;
    if (type === DF.M.types[1] || type === DF.M.types[3]) {
        imageLength = 4;
    }
    for (var i = 0; i < imageLength; i++) {
        var image = new Image();
        image.width = this.width;
        image.height = this.height;
        image.src = 'images/' + type + i + '.png';
        this.images.push(image);
    }
    this.image = this.images[0];
    this.type = type;
    this.pathIndex = pathIndex;
    this.index = index;
    this.alive = true;
};
//更新位置
Monster.prototype.update = function(target) {
    var distH = (this.getCurrentHeight()) * 0.5,
        distW = (this.getCurrentWidth()) * 0.5;
    if (this.type === 'zhongdian') {
        if (this.getPositionY() - target.getPositionY() < -distH / 2) {
            FinishedGame = true;
        }
    }
    if (target.jumping) {
        if (this.type === DF.M.types[4]) {
            if (this.getPositionY() - target.getPositionY() < distH && this.getPositionY() - target.getPositionY() > 0) {
                if (Math.abs(this.getPositionX() - target.getPositionX()) < distW) {
                    this.crash();
                }
            }
        }
    } else {
        if (this.getPositionY() - target.getPositionY() < distH && this.getPositionY() - target.getPositionY() > 0) {
            if (Math.abs(this.getPositionX() - target.getPositionX()) < distW) {
                this.crash();
            }
        }
    }
    this.move();
};
//MOVE
Monster.prototype.move = function() {
    if (!this.alive) {
        return false;
        delete monsters[this.index];
        this.removeFromGlobal();
    }
    var x, y;
    switch (this.pathIndex) {
        case 1:
            x = this.getPositionX() + DF.M.moveSpeed * this.k;
            break;
        case 2:
            x = this.getPositionX();
            break;
        case 3:
            x = this.getPositionX() - DF.M.moveSpeed * this.k;
            break;
    }
    y = this.getPositionY() - DF.M.moveSpeed;
    if (winHeight - this.getPositionY() > DF.M.maxPath) {
        this.alive = false;
        delete monsters[this.index];
        this.removeFromGlobal();
    } else {
        this.image = this.cutImg();
        var ks = DF.M.scale + (this.getPositionY() - getScaleY(yl)) * (1 - DF.M.scale) / getScaleY(HEIGHT - yl);
        this.setScale(ks, ks);
        this.setPosition(x, y);
    }
};
// 切图
Monster.prototype.cutImg = function() {
    if (this.type === DF.M.types[1] || this.type === DF.M.types[3]) {
        if (DF.M.cutImgTime === 0) {
            DF.M.cutImgIndex++;
            if (DF.M.cutImgIndex >= 3) {
                DF.M.cutImgIndex = 0;
            }
            DF.M.cutImgTime = DF.M.cutImgTimeFinal;
        }
        DF.M.cutImgTime--;
        return this.images[DF.M.cutImgIndex];
    } else {
        return this.images[0];
    }
};
//crash
Monster.prototype.crash = function() {
    if (this.type != 'zhongdian') {
        this.alive = false;
        delete monsters[this.index];
        this.removeFromGlobal();
        if (this.type === DF.M.types[0]) {
            popupTip('gmf+1', 'fc_or');
            gmfCounts++;
            DF.AddTime = 1;
            if (isPlayMusic) {
                musicGmf.play();
            }
        } else {
            popupTip('+' + DF.AddTime.toFixed(1) + 's');
            DF.AddTime += 0.1;
            startTime -= 1000 * DF.AddTime;
            if (isPlayMusic) {
                musicCrash.play();
            }
        }
    }
};
//========================================================================//
//======================== :: AsideMile :: ===============================//
//========================================================================//
// 创建
var AsideMile = function(type, width, height, index) {
    GAME.Sprite.apply(this, [type + index, 'images/number/' + type + '.png', width, height, 0]);
    this.k = Math.abs((getScaleX(xA) - getScaleX(3)) / (winHeight - getScaleY(yl)));
    this.index = index;
};
//更新位置
AsideMile.prototype.update = function(target) {
    this.move();
};
//MOVE
AsideMile.prototype.move = function() {
    var x, y;
    x = this.getPositionX() + DF.M.moveSpeed * this.k;
    y = this.getPositionY() - DF.M.moveSpeed;
    if (winHeight - this.getPositionY() > DF.M.maxPathMile) {
        delete asideMiles[this.index];
        this.removeFromGlobal();
    } else {
        var ks = DF.M.scaleMile + (this.getPositionY() - getScaleY(yl)) * (1 - DF.M.scaleMile) / getScaleY(HEIGHT - yl);
        this.setScale(ks, ks);
        this.setPosition(x, y);
    }
};<|endoftext|>


<commit_before>function processInput() {
  var jump = jumpButton.isDown || cursors.up.isDown;
  var run = runButton.isDown;
  var left = cursors.left.isDown;
  var right = cursors.right.isDown;

  if (gamepadConnected) {
    jump |= buttonA.isDown;
    run |= buttonX.isDown || buttonR2.isDown;
    left |= buttonDPadLeft.isDown;
    right |= buttonDPadRight.isDown;
  }

  return {
    jump: jump,
    run: run,
    left: left,
    right: right
  };
}

var grabbing;

function grab(box) {
    grabbing = box;
}

function jump() {
  if (curState != 'Game') {
    return;
  }

  var input = processInput();

  //  Allow the player to jump if they are touching the ground.
  if (player.body.touching.down) {
    player.body.velocity.y = -jumpSpeed;
  }

  // walljumps TODO: only works if holding left/right :(
  else if (player.body.touching.left) {
    player.body.velocity.y = -jumpSpeed;
    player.body.velocity.x = input.run ? runSpeed : maxSpeed;
  } else if (player.body.touching.right) {
    player.body.velocity.y = -jumpSpeed;
    player.body.velocity.x = input.run ? -runSpeed : -maxSpeed;
  }
}

function playerMovement() {
  if (grabbing) {
      grabbing.body.position = new Phaser.Point(player.body.position.x + 10, player.body.position.y - 10);
  }
  var input = processInput();

  if (grabbing && !input.run) {
      grabbing.body.velocity.x = player.body.velocity.x * bouncyThrowMultiplier;
      grabbing = null;
      console.log(grabbing);
  }

  // set acceleration to 0.
  // below code will set it to something else if we still want to move
  player.body.acceleration.x = 0;

  if(input.run) {
    player.body.maxVelocity.x = runSpeed;
  } else {
    player.body.maxVelocity.x = maxSpeed;
  }

  if (input.left) {
    //  Move to the left
    player.body.acceleration.x = input.run ? -runAccel : -accel;

    // turn instantly if we're on the ground
    if (player.body.touching.down) {
      if (player.body.velocity.x > 0) {
        player.body.velocity.x = 0;
      }
    }
  } else if (input.right) {
    //  Move to the right
    player.body.acceleration.x = input.run ? runAccel : accel;

    // turn instantly if we're on the ground
    if (player.body.touching.down) {
      if (player.body.velocity.x < 0) {
        player.body.velocity.x = 0;
      }
    }
  } else {
    if (player.body.touching.down) {
      player.body.velocity.x = 0;
    }
    //  Stand still
    //player.animations.stop();

    //player.frame = 4;
  }

  if (!input.jump) {
    player.body.velocity.y = Math.max(0, player.body.velocity.y);
  }

  // out of bounds check for player, acts as win condition
  if (player.body.position.x + player.body.width  < game.world.bounds.x ||
      player.body.position.y + player.body.height < game.world.bounds.y ||
      player.body.position.x > game.world.bounds.width ||
      player.body.position.y > game.world.bounds.height) {
    if (++levelId == levels.length) {
      console.log('YOU\'RE WINNER!');
      levelId = 0;
    }
    saveTime(levelId - 1);
    loadLevel(levelId);
    startTimer();
    spawnPlayer();
  }
}

function spawnPlayer() {
  player = game.add.sprite(playerSpawn.x, playerSpawn.y, 'player');
  player.scale.setTo(0.25, 0.25);

  //  We need to enable physics on the player
  game.physics.arcade.enable(player);

  //  Player physics properties. Give the little guy a slight bounce.
  //player.body.bounce.y = 0.2;
  player.body.maxVelocity.x = maxSpeed;
  player.body.maxVelocity.y = maxYVelocity;
  player.body.gravity.y = gravity;

  // We allow out of bounds as that is our current win condition
  player.body.collideWorldBounds = false;

  //  Our two animations, walking left and right.
  player.animations.add('left', [3, 2], 10, true);
  player.animations.add('right', [0, 1], 10, true);
  player.animations.add('jump', [4], 10, true);
  player.animations.add('stand', [5], 10, true);

  game.camera.follow(player);
}
<commit_msg>Removed incorrect non-breaking space which caused the game to crash<commit_after>function processInput() {
  var jump = jumpButton.isDown || cursors.up.isDown;
  var run = runButton.isDown;
  var left = cursors.left.isDown;
  var right = cursors.right.isDown;

  if (gamepadConnected) {
    jump |= buttonA.isDown;
    run |= buttonX.isDown || buttonR2.isDown;
    left |= buttonDPadLeft.isDown;
    right |= buttonDPadRight.isDown;
  }

  return {
    jump: jump,
    run: run,
    left: left,
    right: right
  };
}

var grabbing;

function grab(box) {
    grabbing = box;
}

function jump() {
  if (curState != 'Game') {
    return;
  }

  var input = processInput();

  //  Allow the player to jump if they are touching the ground.
  if (player.body.touching.down) {
    player.body.velocity.y = -jumpSpeed;
  }

  // walljumps TODO: only works if holding left/right :(
  else if (player.body.touching.left) {
    player.body.velocity.y = -jumpSpeed;
    player.body.velocity.x = input.run ? runSpeed : maxSpeed;
  } else if (player.body.touching.right) {
    player.body.velocity.y = -jumpSpeed;
    player.body.velocity.x = input.run ? -runSpeed : -maxSpeed;
  }
}

function playerMovement() {
  if (grabbing) {
      grabbing.body.position = new Phaser.Point(player.body.position.x + 10, player.body.position.y - 10);
  }
  var input = processInput();

  if (grabbing && !input.run) {
      grabbing.body.velocity.x = player.body.velocity.x * bouncyThrowMultiplier;
      grabbing = null;
      console.log(grabbing);
  }

  // set acceleration to 0.
  // below code will set it to something else if we still want to move
  player.body.acceleration.x = 0;

  if(input.run) {
    player.body.maxVelocity.x = runSpeed;
  } else {
    player.body.maxVelocity.x = maxSpeed;
  }

  if (input.left) {
    //  Move to the left
    player.body.acceleration.x = input.run ? -runAccel : -accel;

    // turn instantly if we're on the ground
    if (player.body.touching.down) {
      if (player.body.velocity.x > 0) {
        player.body.velocity.x = 0;
      }
    }
  } else if (input.right) {
    //  Move to the right
    player.body.acceleration.x = input.run ? runAccel : accel;

    // turn instantly if we're on the ground
    if (player.body.touching.down) {
      if (player.body.velocity.x < 0) {
        player.body.velocity.x = 0;
      }
    }
  } else {
    if (player.body.touching.down) {
      player.body.velocity.x = 0;
    }
    //  Stand still
    //player.animations.stop();

    //player.frame = 4;
  }

  if (!input.jump) {
    player.body.velocity.y = Math.max(0, player.body.velocity.y);
  }

  // out of bounds check for player, acts as win condition
  if (player.body.position.x + player.body.width  < game.world.bounds.x ||
      player.body.position.y + player.body.height < game.world.bounds.y ||
      player.body.position.x > game.world.bounds.width ||
      player.body.position.y > game.world.bounds.height) {
    if (++levelId == levels.length) {
      console.log('YOU\'RE WINNER!');
      levelId = 0;
    }
    saveTime(levelId - 1);
    loadLevel(levelId);
    startTimer();
    spawnPlayer();
  }
}

function spawnPlayer() {
  player = game.add.sprite(playerSpawn.x, playerSpawn.y, 'player');
  player.scale.setTo(0.25, 0.25);

  //  We need to enable physics on the player
  game.physics.arcade.enable(player);

  //  Player physics properties. Give the little guy a slight bounce.
  //player.body.bounce.y = 0.2;
  player.body.maxVelocity.x = maxSpeed;
  player.body.maxVelocity.y = maxYVelocity;
  player.body.gravity.y = gravity;

  // We allow out of bounds as that is our current win condition
  player.body.collideWorldBounds = false;

  //  Our two animations, walking left and right.
  player.animations.add('left', [3, 2], 10, true);
  player.animations.add('right', [0, 1], 10, true);
  player.animations.add('jump', [4], 10, true);
  player.animations.add('stand', [5], 10, true);

  game.camera.follow(player);
}
<|endoftext|>


<commit_before>var iphone4sLCD =      55;
var iphone5sGlass =    45;
var iphone5sLCD =      60;
var iphone6Glass =     49;
var iphone6LCD =       60;
var iphone6PlusGlass = 60;
var iphone6PlusLCD =   69;
var iphone6SGlass =    60;
var iphone6SLCD =      79;
var iphone6SPlusGlass= 70;
var iphone6SPlusLCD =  85;
var iphone7Glass =     79;
var iphone7LCD =       89;
var iphone7PlusGlass = 95;
var iphone7PlusLCD =   99;
var iphone8Glass =     99;
var iphone8LCD =       110;
var iphone8PlusGlass = 109;
var iphone8PlusLCD =   120;
var ipad1Glass =       90;
var ipad234Glass =     85;
var ipadMiniGlass =    75;
var ipadAirGlass =     90;
var ipadAir2Glass =    195;
var ipadAir2LCD =      230;

//Samsung
var galaxyS3LCD =      80;
var galaxyS4Glass =    45;
var galaxyS4LCD =      90;
var galaxyS5Glass =    95;
var galaxyS5LCD =      135;
var galaxyS5NeoGlass =  85;
var galaxyS5NeoLCD =   155;
var galaxyS6Glass =    109;
var galaxyS6LCD =      180;
var galaxyS6EdgeLCD =  175;
var galaxyS7Glass =    120;
var galaxyS7LCD =      210;
var galaxyS7EdgeLCD =  300;
var galaxyS8Glass =    205;
var galaxyS8LCD =      255;
var galaxyS8PGlass =   240;
var galaxyS8PLCD =     335;
var galaxyNote3Glass = 80;
var galaxyNote3LCD =   160;
var galaxyNote4Glass = 85;
var galaxyNote4LCD =   175;
var galaxyNote5Glass = 130;
var galaxyNote5LCD =   215;
//LG
var nexus4Glass =     75;
var nexus4LCD =       85;
var nexus5LCD =       65;
var nexus5XLCD =      75;
var LGG2Glass =       85;
var LGG2LCD =         95;
var LGG3Glass =       75;
var LGG3LCD =         80;
var LGG4LCD =         75;
var LGG5LCD =         80;
var V20Glass =        135;
var V20LCD =          140;

//OnePlus
var OnePlus1LCD =  100;
var OnePlus2LCD = 110;
var OnePlus3LCD =  175;
var OnePlus5LCD = 210;
var OnePlus5TLCD = 175;
var OnePlusXLCD = 215;
var OnePlus6LCD = 230;

//Sony
var Z3LCD =            100;
var Z4LCD =            115;
var Z5LCD =            120;

//Blackberry
var bbZ10 =            45;
var bbZ30 =            105;
var bbQ10 =            50;
var bbQ20 =            80;
var bbQ30 =            130;

//HTC
var M9LCD =            100;
var M10LCD =           120;

//Huawei
var mate7LCD =         105;
var mate8LCD =         110;
var mate9LCD =         115;
var p9LCD =            105;
var p10LCD =           125;
var huaweiG7LCD =      105;
var p20LCD=            210;
var p20PROLCD=         370;
var p20LiteLCD =       135;

//Pixel
var pixelLCD =         140;
var pixelXLLCD =       160;
var pixel2LCD =        210;
var pixel2XLLCD =      225;
var Nexus6LCD =        190;
var Nexus6PLCD =       170;

//Services
var diagnostic =         25;
var waterDamageL =       65;
var waterDamageH =       75;
var waterDamageSamsung = 75;
var advancedDiagnostic = 60;
var systemRestore =      50;
<commit_msg>Update prices.js<commit_after>var iphone4sLCD =      55;
var iphone5sGlass =    45;
var iphone5sLCD =      60;
var iphone6Glass =     49;
var iphone6LCD =       60;
var iphone6PlusGlass = 60;
var iphone6PlusLCD =   69;
var iphone6SGlass =    60;
var iphone6SLCD =      79;
var iphone6SPlusGlass= 70;
var iphone6SPlusLCD =  85;
var iphone7Glass =     79;
var iphone7LCD =       89;
var iphone7PlusGlass = 95;
var iphone7PlusLCD =   99;
var iphone8Glass =     99;
var iphone8LCD =       110;
var iphone8PlusGlass = 109;
var iphone8PlusLCD =   120;
var ipad1Glass =       90;
var ipad234Glass =     85;
var ipadMiniGlass =    75;
var ipadAirGlass =     90;
var ipadAir2Glass =    195;
var ipadAir2LCD =      230;

//Samsung
var galaxyS3LCD =      80;
var galaxyS4Glass =    45;
var galaxyS4LCD =      90;
var galaxyS5Glass =    95;
var galaxyS5LCD =      135;
var galaxyS5NeoGlass =  85;
var galaxyS5NeoLCD =   155;
var galaxyS6Glass =    109;
var galaxyS6LCD =      180;
var galaxyS6EdgeLCD =  175;
var galaxyS7Glass =    120;
var galaxyS7LCD =      210;
var galaxyS7EdgeLCD =  280;
var galaxyS8Glass =    205;
var galaxyS8LCD =      255;
var galaxyS8PGlass =   240;
var galaxyS8PLCD =     335;
var galaxyNote3Glass = 80;
var galaxyNote3LCD =   160;
var galaxyNote4Glass = 85;
var galaxyNote4LCD =   175;
var galaxyNote5Glass = 130;
var galaxyNote5LCD =   215;
//LG
var nexus4Glass =     75;
var nexus4LCD =       85;
var nexus5LCD =       65;
var nexus5XLCD =      75;
var LGG2Glass =       85;
var LGG2LCD =         95;
var LGG3Glass =       75;
var LGG3LCD =         80;
var LGG4LCD =         75;
var LGG5LCD =         80;
var V20Glass =        135;
var V20LCD =          140;

//OnePlus
var OnePlus1LCD =  100;
var OnePlus2LCD = 110;
var OnePlus3LCD =  175;
var OnePlus5LCD = 210;
var OnePlus5TLCD = 175;
var OnePlusXLCD = 215;
var OnePlus6LCD = 230;

//Sony
var Z3LCD =            100;
var Z4LCD =            115;
var Z5LCD =            120;

//Blackberry
var bbZ10 =            45;
var bbZ30 =            105;
var bbQ10 =            50;
var bbQ20 =            80;
var bbQ30 =            130;

//HTC
var M9LCD =            100;
var M10LCD =           120;

//Huawei
var mate7LCD =         105;
var mate8LCD =         110;
var mate9LCD =         115;
var p9LCD =            105;
var p10LCD =           125;
var huaweiG7LCD =      105;
var p20LCD=            210;
var p20PROLCD=         370;
var p20LiteLCD =       135;

//Pixel
var pixelLCD =         140;
var pixelXLLCD =       160;
var pixel2LCD =        210;
var pixel2XLLCD =      225;
var Nexus6LCD =        190;
var Nexus6PLCD =       170;

//Services
var diagnostic =         25;
var waterDamageL =       65;
var waterDamageH =       75;
var waterDamageSamsung = 75;
var advancedDiagnostic = 60;
var systemRestore =      50;
<|endoftext|>


<commit_before>function Pusher(options) {
  var that = this;
  // next message id
  that.nextId = 0;
  // socket url
  that.url = options.url;
  // heartbeat interval
  that.heartbeat = null;
  // session id
  that.id = null;
  // min backoff
  that.minBackoff = 500;
  // max backoff
  that.maxBackoff = 30000;
  // exponential backoff
  that.backoff = that.minBackoff;
  // interval that sends heartbeats
  that.heartbeater = null;
  // socket
  that.socket = null;
  // reconnect timeout
  that.reconnector = null;
  // buffer while closed
  that.buffer = [];
  // subscriptions
  that.subscriptions = {};
  // callbacks
  that.callbacks = {};
  // errbacks
  that.errbacks = {};
  // error handler
  that.onerror = options.onerror || function(err) {
    console.log('pusher error:', err);
  };
  // on connect handler
  that.onconnect = options.onconnect || function(msg) {
    console.log('pusher connected:', msg);
  };
  // authorizer is a function that generate authorization tokens for your rights.
  that.authorizer = options.authorizer || function(uri, write) {
    console.log('authorizer returned empty token for ', uri, write);
    return "";
  };
  /*
   * set up the socket
   */
  that.connect = function() {
    var url = that.url;
    if (that.id != null) {
      url += '?session_id=' + that.id;
    }
    that.socket = new WebSocket(url);
    that.socket.onopen = function() {
      that.lastHeartbeatReceived = new Date();
      that.backoff = that.minBackoff;
    };
    that.socket.onerror = function(err) {
      that.onerror(err);
    };
    that.socket.onmessage = function(message) {
      var msg = JSON.parse(message.data);
      that.handleMessage(msg);
    };
    that.socket.onclose = function() {
      that.close();
    };
  }
  /*
   * handle incoming messages
   */
  that.handleMessage = function(msg) {
    if (msg.Type == "Welcome") {
      that.heartbeat = msg.Welcome.Heartbeat;
      if (that.id != null && msg.Welcome.Id != that.id) {
        var oldSubscriptions = that.subscriptions;
        that.subscriptions = {};
        for (var uri in oldSubscriptions) {
          for (var i = 0; i < oldSubscriptions[uri].length; i++) {
            that.on(uri, oldSubscriptions[uri][i]);
          }
        }
      }
      that.id = msg.Welcome.Id;
      if (that.heartbeater != null) {
        clearInterval(that.heartbeater);
      }
      that.heartbeater = setInterval(function() {
        if (new Date().getTime() - that.lastHeartbeatReceived.getTime() > that.heartbeat) {
          that.close()
        } else {
          if (that.socket.readyState == 1) {
            that.send({
              Type: "Heartbeat"
            });
          }
        }
      }, that.heartbeat / 2);
      while (that.buffer.length > 0) {
        that.send(that.buffer.shift());
      }
      that.onconnect(msg);
    } else if (msg.Type == "Heartbeat") {
      that.lastHeartbeatReceived = new Date();
    } else if (msg.Type == "Message") {
      var subscriptions = that.subscriptions[msg.URI];
      if (subscriptions != null) {
        for (var subscription in subscriptions) {
          subscriptions[subscription].apply(msg, msg.Data);
        }
      }
    } else if (msg.Type == "Error") {
      if (msg.Data.Type == "Subscribe") {
        delete(that.subscriptions[msg.Data.URI]);
      }
      var obj = that.errbacks[msg.Id];
      if (obj != null) {
        obj.errback.call(obj, msg);
      } else {
        that.onerror(msg);
      }
      delete(that.errbacks[msg.Id]);
      delete(that.callbacks[msg.Id]);
    } else if (msg.Type == "Ack") {
      var obj = that.callbacks[msg.Id];
      if (obj != null) {
        obj.callback.call(obj, msg);
      }
      delete(that.callbacks[msg.Id]);
      delete(that.errbacks[msg.Id]);
    } else {
      that.onerror({
        Type: "Error",
        Error: "Unknown message type " + msg.Type,
        Data: msg
      });
    }
  };
  that.emit = function(uri) {
    // Copy arguments, becouse slice changes it.
    var args = null;
    var callback = function() {};
    if (typeof (arguments[arguments.length-1]) === "function") {
      args = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
      callback = arguments[arguments.length - 1];
    } else {
      args = Array.prototype.slice.call(arguments, 0);
    }
    var sendFunc = null;
    var msg = {
        Type: 'Message',
        URI: uri,
        Data: args.slice(1),
        Id: true,
        errback: function(err) {
          if (err.Error.Type == "AuthorizationError") {
            that.send({
              Type: 'Authorize',
              URI: uri,
              Write: true,
              Token: that.authorizer(uri, true),
              Id: true,
              callback: sendFunc
            });
          } else {
            that.onerror(err);
          }
        }
    };
    msg.callback = function() {
      callback(msg);
    };
    sendFunc = function() {
      that.send(msg);
    };
    sendFunc();
  };
  that.on = function(uri, subscription, callback) {
    if (that.subscriptions[uri] == null) {
      that.send({
        Type: 'Subscribe',
        URI: uri,
        Id: true,
        callback: function() {
          if (that.subscriptions[uri] == null) {
            that.subscriptions[uri] = {};
          }
          that.subscriptions[uri][subscription] = subscription;
          if (callback != null) {
            callback(uri);
          }
        },
        errback: function(err) {
          if (err.Error.Type == "AuthorizationError") {
            that.send({
              Type: 'Authorize',
              URI: uri,
              Id: true,
              Token: that.authorizer(uri, false),
              callback: function() {
                that.on(uri, subscription, callback);
              }
            });
          } else {
            that.onerror(err)
          }
        }
      });
    }
  };
  that.off = function(uri, subscription) {
    delete(that.subscriptions[uri][subscription]);
    var left = 0;
    for (var subscription in that.subscriptions[uri]) {
      left++;
    }
    if (left == 0) {
      that.send({
        Type: 'Unsubscribe',
        URI: uri,
        Id: true
      });
      delete(that.subscriptions[uri]);
    }
  };
  /*
   * close
   */
  that.close = function() {
    clearInterval(that.heartbeater);
    that.heartbeater = null;
    that.socket.close();
    if (that.backoff < that.maxBackoff) {
      that.backoff *= 2;
    }
    if (that.reconnector != null) {
      clearTimeout(that.reconnector);
    }
    that.reconnector = setTimeout(that.connect, that.backoff);
  };
  /*
   * send a JSON encoded obj
   */
  that.send = function(obj) {
    if (that.socket.readyState == 1) {
      if (obj.Id) {
        obj.Id = that.id + ":" + that.nextId++;
        if (obj.callback != null) {
          that.callbacks[obj.Id] = obj;
        }
        if (obj.errback != null) {
          that.errbacks[obj.Id] = obj;
        }
      }
      that.socket.send(JSON.stringify(obj));
    } else {
      that.buffer.push(obj);
    }
  };
  that.connect();
  return that;
}
<commit_msg>updated pusher to follow our jslint standard<commit_after>var Pusher = function(options) {
  var that = this;
  // next message id
  that.nextId = 0;
  // socket url
  that.url = options.url;
  // heartbeat interval
  that.heartbeat = null;
  // session id
  that.id = null;
  // min backoff
  that.minBackoff = 500;
  // max backoff
  that.maxBackoff = 30000;
  // exponential backoff
  that.backoff = that.minBackoff;
  // interval that sends heartbeats
  that.heartbeater = null;
  // socket
  that.socket = null;
  // reconnect timeout
  that.reconnector = null;
  // buffer while closed
  that.buffer = [];
  // subscriptions
  that.subscriptions = {};
  // callbacks
  that.callbacks = {};
  // errbacks
  that.errbacks = {};
  // error handler
  that.onerror = options.onerror || function(err) {
    console.log('pusher error:', err);
  };
  // on connect handler
  that.onconnect = options.onconnect || function(msg) {
    console.log('pusher connected:', msg);
  };
  // authorizer is a function that generate authorization tokens for your rights.
  that.authorizer = options.authorizer || function(uri, write, callback) {
    console.log('authorizer returned empty token for ', uri, write);
    callback('');
  };
  /*
   * set up the socket
   */
  that.connect = function() {
    var url = that.url;
    if (that.id !== null) {
      url += '?session_id=' + that.id;
    }
    that.socket = new WebSocket(url);
    that.socket.onopen = function() {
      that.lastHeartbeatReceived = new Date();
      that.backoff = that.minBackoff;
    };
    that.socket.onerror = function(err) {
      that.onerror(err);
    };
    that.socket.onmessage = function(message) {
      var msg = JSON.parse(message.data);
      that.handleMessage(msg);
    };
    that.socket.onclose = function() {
      that.close();
    };
  };
  /*
   * handle incoming messages
   */
  that.handleMessage = function(msg) {
    if (msg.Type === 'Welcome') {
      that.heartbeat = msg.Welcome.Heartbeat;
      if (that.id !== null && msg.Welcome.Id !== that.id) {
        var oldSubscriptions = that.subscriptions;
        that.subscriptions = {};
        for (var uri in oldSubscriptions) {
          if (typeof oldSubscriptions[uri] !== 'undefined') {
            for (var i = 0; i < oldSubscriptions[uri].length; i++) {
              that.on(uri, oldSubscriptions[uri][i]);
            }
          }
        }
      }
      that.id = msg.Welcome.Id;
      if (that.heartbeater !== null) {
        clearInterval(that.heartbeater);
      }
      that.heartbeater = setInterval(function() {
        if (new Date().getTime() - that.lastHeartbeatReceived.getTime() > that.heartbeat) {
          that.close();
        } else {
          if (that.socket.readyState === 1) {
            that.send({
              Type: 'Heartbeat'
            });
          }
        }
      }, that.heartbeat / 2);
      while (that.buffer.length > 0) {
        that.send(that.buffer.shift());
      }
      that.onconnect(msg);
    } else if (msg.Type === 'Heartbeat') {
      that.lastHeartbeatReceived = new Date();
    } else if (msg.Type === 'Message') {
      var subscriptions = that.subscriptions[msg.URI];
      if (subscriptions !== null) {
        for (var subscription in subscriptions) {
          if (typeof subscriptions[subscription] !== 'undefined') {
            subscriptions[subscription].apply(msg, msg.Data);
          }
        }
      }
    } else if (msg.Type === 'Error') {
      if (msg.Data.Type === 'Subscribe') {
        delete(that.subscriptions[msg.Data.URI]);
      }
      var obj = that.errbacks[msg.Id];
      if (obj !== null && obj.errback) {
        obj.errback.call(obj, msg);
      } else {
        that.onerror(msg);
      }
      delete(that.errbacks[msg.Id]);
      delete(that.callbacks[msg.Id]);
    } else if (msg.Type === 'Ack') {
      var object = that.callbacks[msg.Id];
      if (object !== null) {
        object.callback.call(object, msg);
      }
      delete(that.callbacks[msg.Id]);
      delete(that.errbacks[msg.Id]);
    } else {
      that.onerror({
        Type: 'Error',
        Error: 'Unknown message type ' + msg.Type,
        Data: msg
      });
    }
  };
  that.emit = function(uri) {
    // Copy arguments, becouse slice changes it.
    var args = null;
    var callback = function() {};
    if (typeof (arguments[arguments.length-1]) === 'function') {
      args = Array.prototype.slice.call(arguments, 0, arguments.length - 1);
      callback = arguments[arguments.length - 1];
    } else {
      args = Array.prototype.slice.call(arguments, 0);
    }
    var sendFunc = null;
    var msg = {
        Type: 'Message',
        URI: uri,
        Data: args.slice(1),
        Id: true,
        errback: function(err) {
          if (err.Error.Type === 'AuthorizationError') {
            that.authorizer(uri, true, function(token) {
              that.send({
                Type: 'Authorize',
                URI: uri,
                Write: true,
                Token: token,
                Id: true,
                callback: sendFunc
              });
            });
          } else {
            that.onerror(err);
          }
        }
    };
    msg.callback = function() {
      callback(msg);
    };
    sendFunc = function() {
      that.send(msg);
    };
    sendFunc();
  };
  that.on = function(uri, subscription, callback) {
    if (typeof that.subscriptions[uri] === 'undefined') {
      that.send({
        Type: 'Subscribe',
        URI: uri,
        Id: true,
        callback: function() {
          if (typeof that.subscriptions[uri] === 'undefined') {
            that.subscriptions[uri] = {};
          }
          that.subscriptions[uri][subscription] = subscription;
          if (callback !== null) {
            callback(uri);
          }
        },
        errback: function(err) {
          if (err.Error.Type === 'AuthorizationError') {
            that.authorizer(uri, false, function(token) {
              that.send({
                Type: 'Authorize',
                URI: uri,
                Id: true,
                Token: token,
                callback: function() {
                  that.on(uri, subscription, callback);
                }
              });
            });
          } else {
            that.onerror(err);
          }
        }
      });
    }
  };
  that.off = function(uri, subscription) {
    delete(that.subscriptions[uri][subscription]);
    var left = 0;
    for (var sub in that.subscriptions[uri]) {
      if (that.subscriptions[uri]) {
        left++;
      }
    }
    if (left === 0) {
      that.send({
        Type: 'Unsubscribe',
        URI: uri,
        Id: true
      });
      delete(that.subscriptions[uri]);
    }
  };
  /*
   * close
   */
  that.close = function() {
    clearInterval(that.heartbeater);
    that.heartbeater = null;
    that.socket.close();
    if (that.backoff < that.maxBackoff) {
      that.backoff *= 2;
    }
    if (that.reconnector !== null) {
      clearTimeout(that.reconnector);
    }
    that.reconnector = setTimeout(that.connect, that.backoff);
  };
  /*
   * send a JSON encoded obj
   */
  that.send = function(obj) {
    if (that.socket.readyState === 1) {
      if (obj.Id) {
        obj.Id = that.id + ':' + that.nextId++;
        if (obj.callback !== null) {
          that.callbacks[obj.Id] = obj;
        }
        if (obj.errback !== null) {
          that.errbacks[obj.Id] = obj;
        }
      }
      that.socket.send(JSON.stringify(obj));
    } else {
      that.buffer.push(obj);
    }
  };
  that.connect();
  return that;
};

module.exports = Pusher;
<|endoftext|>


<commit_before>// relode.js

var relode = (function(jsonld) {

  var my = {}, promises = jsonld.promises;

  var framingContext = {
    "cc": "http://creativecommons.org/ns#",
    "dcterms": "http://purl.org/dc/terms",
    "owl": "http://www.w3.org/2002/07/owl#",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
    "vann": "http://purl.org/vocab/vann/",
    "vs": "http://www.w3.org/2003/06/sw-vocab-status/ns#",
    "xsd": "http://www.w3.org/2001/XMLSchema#",
    "rdfs:domain": { "@type": "@id" },
    "rdfs:range": { "@type": "@id" },
    "rdfs:comment": { "@container": "@language" },
    "rdfs:label": { "@container": "@language" },
    "rdfs:isDefinedBy": { "@type": "@id" },
    "rdfs:subClassOf": { "@type": "@id", "@container": "@set" },
    "rdfs:subPropertyOf": { "@type": "@id", "@container": "@set" },
    "rdfs:seeAlso": { "@type": "@id" },
    "creator": { "@id": "dcterms:creator", "@type": "@id" },
    "contributor": { "@id": "dcterms:contributor", "@type": "@id" },
    "publisher": { "@id": "dcterms:publisher", "@type": "@id" },
    "title": { "@id": "dcterms:title", "@container": "@language" },
    "description": { "@id": "dcterms:description", "@container": "@language" },
    "rights": { "@id": "dcterms:rights" },
    "status": "vs:term_status",
    "moreInfo": { "@id": "vs:moreinfo", "@type": "@id" }
  };

  var documentClasses = function(doc, targetElement) {

    var originalContext = doc['@context'],
        classes = document.createDocumentFragment();

    var classesSection = document.createElement('section');
    var classesHeader = document.createElement('h2');
    classesHeader.textContent = 'Classes';
    classesSection.appendChild(classesHeader);

    var frame = {
      "@context": framingContext,
      "@type": [ "rdfs:Class", "owl:Class" ],
      "rdfs:subClassOf": { "@embed": false },
      "rdfs:isDefinedBy": { "@embed": false },
      "rdfs:seeAlso": { "@embed": false },
    };

    var promise = promises.frame(doc, frame);

    promise.then(function(framed) {

      framed['@graph'].forEach(function(resource) {
        var classSection = assembleClassSection(resource);
        classesSection.appendChild(classSection);
      });

      classes.appendChild(classesSection);
      targetElement.appendChild(classes);

    }, function(err) {
      throw new Exception("Had trouble framing classes", err);
    });

    var assembleClassSection = function(resource) {

      var classSection = assembleCommon(resource, originalContext);

      if (hasRelationships(resource)) {
        var relationships = document.createElement('dl');
        relationships.className = 'relationships';

        var superClasses = resource['rdfs:subClassOf'];
        if (superClasses.length > 0) {
          var dt = document.createElement('dt');
          dt.textContent = "has super-classes";
          relationships.appendChild(dt);

          superClasses.forEach(function(superClass){
            var dd = document.createElement('dd'),
                link = getExpandedUri(superClass, originalContext);
            dd.innerHTML = '' + getCompactUri(superClass, originalContext) + '';
            relationships.appendChild(dd);
          });
        }

        classSection.appendChild(relationships);
      }

      return classSection;
    };

    var supportedRelationships = ['rdfs:subClassOf'];

    var hasRelationships = function(resource) {
      return supportedRelationships.some(function(relationship) {
        return resource[relationship].length > 0;
      });
    };
  };

  var documentProperties = function(doc, targetElement) {

    var originalContext = doc['@context'],
        properties = document.createDocumentFragment();

    var propertiesSection = document.createElement('section'),
        propertiesHeader = document.createElement('h2'),
        propertiesToc = document.createElement('nav'),
        propertiesTocList = document.createElement('ol');

    propertiesHeader.textContent = 'Object Properties';
    propertiesSection.appendChild(propertiesHeader);

    propertiesToc.className = 'properties';
    propertiesToc.appendChild(propertiesTocList);
    propertiesSection.appendChild(propertiesToc);

    var frame = {
      "@context": framingContext,
      "@type": [ "owl:ObjectProperty" ],
      "rdfs:subPropertyOf": { "@embed": false },
      "rdfs:isDefinedBy": { "@embed": false },
      "rdfs:seeAlso": { "@embed": false },
      "rdfs:domain": { "@embed": false },
      "rdfs:range": { "@embed": false },
    };

    var promise = promises.frame(doc, frame);

    promise.then(function(framed) {

      framed['@graph'].forEach(function(resource) {
        var propertySection = assemblePropertySection(resource);
        propertiesSection.appendChild(propertySection);
      });

      properties.appendChild(propertiesSection);
      targetElement.appendChild(properties);

    }, function(err) {
      throw new Exception("Had trouble framing properties", err);
    });

    var assemblePropertySection = function(resource) {

      var propertySection = assembleCommon(resource, originalContext);

      if (hasRelationships(resource)) {
        var relationships = document.createElement('dl');
        relationships.className = 'relationships';

        var superProperties = resource['rdfs:subPropertyOf'];
        if (superProperties.length > 0) {
          var dt = document.createElement('dt');
          dt.textContent = "has super-properties";
          relationships.appendChild(dt);

          superProperties.forEach(function(superProperty){
            var dd = document.createElement('dd'),
                link = getExpandedUri(superProperty, originalContext);

            dd.innerHTML = '' + getCompactUri(superProperty, originalContext) + '';
            relationships.appendChild(dd);
          });
        }

        var domain = resource['rdfs:domain'];
        if (domain) {
          var dt = document.createElement('dt');
          dt.textContent = 'has domain';
          relationships.appendChild(dt);

          var dd = document.createElement('dd'),
              link = getExpandedUri(domain, originalContext);

          dd.innerHTML = '' + getCompactUri(domain, originalContext) + '';
          relationships.appendChild(dd);
        }

        var range = resource['rdfs:range'];
        if (range) {
          var dt = document.createElement('dt');
          dt.textContent = 'has range';
          relationships.appendChild(dt);

          var dd = document.createElement('dd'),
              link = getExpandedUri(range, originalContext);

          dd.innerHTML = '' + getCompactUri(range, originalContext) + '';
          relationships.appendChild(dd);
        }

        propertySection.appendChild(relationships);
      }

      return propertySection;
    };

    var supportedRelationships = ['rdfs:subPropertyOf', 'rdfs:domain', 'rdfs:range'];

    var hasRelationships = function(resource) {
      return supportedRelationships.some(function(relationship) {
        return Array.isArray(resource[relationship]) ? resource[relationship].length > 0 : !!resource[relationship];
      });
    };
  };

  var assembleCommon = function(resource, context) {

    var id = decomposeCurie(resource['@id'], context);

    console.log(resource);

    var resourceElement = document.createElement('div');
    resourceElement.id = id.name;
    resourceElement.className = 'resource ' + getTypeClassification(resource);
    resourceElement.setAttribute('resource', '[' + id.curie + ']');
    resourceElement.setAttribute('typeof', getAttribute(resource['@type']));

    var resourceElementHeader = document.createElement('h2');
    resourceElementHeader.innerHTML = '' + resource['rdfs:label']['en'] + '';
    resourceElement.appendChild(resourceElementHeader);

    var iri = document.createElement('dl');
    iri.className = 'iri inline';
    iri.innerHTML = '
IRI:

' + id.expanded + '
';
    resourceElement.appendChild(iri);

    var definedBy = document.createElement('dl');
    definedBy.className = 'defined-by inline invisible';
    definedBy.innerHTML = '
Is defined by:

' + resource['rdfs:isDefinedBy'] + '
';
    resourceElement.appendChild(definedBy);

    var comment = resource['rdfs:comment'];
    if (comment) {
      var commentElement = document.createElement('div');
      commentElement.className = "comment";
      commentElement.innerHTML = '
' + comment['en'] + '
';
      resourceElement.appendChild(commentElement);
    }

    var seeAlso = resource['rdfs:seeAlso'];
    if (seeAlso) {
      var seeAlsoElement = document.createElement('dl');
      seeAlsoElement.className = 'see-also inline';
      seeAlsoElement.innerHTML = '
See also:

' + seeAlso + '
';
      resourceElement.appendChild(seeAlsoElement);
    }

    var moreInfo = resource['moreInfo'];
    if (moreInfo) {
      var moreInfoElement = document.createElement('dl');
      moreInfoElement.className = 'more-info inline';
      moreInfoElement.innerHTML = '
More status info:

' + moreInfo + '
';
      resourceElement.appendChild(moreInfoElement);
    }

    return resourceElement;
  };

  var getTypeClassification = function(resource) {
    var classTypes = ['rdfs:Class', 'owl:Class'],
        objectPropertyTypes = ['owl:ObjectProperty'],
        datatypePropertyTypes = ['owl:DatatypeProperty'],
        type = (typeof resource === 'string') ? resource : resource['@type'];

    if (Array.isArray(type)) {
      return type.map(getTypeClassification).join(' ');
    }

    if (classTypes.indexOf(type) > -1) return 'class';
    else if (objectPropertyTypes.indexOf(type) > -1) return 'object-property';
    else if (datatypePropertyTypes.indexOf(type) > -1) return 'data-property';
    else if (type === 'owl:FunctionalProperty') return 'functional';
  };

  var getAttribute = function(attribute) {
    return Array.isArray(attribute) ? attribute.join(' ') : attribute;
  };

  var decomposeCurie = function(curie, context) {
    if (!isCurie(curie)) {
      for (var term in context) {
        var prefix = context[term];
        if (typeof prefix === 'string' && curie.indexOf(prefix) !== -1) {
          curie = term + ":" + curie.substring(prefix.length);
        }
      }

      if (!isCurie(curie))
        throw new Error("<" + curie + "> is not a curie!");
    }

    var parts = curie.split(":"),
        prefix = parts[0],
        name = parts[1];

    return {
      "curie": curie,
      "prefix": prefix,
      "name": name,
      "expanded": context[prefix] + name
    };
  };

  // Not comprehensive...
  var isCurie = function(uri) {
    return typeof uri === 'string' && !isAbsoluteWebUri(uri);
  };

  var getExpandedUri = function(uri, context) {
    return isCurie(uri) ? decomposeCurie(uri, context).expanded : uri ;
  };

  var getCompactUri = function(uri, context) {
    return isCurie(uri) ? uri : decomposeCurie(uri, context).curie ;
  }

  var isAbsoluteWebUri = function(uri) {
    return (uri.indexOf('http://') === 0 || uri.indexOf('https://') === 0);
  };

  my.init = function(vocabUrl, targetId, options) {

    if (!vocabUrl) {
      throw new Error("A vocabUrl parameter is needed. This should resolve to a valid JSON-LD representation of the ontology that you wish to relode.");
    }
    if (!targetId) {
      throw new Error("A targetId parameter is needed. This id the id of the element to which the ontology description shall be appended.");
    }

    options = options || {};

    if (!('base' in options)) {
      options.base = document.location.protocol + "//" + document.location.host + document.location.pathname;
    }
    if (!('documentLoader' in options)) {
      options.documentLoader = jsonld.documentLoaders.xhr();
    }

    var documentLoader = options.documentLoader || jsonld.documentLoaders.xhr(),
        vocabUrl = isAbsoluteWebUri(vocabUrl) ? vocabUrl : options.base + vocabUrl,
        targetElement = document.getElementById(targetId);

    documentLoader(vocabUrl).then(function(response) {
      var doc = JSON.parse(response.document);

      documentClasses(doc, targetElement);
      documentProperties(doc, targetElement);

    }, function(err) {
      console.warn("There was a problem: ", err);
    });

  };

  return my;

}(jsonld));
<commit_msg>Don't use a JSON-LD keyword for the term<commit_after>// relode.js

var relode = (function(jsonld) {

  var my = {}, promises = jsonld.promises;

  var framingContext = {
    "cc": "http://creativecommons.org/ns#",
    "dcterms": "http://purl.org/dc/terms",
    "owl": "http://www.w3.org/2002/07/owl#",
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
    "vann": "http://purl.org/vocab/vann/",
    "vs": "http://www.w3.org/2003/06/sw-vocab-status/ns#",
    "xsd": "http://www.w3.org/2001/XMLSchema#",
    "rdfs:domain": { "@type": "@id" },
    "rdfs:range": { "@type": "@id" },
    "rdfs:comment": { "@container": "@language" },
    "rdfs:label": { "@container": "@language" },
    "rdfs:isDefinedBy": { "@type": "@id" },
    "rdfs:subClassOf": { "@type": "@id", "@container": "@set" },
    "rdfs:subPropertyOf": { "@type": "@id", "@container": "@set" },
    "rdfs:seeAlso": { "@type": "@id" },
    "creator": { "@id": "dcterms:creator", "@type": "@id" },
    "contributor": { "@id": "dcterms:contributor", "@type": "@id" },
    "publisher": { "@id": "dcterms:publisher", "@type": "@id" },
    "title": { "@id": "dcterms:title", "@container": "@language" },
    "description": { "@id": "dcterms:description", "@container": "@language" },
    "rights": { "@id": "dcterms:rights" },
    "status": "vs:term_status",
    "moreInfo": { "@id": "vs:moreinfo", "@type": "@id" }
  };

  var documentClasses = function(doc, targetElement) {

    var originalContext = doc['@context'],
        classes = document.createDocumentFragment();

    var classesSection = document.createElement('section');
    var classesHeader = document.createElement('h2');
    classesHeader.textContent = 'Classes';
    classesSection.appendChild(classesHeader);

    var frame = {
      "@context": framingContext,
      "@type": [ "rdfs:Class", "owl:Class" ],
      "rdfs:subClassOf": { "@embed": false },
      "rdfs:isDefinedBy": { "@embed": false },
      "rdfs:seeAlso": { "@embed": false },
    };

    var promise = promises.frame(doc, frame);

    promise.then(function(framed) {

      framed['@graph'].forEach(function(resource) {
        var classSection = assembleClassSection(resource);
        classesSection.appendChild(classSection);
      });

      classes.appendChild(classesSection);
      targetElement.appendChild(classes);

    }, function(err) {
      throw new Exception("Had trouble framing classes", err);
    });

    var assembleClassSection = function(resource) {

      var classSection = assembleCommon(resource, originalContext);

      if (hasRelationships(resource)) {
        var relationships = document.createElement('dl');
        relationships.className = 'relationships';

        var superClasses = resource['rdfs:subClassOf'];
        if (superClasses.length > 0) {
          var dt = document.createElement('dt');
          dt.textContent = "has super-classes";
          relationships.appendChild(dt);

          superClasses.forEach(function(superClass){
            var dd = document.createElement('dd'),
                link = getExpandedUri(superClass, originalContext);
            dd.innerHTML = '' + getCompactUri(superClass, originalContext) + '';
            relationships.appendChild(dd);
          });
        }

        classSection.appendChild(relationships);
      }

      return classSection;
    };

    var supportedRelationships = ['rdfs:subClassOf'];

    var hasRelationships = function(resource) {
      return supportedRelationships.some(function(relationship) {
        return resource[relationship].length > 0;
      });
    };
  };

  var documentProperties = function(doc, targetElement) {

    var originalContext = doc['@context'],
        properties = document.createDocumentFragment();

    var propertiesSection = document.createElement('section'),
        propertiesHeader = document.createElement('h2'),
        propertiesToc = document.createElement('nav'),
        propertiesTocList = document.createElement('ol');

    propertiesHeader.textContent = 'Object Properties';
    propertiesSection.appendChild(propertiesHeader);

    propertiesToc.className = 'properties';
    propertiesToc.appendChild(propertiesTocList);
    propertiesSection.appendChild(propertiesToc);

    var frame = {
      "@context": framingContext,
      "@type": [ "owl:ObjectProperty" ],
      "rdfs:subPropertyOf": { "@embed": false },
      "rdfs:isDefinedBy": { "@embed": false },
      "rdfs:seeAlso": { "@embed": false },
      "rdfs:domain": { "@embed": false },
      "rdfs:range": { "@embed": false },
    };

    var promise = promises.frame(doc, frame);

    promise.then(function(framed) {

      framed['@graph'].forEach(function(resource) {
        var propertySection = assemblePropertySection(resource);
        propertiesSection.appendChild(propertySection);
      });

      properties.appendChild(propertiesSection);
      targetElement.appendChild(properties);

    }, function(err) {
      throw new Exception("Had trouble framing properties", err);
    });

    var assemblePropertySection = function(resource) {

      var propertySection = assembleCommon(resource, originalContext);

      if (hasRelationships(resource)) {
        var relationships = document.createElement('dl');
        relationships.className = 'relationships';

        var superProperties = resource['rdfs:subPropertyOf'];
        if (superProperties.length > 0) {
          var dt = document.createElement('dt');
          dt.textContent = "has super-properties";
          relationships.appendChild(dt);

          superProperties.forEach(function(superProperty){
            var dd = document.createElement('dd'),
                link = getExpandedUri(superProperty, originalContext);

            dd.innerHTML = '' + getCompactUri(superProperty, originalContext) + '';
            relationships.appendChild(dd);
          });
        }

        var domain = resource['rdfs:domain'];
        if (domain) {
          var dt = document.createElement('dt');
          dt.textContent = 'has domain';
          relationships.appendChild(dt);

          var dd = document.createElement('dd'),
              link = getExpandedUri(domain, originalContext);

          dd.innerHTML = '' + getCompactUri(domain, originalContext) + '';
          relationships.appendChild(dd);
        }

        var range = resource['rdfs:range'];
        if (range) {
          var dt = document.createElement('dt');
          dt.textContent = 'has range';
          relationships.appendChild(dt);

          var dd = document.createElement('dd'),
              link = getExpandedUri(range, originalContext);

          dd.innerHTML = '' + getCompactUri(range, originalContext) + '';
          relationships.appendChild(dd);
        }

        propertySection.appendChild(relationships);
      }

      return propertySection;
    };

    var supportedRelationships = ['rdfs:subPropertyOf', 'rdfs:domain', 'rdfs:range'];

    var hasRelationships = function(resource) {
      return supportedRelationships.some(function(relationship) {
        return Array.isArray(resource[relationship]) ? resource[relationship].length > 0 : !!resource[relationship];
      });
    };
  };

  var assembleCommon = function(resource, context) {

    var id = decomposeCurie(resource['@id'], context);

    console.log(resource);

    var resourceElement = document.createElement('div');
    resourceElement.id = id.name;
    resourceElement.className = 'resource ' + getTypeClassification(resource);
    resourceElement.setAttribute('resource', '[' + id.curie + ']');
    resourceElement.setAttribute('typeof', getAttribute(resource['@type']));

    var resourceElementHeader = document.createElement('h2');
    resourceElementHeader.innerHTML = '' + resource['rdfs:label']['en'] + '';
    resourceElement.appendChild(resourceElementHeader);

    var iri = document.createElement('dl');
    iri.className = 'iri inline';
    iri.innerHTML = '
IRI:

' + id.expanded + '
';
    resourceElement.appendChild(iri);

    var definedBy = document.createElement('dl');
    definedBy.className = 'defined-by inline invisible';
    definedBy.innerHTML = '
Is defined by:

' + resource['rdfs:isDefinedBy'] + '
';
    resourceElement.appendChild(definedBy);

    var comment = resource['rdfs:comment'];
    if (comment) {
      var commentElement = document.createElement('div');
      commentElement.className = "comment";
      commentElement.innerHTML = '
' + comment['en'] + '
';
      resourceElement.appendChild(commentElement);
    }

    var seeAlso = resource['rdfs:seeAlso'];
    if (seeAlso) {
      var seeAlsoElement = document.createElement('dl');
      seeAlsoElement.className = 'see-also inline';
      seeAlsoElement.innerHTML = '
See also:

' + seeAlso + '
';
      resourceElement.appendChild(seeAlsoElement);
    }

    var moreInfo = resource['moreInfo'];
    if (moreInfo) {
      var moreInfoElement = document.createElement('dl');
      moreInfoElement.className = 'more-info inline';
      moreInfoElement.innerHTML = '
More status info:

' + moreInfo + '
';
      resourceElement.appendChild(moreInfoElement);
    }

    return resourceElement;
  };

  var getTypeClassification = function(resource) {
    var classTypes = ['rdfs:Class', 'owl:Class'],
        objectPropertyTypes = ['owl:ObjectProperty'],
        datatypePropertyTypes = ['owl:DatatypeProperty'],
        type = (typeof resource === 'string') ? resource : resource['@type'];

    if (Array.isArray(type)) {
      return type.map(getTypeClassification).join(' ');
    }

    if (classTypes.indexOf(type) > -1) return 'class';
    else if (objectPropertyTypes.indexOf(type) > -1) return 'object-property';
    else if (datatypePropertyTypes.indexOf(type) > -1) return 'data-property';
    else if (type === 'owl:FunctionalProperty') return 'functional';
  };

  var getAttribute = function(attribute) {
    return Array.isArray(attribute) ? attribute.join(' ') : attribute;
  };

  var decomposeCurie = function(curie, context) {
    if (!isCurie(curie)) {
      for (var term in context) {
        var prefix = context[term];
        if (typeof prefix === 'string' && term.indexOf('@') !== 0 && curie.indexOf(prefix) !== -1) {
          curie = term + ":" + curie.substring(prefix.length);
        }
      }

      if (!isCurie(curie))
        throw new Error("<" + curie + "> is not a curie!");
    }

    var parts = curie.split(":"),
        prefix = parts[0],
        name = parts[1];

    return {
      "curie": curie,
      "prefix": prefix,
      "name": name,
      "expanded": context[prefix] + name
    };
  };

  // Not comprehensive...
  var isCurie = function(uri) {
    return typeof uri === 'string' && !isAbsoluteWebUri(uri);
  };

  var getExpandedUri = function(uri, context) {
    return isCurie(uri) ? decomposeCurie(uri, context).expanded : uri ;
  };

  var getCompactUri = function(uri, context) {
    return isCurie(uri) ? uri : decomposeCurie(uri, context).curie ;
  }

  var isAbsoluteWebUri = function(uri) {
    return (uri.indexOf('http://') === 0 || uri.indexOf('https://') === 0);
  };

  my.init = function(vocabUrl, targetId, options) {

    if (!vocabUrl) {
      throw new Error("A vocabUrl parameter is needed. This should resolve to a valid JSON-LD representation of the ontology that you wish to relode.");
    }
    if (!targetId) {
      throw new Error("A targetId parameter is needed. This id the id of the element to which the ontology description shall be appended.");
    }

    options = options || {};

    if (!('base' in options)) {
      options.base = document.location.protocol + "//" + document.location.host + document.location.pathname;
    }
    if (!('documentLoader' in options)) {
      options.documentLoader = jsonld.documentLoaders.xhr();
    }

    var documentLoader = options.documentLoader || jsonld.documentLoaders.xhr(),
        vocabUrl = isAbsoluteWebUri(vocabUrl) ? vocabUrl : options.base + vocabUrl,
        targetElement = document.getElementById(targetId);

    documentLoader(vocabUrl).then(function(response) {
      var doc = JSON.parse(response.document);

      documentClasses(doc, targetElement);
      documentProperties(doc, targetElement);

    }, function(err) {
      console.warn("There was a problem: ", err);
    });

  };

  return my;

}(jsonld));
<|endoftext|>


<commit_before>var Router = {
	findRoute: function(pid1, pid2) {
		if(pid1 == pid2) return;

		var pid1Groups = [], pid2Groups = [];

		for(var key in Buses.groups) {
			for(var i = 0; i < Buses.groups[key].stops.length; i++) {
				if(pid1 == Buses.groups[key].stops[i]) {
					pid1Groups.push(key);
				}

				if(pid2 == Buses.groups[key].stops[i]) {
					pid2Groups.push(key);
				}
			}
		}

		var result = {		from	: Router.getPlaceDetail(pid1),
							to		: Router.getPlaceDetail(pid2),
							routes	: [] };

		var commonGroup = _.intersection(pid1Groups, pid2Groups);
		if(commonGroup.length > 0) {
			console.log('Single bus group found! Opts: ' + commonGroup.length);
			_.forEach(commonGroup, function(groupid) {
				result.routes.push({	buses		: Router.renderOneBusRouteDetail(pid1, pid2, groupid),
										changeovers	: [] });
			});
		}
		else {
			/** two bus territory */
			var commonStops = [], bus1, bus2;
			for(var i = 0; i < pid1Groups.length; i++) {
				for(var j = 0; j < pid2Groups.length; j++) {
					commonStops = _.intersection(Buses.groups[pid1Groups[i]].stops, Buses.groups[pid2Groups[j]].stops);
					_.forEach(commonStops, function(stop) {
						bus1 = Router.renderOneBusRouteDetail(pid1, stop, pid1Groups[i]);
						bus2 = Router.renderOneBusRouteDetail(stop, pid2, pid2Groups[j]);
						if(bus1.length > 0 && bus2.length > 0) {
							result.routes.push({	buses		: [bus1, bus2],
													changeovers	: [stop] });
						}
					});
				}
			}
		}
		/*
		var commonBus = _.intersection(pid1Buses, pid2Buses);

		if(commonBus.length > 0) {
			console.log('Single bus routes found! Opts: ' + commonBus.length);
			_.forEach(commonBus, function(bid) {
				result.routes.push(Router.renderOneBusRouteDetail(pid1, pid2, bid));
			});
		}
		else {
			var commonStops = [], _comStop = [];

			for(var i = 0; i < pid1Buses.length; i++) {
				for(var j = 0; j < pid2Buses.length; j++) {
					var pid1BusStops = _.pluck(Buses.routes[pid1Buses[i]].stops, 'pid');
					var pid2BusStops = _.pluck(Buses.routes[pid2Buses[j]].stops, 'pid');

					_comStop = _.intersection(pid1BusStops, pid2BusStops);

					if(_comStop.length > 0) {
						commonStops.push({bus1: pid1Buses[i], bus2: pid2Buses[j], ids: _.clone(_comStop) });
					}
				}
			}

			commonStops = _.uniq(commonStops);
			if(commonStops.length > 0) {
				console.log('Two bus routes found! Opts: ' + commonStops.length);
				_.forEach(commonStops, function(stop) {
					result.routes.push(Router.renderRouteDetail(pid1, pid2, stop));
				});
			}
		}
		*/

		return result;
	},

	renderOneBusRouteDetail: function(pid1, pid2, groupid) {

		var routeid, routestops, pid1match, pid2match, routes = [];

		for(var i = 0; i < Buses.groups[groupid].routes.length; i++) {
			routeid = Buses.groups[groupid].routes[i];
			routestops = _.pluck(Buses.routes[routeid].stopsfrom, 'pid');
			if(_.contains(routestops, pid1) && _.contains(routestops, pid2)) {

				pid1match = _.find(Buses.routes[routeid].stopsfrom, { 'pid': pid1 });
				pid2match = _.find(Buses.routes[routeid].stopsfrom, { 'pid': pid2 });
				if(pid1match && pid2match && pid1match.dist <= pid2match.dist) {
					routes.push(Router.renderBusDetail(routeid));
				}
			}

			/** reverse journey of bus */
			routestops = _.pluck(Buses.routes[routeid].stopsto, 'pid');
			if(_.contains(routestops, pid1) && _.contains(routestops, pid2)) {
				pid1match = _.find(Buses.routes[routeid].stopsto, { 'pid': pid1 });
				pid2match = _.find(Buses.routes[routeid].stopsto, { 'pid': pid2 });
				if(pid1match && pid2match && pid1match.dist <= pid2match.dist) {
					/** tell render function that travel direction is reversed */
					routes.push(Router.renderBusDetail(routeid, true));
				}
			}
		}

		return routes;

					//verbose		: 'Take the ' + Router.renderBusDetail(busid, 'detailed') + ' at ' + Buses.places[pid1].name +
									//'. Get down at ' + Buses.places[pid2].name };
	},

	renderRouteDetail: function(pid1, pid2, stop) {
		var names = [], places = [];
		for(var i = 0; i < stop.ids.length; i++) {
			names.push(Buses.places[stop.ids[i]].name);
			places.push(Router.getPlaceDetail(stop.ids[i]));
		}

		return { 	buses		: [Router.renderBusDetail(stop.bus1, 'json'), Router.renderBusDetail(stop.bus2, 'json')],
					changeovers	: places,
					verbose		: 'Take the ' + Router.renderBusDetail(stop.bus1, 'detailed') + ' at ' + Buses.places[pid1].name +
									'. Get down at ' + names.join(' or ') +
									'. Take ' +  Router.renderBusDetail(stop.bus2, 'detailed') + ' to ' + Buses.places[pid2].name };
	},

	renderBusDetail: function(bid, reverse) {
		/* bus only travels this way when returning, not on original journey */
		if(reverse) {
			return { routeno: Buses.routes[bid].routeno, from: Buses.routes[bid].to, to: Buses.routes[bid].from };
		}
		else {
			return { routeno: Buses.routes[bid].routeno, from: Buses.routes[bid].from, to: Buses.routes[bid].to };
		}
	},

	getPlaceDetail: function(pid) {
		return { name: Buses.places[pid].name, lat: Buses.places[pid].lat, lng: Buses.places[pid].lon };
	}
};
<commit_msg>cleaned up code, added sorting by distance<commit_after>var Router = {
	findRoute: function(pid1, pid2) {
		if(pid1 == pid2) return;

		var pid1Groups = [], pid2Groups = [];

		for(var key in Buses.groups) {
			for(var i = 0; i < Buses.groups[key].stops.length; i++) {
				if(pid1 == Buses.groups[key].stops[i]) {
					pid1Groups.push(key);
				}

				if(pid2 == Buses.groups[key].stops[i]) {
					pid2Groups.push(key);
				}
			}
		}

		var result = {		from	: Router.getPlaceDetail(pid1),
							to		: Router.getPlaceDetail(pid2),
							routes	: [] };

		var commonGroup = _.intersection(pid1Groups, pid2Groups), bus;
		if(commonGroup.length > 0) {
			console.log('Single bus group found! Opts: ' + commonGroup.length);
			_.forEach(commonGroup, function(groupid) {
				bus = Router.renderRouteDetail(pid1, pid2, groupid);
				result.routes.push({	buses		: [bus],
										dist		: _.max(_.pluck(bus, 'dist')),
										changeovers	: [] });
			});
		}
		else {
			/** two bus territory */
			var commonStops = [], bus1, bus2;
			for(var i = 0; i < pid1Groups.length; i++) {
				for(var j = 0; j < pid2Groups.length; j++) {
					commonStops = _.intersection(Buses.groups[pid1Groups[i]].stops, Buses.groups[pid2Groups[j]].stops);
					_.forEach(commonStops, function(stop) {
						bus1 = Router.renderRouteDetail(pid1, stop, pid1Groups[i]);
						bus2 = Router.renderRouteDetail(stop, pid2, pid2Groups[j]);
						if(bus1.length > 0 && bus2.length > 0) {
							result.routes.push({	buses		: [bus1, bus2],
													dist		: _.max(_.pluck(bus1, 'dist')) + _.max(_.pluck(bus2, 'dist')),
													changeovers	: [Router.getPlaceDetail(stop)] });
						}
					});
				}
			}
		}
		/*
		var commonBus = _.intersection(pid1Buses, pid2Buses);

		if(commonBus.length > 0) {
			console.log('Single bus routes found! Opts: ' + commonBus.length);
			_.forEach(commonBus, function(bid) {
				result.routes.push(Router.renderOneBusRouteDetail(pid1, pid2, bid));
			});
		}
		else {
			var commonStops = [], _comStop = [];

			for(var i = 0; i < pid1Buses.length; i++) {
				for(var j = 0; j < pid2Buses.length; j++) {
					var pid1BusStops = _.pluck(Buses.routes[pid1Buses[i]].stops, 'pid');
					var pid2BusStops = _.pluck(Buses.routes[pid2Buses[j]].stops, 'pid');

					_comStop = _.intersection(pid1BusStops, pid2BusStops);

					if(_comStop.length > 0) {
						commonStops.push({bus1: pid1Buses[i], bus2: pid2Buses[j], ids: _.clone(_comStop) });
					}
				}
			}

			commonStops = _.uniq(commonStops);
			if(commonStops.length > 0) {
				console.log('Two bus routes found! Opts: ' + commonStops.length);
				_.forEach(commonStops, function(stop) {
					result.routes.push(Router.renderRouteDetail(pid1, pid2, stop));
				});
			}
		}
		*/

		result.routes = _.sortBy(result.routes, function(r) { return r.dist; });
		return result;
	},

	renderRouteDetail: function(pid1, pid2, groupid) {

		var routeid, routestops, pid1match, pid2match, routes = [];

		for(var i = 0; i < Buses.groups[groupid].routes.length; i++) {
			routeid = Buses.groups[groupid].routes[i];
			routestops = _.pluck(Buses.routes[routeid].stopsfrom, 'pid');
			if(_.contains(routestops, pid1) && _.contains(routestops, pid2)) {

				pid1match = _.find(Buses.routes[routeid].stopsfrom, { 'pid': pid1 });
				pid2match = _.find(Buses.routes[routeid].stopsfrom, { 'pid': pid2 });
				if(pid1match && pid2match && pid1match.dist <= pid2match.dist) {
					routes.push(Router.renderBusDetail(routeid, (pid2match.dist - pid1match.dist)));
				}
			}

			/** reverse journey of bus */
			routestops = _.pluck(Buses.routes[routeid].stopsto, 'pid');
			if(_.contains(routestops, pid1) && _.contains(routestops, pid2)) {
				pid1match = _.find(Buses.routes[routeid].stopsto, { 'pid': pid1 });
				pid2match = _.find(Buses.routes[routeid].stopsto, { 'pid': pid2 });
				if(pid1match && pid2match && pid1match.dist <= pid2match.dist) {
					/** tell render function that travel direction is reversed */
					routes.push(Router.renderBusDetail(routeid, (pid2match.dist - pid1match.dist), true));
				}
			}
		}

		return routes;
	},

	renderBusDetail: function(bid, distance, reverse) {
		/* bus only travels this way when returning, not on original journey */
		if(reverse) {
			return { routeno: Buses.routes[bid].routeno, from: Buses.routes[bid].to, to: Buses.routes[bid].from, dist: distance };
		}
		else {
			return { routeno: Buses.routes[bid].routeno, from: Buses.routes[bid].from, to: Buses.routes[bid].to, dist: distance };
		}
	},

	getPlaceDetail: function(pid) {
		return { name: Buses.places[pid].name, lat: Buses.places[pid].lat, lng: Buses.places[pid].lon };
	}
};
<|endoftext|>


<commit_before>define([ 'backbone' ], function(Backbone) {
    var Router = Backbone.Router.extend({
        routes: {
            '': 'home',
            'community': 'community_areas',
        }
    });
    return Router;
});
<commit_msg>fix trailing comma<commit_after>define([ 'backbone' ], function(Backbone) {
    var Router = Backbone.Router.extend({
        routes: {
            '': 'home',
            'community': 'community_areas'
        }
    });
    return Router;
});
<|endoftext|>


<commit_before>App.Router.map(function(){
	this.resource('App', { 'path' : '/' }, function() {
		this.resource('dashboard');
		this.resource('drones');
		this.resource('drone', { path: '/drones/:drone_id' });
		this.resource('assignments');
		this.resource('basestations');
		this.resource('users');
	});
	this.resource('login');
});

App.BaseRoute = Ember.Route.extend({
    beforeModel: function() {
        if(!this.customAdapter.linkLibrary.hasOwnProperty("login")) {
            this.customAdapter.find("home");
        }

		if (!App.currentSocketManager) {
			App.currentSocketManager = App.SocketManager.create({ url : this.customAdapter.host + this.customAdapter.linkLibrary["datasocket"] });
		}
    },

	setupController: function (controller, model) {
		this._super(controller, model);

		NProgress.done();
	},

	actions: {
		loading : function(transition, originRoute) {
			NProgress.start();
		},
	}
});

App.AuthRoute = App.BaseRoute.extend({
    beforeModel: function() {
        this._super();

        if (this.customAdapter.token().authToken == "") {
            this.transitionTo('login');
        }
    }
});

App.DashboardRoute = App.AuthRoute.extend({});

App.DronesRoute = App.AuthRoute.extend({
    model: function() {
        return this.customAdapter.find('drone').then(function(data){
            console.log(data.resource);
			return data.resource;
		});
    }
});

App.AssignmentsRoute = App.AuthRoute.extend({
    model: function() {
        return this.customAdapter.find('assignment').then(function(data){
            console.log(data.resource);
            return data.resource;
        });
    }
});

App.BasestationsRoute = App.AuthRoute.extend({
    model: function() {
        return this.customAdapter.find('basestation').then(function(data){
            console.log(data.resource);
            return data.resource;
        });
    }
});

App.UsersRoute = App.AuthRoute.extend({
    model: function() {
        return this.customAdapter.find('user').then(function(data){
            console.log(data.resource);
            return data.resource;
        });
    }
});

App.PopupRoute = App.AuthRoute.extend({
	renderTemplate: function(resource, resources) {
		this.render(resources);
		this.render(resource, {
			into: 'App',
			outlet: 'modal'
		});
	}
});

App.DroneRoute = App.PopupRoute.extend({

    model: function(params) {
        return this.customAdapter.find('drone', params.drone_id);
    },
	renderTemplate: function() {
		this._super('drone', 'drones');
	}
});

App.LoginRoute = App.BaseRoute.extend({
	renderTemplate : function() {
		this.render('login', {into: ''});
	}
});<commit_msg>removed debug code<commit_after>App.Router.map(function(){
	this.resource('App', { 'path' : '/' }, function() {
		this.resource('dashboard');
		this.resource('drones');
		this.resource('drone', { path: '/drones/:drone_id' });
		this.resource('assignments');
		this.resource('basestations');
		this.resource('users');
	});
	this.resource('login');
});

App.BaseRoute = Ember.Route.extend({
    beforeModel: function() {
        if(!this.customAdapter.linkLibrary.hasOwnProperty("login")) {
            this.customAdapter.find("home");
        }

		if (!App.currentSocketManager) {
			App.currentSocketManager = App.SocketManager.create({ url : this.customAdapter.host + this.customAdapter.linkLibrary["datasocket"] });
		}
    },

	setupController: function (controller, model) {
		this._super(controller, model);

		NProgress.done();
	},

	actions: {
		loading : function(transition, originRoute) {
			NProgress.start();
		},
	}
});

App.AuthRoute = App.BaseRoute.extend({
    beforeModel: function() {
        this._super();

        if (this.customAdapter.token().authToken == "") {
            this.transitionTo('login');
        }
    }
});

App.DashboardRoute = App.AuthRoute.extend({});

App.DronesRoute = App.AuthRoute.extend({
    model: function() {
        return this.customAdapter.find('drone').then(function(data){
			return data.resource;
		});
    }
});

App.AssignmentsRoute = App.AuthRoute.extend({
    model: function() {
        return this.customAdapter.find('assignment').then(function(data){
            return data.resource;
        });
    }
});

App.BasestationsRoute = App.AuthRoute.extend({
    model: function() {
        return this.customAdapter.find('basestation').then(function(data){
            return data.resource;
        });
    }
});

App.UsersRoute = App.AuthRoute.extend({
    model: function() {
        return this.customAdapter.find('user').then(function(data){
            return data.resource;
        });
    }
});

App.PopupRoute = App.AuthRoute.extend({
	renderTemplate: function(resource, resources) {
		this.render(resources);
		this.render(resource, {
			into: 'App',
			outlet: 'modal'
		});
	}
});

App.DroneRoute = App.PopupRoute.extend({

    model: function(params) {
        return this.customAdapter.find('drone', params.drone_id);
    },
	renderTemplate: function() {
		this._super('drone', 'drones');
	}
});

App.LoginRoute = App.BaseRoute.extend({
	renderTemplate : function() {
		this.render('login', {into: ''});
	}
});<|endoftext|>


<commit_before>Todos.Router.map(function() {
    this.resource('todos', { path: '/' }, function() {
        this.route('active');
        this.route('completed');
    });
});

Todos.TodosRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('todo');
    }
});

Todos.TodosIndexRoute = Ember.Route.extend({
    model: function() {
        return this.modelFor('todos');
    }
});

Todos.TodosActiveRoute = Ember.Route.extend({
    model: function () {
        return this.store.filter('todo', function(todo) {
            return !todo.get('isCompleted');
        });
    },
    renderTemplate: function(controller) {
        this.render('todos/index', {controller: controller});
    }
});

Todos.TodosCompletedRoute = Ember.Route.extend({
    model: function () {
        return this.store.filter('todo', function(todo) {
            return todo.get('isCompleted');
        });
    },
    renderTemplate: function(controller) {
        this.render('todos/index', {controller: controller});
    }
});<commit_msg>route refactoring. Man, do I love javascript.<commit_after>Todos.Router.map(function() {
    this.resource('todos', { path: '/' }, function() {
        this.route('active');
        this.route('completed');
    });
});

Todos.TodosRoute = Ember.Route.extend({
    model: function() {
        return this.store.find('todo');
    }
});

Todos.TodosIndexRoute = Ember.Route.extend({
    model: function() {
        return this.modelFor('todos');
    }
});

Todos.TodosBaseFilterRoute = Ember.Route.extend({
   model: function () {
        return this.store.filter('todo', this.getFilteredList);
    },
    renderTemplate: function(controller) {
        this.render('todos/index', {controller: controller});
    }
});

Todos.TodosActiveRoute = Todos.TodosBaseFilterRoute.extend({
    getFilteredList: function(todo) {
        return !todo.get('isCompleted');
    }
});

Todos.TodosCompletedRoute = Todos.TodosBaseFilterRoute.extend({
    getFilteredList: function(todo) {
        return todo.get('isCompleted');
    }
});
<|endoftext|>