<commit_before>/*
 *  player.js
 *  2014/09/05
 *  @auther minimo
 *  This Program is MIT license.
 */
(function() {

var KEYBOARD_MOVE = {
      0: { x:  1.0, y:  0.0 },
     45: { x:  0.7, y: -0.7 },
     90: { x:  0.0, y: -1.0 },
    135: { x: -0.7, y: -0.7 },
    180: { x: -1.0, y:  0.0 },
    225: { x: -0.7, y:  0.7 },
    270: { x:  0.0, y:  1.0 },
    315: { x:  0.7, y:  0.7 },
};

tm.define("pb3.Player", {
    superClass: "tm.display.Sprite",
    layer: LAYER_OBJECT,

    //当り判定サイズ
    width: 2,
    height: 2,

    control: true,  //操作可能フラグ
    shotON: false,  //ショットフラグ
    mouseON: false, //マウス操作中フラグ

    isCollision: false, //当り判定有効フラグ

    timeMuteki: 0, //無敵フレーム残り時間

    speed: 10,      //移動係数
    type: 0,        //自機タイプ(0:赤 1:緑 2:青)

    shotPower: 10,      //ショット威力
    shotInterval: 6,    //ショット間隔

    rollcount: 50,
    pitchcount: 50,

    parentScene: null,
    indecies: [0,1,2,3,4,4,4,5,6,7,8],

    init: function() {
        this.superInit("gunship", 48, 48);
        this.setFrameIndex(4);
//        this.setScale(1.5);

        this.setupBody();

        //当り判定設定
        this.boundingType = "circle";
        this.radius = 2;
        this.checkHierarchy = true;

        this.time = 0;
        this.changeInterval = 0;
        return this;
    },

    //機体準備
    setupBody: function() {
        //コア
        core = tm.display.Shape(16, 16).addChildTo(this);
        core.canvas.setFillStyle(
            tm.graphics.RadialGradient(8, 8, 0, 8, 8, 8)
                .addColorStopList([
                    {offset:0.0, color: "hsla(200, 60%, 70%, 1.0)"},
                    {offset:0.5, color: "hsla(240, 60%, 70%, 1.0)"},
                    {offset:1.0, color: "hsla(240, 60%, 50%, 0.0)"},
                ]).toStyle()
            ).fillRect(0, 0, 16, 16);
        core.tweener.clear();
        core.tweener.scale(1.0, 100, "easeInOutQuad").scale(0.5, 150, "easeInOutQuad").setLoop(true);

        //ビット
        this.bits = [];
        this.bits.status = 0; //0:close 1:open1 2:open2 3:rollingStanby 4:rollingReady
        this.bits.roll = 0;
        this.bits[0] = pb3.PlayerBit().addChildTo(this);
        this.bits[1] = pb3.PlayerBit().addChildTo(this);
        this.bits[2] = pb3.PlayerBit().addChildTo(this);
        this.bits[3] = pb3.PlayerBit().addChildTo(this);

        this.openBit(0);
    },

    update: function() {
        //操作系
        if (this.control) {
            //マウス操作
            var p = app.pointing;
            if (p.getPointing()) {
                var pt = this.parentScene.pointer;
                this.x += (pt.x - this.x)/this.speed;
                this.y += (pt.y - this.y)/this.speed;

                this.mouseON = true;
                this.shotON = true;
            } else {
                this.mouseON = false;
                this.shotON = false;
            }

            //キーボード操作
            var kb = app.keyboard;
            var angle = kb.getKeyAngle();
            if (angle !== null) {
                var m = KEYBOARD_MOVE[angle];
                this.x += m.x*this.speed*0.4;
                this.y += m.y*this.speed*0.4;
            }
            if (!this.mouseON) this.shotON = app.keyboard.getKey("Z");

            //ショットタイプ変更（テスト用）
            if (app.keyboard.getKey("X") && this.time > this.changeInterval) {
                this.type = (this.type+1)%3;
                this.openBit(this.type);
                this.changeInterval = this.time+30;
            }

            //移動範囲の制限
            this.x = Math.clamp(this.x, 16, GS_W-16);
            this.y = Math.clamp(this.y, 16, GS_H-16);

            //ショット
            if (this.shotON && this.time % this.shotInterval == 0) this.enterShot();
        }

        //機体ロール
        var x = ~~this.x;
        var bx = ~~this.bx;
        if (bx > x) {
            this.rollcount-=2;
            if (this.rollcount < 0) this.rollcount = 0;
        }
        if (bx < x) {
            this.rollcount+=2;
            if (this.rollcount > 100) this.rollcount = 100;
        }
        var vx = Math.abs(bx - x);
        if (vx < 2) {
            if (this.rollcount < 50) this.rollcount+=2;
            else this.rollcount-=2;
            if (this.rollcount < 0) this.rollcount = 0;
            if (this.rollcount > 100) this.rollcount = 100;
        }
        //機体ロール
        this.setFrameIndex(this.indecies[Math.clamp(~~(this.rollcount/10),0, 9)]);

        this.bx = this.x;
        this.by = this.y;
        this.time++;
        this.timeMuteki--;
    },

    //被弾処理
    damage: function() {
        if (this.timeMuteki>0 || MUTEKI) return;

        pb3.burnParticlePlayer(this.x, this.y).addChildTo(this.parentScene);
        app.playSE("explodePlayer");

        this.parentScene.stageMiss++;
        this.parentScene.life--;
        this.parentScene.dispLife.dec();
        if (this.parentScene.life > -1) {
            this.startup();
            this.parentScene.eraseBullet();
            this.parentScene.eraseBulletTime = 60;
        } else {
            this.setPosition(GS_W*0.5, GS_H*3);
            this.control = false;
        }
    },

    //ショット発射
    enterShot: function() {
        var shotPower = this.shotPower;
        //自機から
        pb3.ShotBullet(0, shotPower, 0).addChildTo(this.parentScene).setPosition(this.x   , this.y-16);
        pb3.ShotBullet(0, shotPower, 0).addChildTo(this.parentScene).setPosition(this.x+16, this.y-8);
        pb3.ShotBullet(0, shotPower, 0).addChildTo(this.parentScene).setPosition(this.x-16, this.y-8);
    },

    //ビット展開
    openBit: function(type) {
        switch (type) {
            case 0:
                //赤（前方集中型）
                this.bits[0].tweener.clear().to({ x:  5, y:-32, rotation:0, alpha:1}, 300).call(function(){this.tweener.clear().moveBy(-30,0,500,"easeInOutSine").moveBy( 30,0,500,"easeInOutSine").setLoop(true);}.bind(this.bits[0]));
                this.bits[1].tweener.clear().to({ x: -5, y:-32, rotation:0, alpha:1}, 300).call(function(){this.tweener.clear().moveBy( 30,0,500,"easeInOutSine").moveBy(-30,0,500,"easeInOutSine").setLoop(true);}.bind(this.bits[1]));
                this.bits[2].tweener.clear().to({ x: 20, y:-24, rotation:0, alpha:1}, 300).call(function(){this.tweener.clear().moveBy(-40,0,500,"easeInOutSine").moveBy( 40,0,500,"easeInOutSine").setLoop(true);}.bind(this.bits[2]));
                this.bits[3].tweener.clear().to({ x:-20, y:-24, rotation:0, alpha:1}, 300).call(function(){this.tweener.clear().moveBy( 40,0,500,"easeInOutSine").moveBy(-40,0,500,"easeInOutSine").setLoop(true);}.bind(this.bits[3]));
                break;
            case 1:
                //緑（方向変更型）
                this.bits[0].tweener.clear().to({ x: 36, y:0, rotation:0, alpha:1}, 300);
                this.bits[1].tweener.clear().to({ x:-36, y:0, rotation:0, alpha:1}, 300);
                this.bits[2].tweener.clear().to({ x: 48, y:0, rotation:0, alpha:1}, 300);
                this.bits[3].tweener.clear().to({ x:-48, y:0, rotation:0, alpha:1}, 300);
                break;
            case 2:
                //青（広範囲型）
                this.bits[0].tweener.clear().to({ x: 36, y:16, rotation:  5, alpha:1}, 300);
                this.bits[1].tweener.clear().to({ x:-36, y:16, rotation: -5, alpha:1}, 300);
                this.bits[2].tweener.clear().to({ x: 60, y:24, rotation: 10, alpha:1}, 300);
                this.bits[3].tweener.clear().to({ x:-60, y:24, rotation:-10, alpha:1}, 300);
                break;
        }
    },

    //ビット収納
    closeBit: function() {
        if (this.bits.status == 0) return;
        this.bits.status = 0;
        this.bits[0].tweener.clear().to({ x:0, y: 0, alpha:0}, 300);
        this.bits[1].tweener.clear().to({ x:0, y: 0, alpha:0}, 300);
        this.bits[2].tweener.clear().to({ x:0, y: 0, alpha:0}, 300);
        this.bits[3].tweener.clear().to({ x:0, y: 0, alpha:0}, 300);
    },

    //プレイヤー投入時演出
    startup: function() {
        this.x = GS_W/2;
        this.y = GS_H+128;
        this.tweener.clear()
            .wait(2000)
            .to({x: GS_W/2, y: GS_H-128}, 2000, "easeOutQuint")
            .call(function(){
                this.shotON = true;
                this.control = true;
                this.isCollision = true;
                this.timeMuteki = 180;
            }.bind(this));
        this.shotON = false;
        this.control = false;
        this.isCollision = false;
        this.parentScene.timeVanish = 300;
    },

    //ステージ開始時演出
    stageStartup: function() {
        this.x = GS_W/2;
        this.y = GS_H+128;
        this.tweener.clear()
            .to({x: GS_W/2, y: GS_H/2+32}, 1000, "easeOutCubic")
            .to({x: GS_W/2, y: GS_H-64  }, 1000)
            .call(function(){
                this.shotON = true;
                this.control = true;
                this.isCollision = true;
                this.timeMuteki = 180;
            }.bind(this));
        this.shotON = false;
        this.control = false;
        this.isCollision = false;
    },
});

//ビット
tm.define("pb3.PlayerBit", {
    superClass: "tm.display.Sprite",

    active: false,

    init: function() {
        this.superInit("bit", 32, 32);
        this.setScale(0.8);
        this.parentScene = app.currentScene;
        this.index = 0;

        this.alpha = 1;

        this.beforeX = 0;
        this.beforeY = 0;

        this.time = 0;
    },

    update: function() {
        if (this.time % 2 == 0) {
            this.index = (this.index+1)%9;
            this.setFrameIndex(this.index);
        }
        var player = app.player;
        if (player.shotON) {
            if (this.time % player.shotInterval == 0) {
                var x = this.x + player.x;
                var y = this.y + player.y;
                pb3.ShotBullet(this.rotation, player.shotPower).addChildTo(player.parentScene).setPosition(x, y-4);
            }
        }

        if (player.type == 1) {
        }
        this.time++;
    },
});

//プレイヤー操作用ポインタ
tm.define("pb3.PlayerPointer", {
    superClass: "tm.display.Shape",
    layer: LAYER_OBJECT_LOWER,

    init: function() {
        this.superInit(32, 32);
        this.canvas.lineWidth = 3;
        this.canvas.globalCompositeOperation = "lighter";
        this.canvas.strokeStyle = "rgb(255, 255, 255)";
        this.canvas.strokeArc(16, 16, 8, Math.PI*2, 0, true);
    },

    update: function() {
        var p = app.pointing;
        if (app.player.control && p.getPointing()) {
            if (~~(this.x) == ~~(app.player.x) && ~~(this.y) == ~~(app.player.y)) {
                this.alpha = 0;
            } else {
                this.alpha = 0.5;
            }
            this.x += (p.position.x - p.prevPosition.x);
            this.y += (p.position.y - p.prevPosition.y);
            this.x = Math.clamp(this.x, 16, GS_W-16);
            this.y = Math.clamp(this.y, 16, GS_H-16);
        } else {
            this.x = app.player.x;
            this.y = app.player.y;
            this.alpha = 0;
        }
    },
});

})();<commit_msg>update player<commit_after>/*
 *  player.js
 *  2014/09/05
 *  @auther minimo
 *  This Program is MIT license.
 */
(function() {

var KEYBOARD_MOVE = {
      0: { x:  1.0, y:  0.0 },
     45: { x:  0.7, y: -0.7 },
     90: { x:  0.0, y: -1.0 },
    135: { x: -0.7, y: -0.7 },
    180: { x: -1.0, y:  0.0 },
    225: { x: -0.7, y:  0.7 },
    270: { x:  0.0, y:  1.0 },
    315: { x:  0.7, y:  0.7 },
};

tm.define("pb3.Player", {
    superClass: "tm.display.Sprite",
    layer: LAYER_OBJECT,

    //当り判定サイズ
    width: 2,
    height: 2,

    control: true,  //操作可能フラグ
    shotON: false,  //ショットフラグ
    mouseON: false, //マウス操作中フラグ

    isCollision: false, //当り判定有効フラグ

    timeMuteki: 0, //無敵フレーム残り時間

    speed: 10,      //移動係数
    type: 0,        //自機タイプ(0:赤 1:緑 2:青)

    shotPower: 10,      //ショット威力
    shotInterval: 6,    //ショット間隔

    rollcount: 50,
    pitchcount: 50,

    parentScene: null,
    indecies: [0,1,2,3,4,4,4,5,6,7,8],

    init: function() {
        this.superInit("gunship", 48, 48);
        this.setFrameIndex(4);
//        this.setScale(1.5);

        this.setupBody();

        //当り判定設定
        this.boundingType = "circle";
        this.radius = 2;
        this.checkHierarchy = true;

        this.time = 0;
        this.changeInterval = 0;
        return this;
    },

    //機体準備
    setupBody: function() {
        //コア
        core = tm.display.Shape(16, 16).addChildTo(this);
        core.canvas.setFillStyle(
            tm.graphics.RadialGradient(8, 8, 0, 8, 8, 8)
                .addColorStopList([
                    {offset:0.0, color: "hsla(200, 60%, 70%, 1.0)"},
                    {offset:0.5, color: "hsla(240, 60%, 70%, 1.0)"},
                    {offset:1.0, color: "hsla(240, 60%, 50%, 0.0)"},
                ]).toStyle()
            ).fillRect(0, 0, 16, 16);
        core.tweener.clear();
        core.tweener.scale(1.0, 100, "easeInOutQuad").scale(0.5, 150, "easeInOutQuad").setLoop(true);

        //ビット
        this.bits = [];
        this.bits.status = 0; //0:close 1:open1 2:open2 3:rollingStanby 4:rollingReady
        this.bits.roll = 0;
        this.bits[0] = pb3.PlayerBit(0).addChildTo(this);
        this.bits[1] = pb3.PlayerBit(1).addChildTo(this);
        this.bits[2] = pb3.PlayerBit(2).addChildTo(this);
        this.bits[3] = pb3.PlayerBit(3).addChildTo(this);

        this.openBit(0);
    },

    update: function() {
        //操作系
        if (this.control) {
            //マウス操作
            var p = app.pointing;
            if (p.getPointing()) {
                var pt = this.parentScene.pointer;
                this.x += (pt.x - this.x)/this.speed;
                this.y += (pt.y - this.y)/this.speed;

                this.mouseON = true;
                this.shotON = true;
            } else {
                this.mouseON = false;
                this.shotON = false;
            }

            //キーボード操作
            var kb = app.keyboard;
            var angle = kb.getKeyAngle();
            if (angle !== null) {
                var m = KEYBOARD_MOVE[angle];
                this.x += m.x*this.speed*0.4;
                this.y += m.y*this.speed*0.4;
            }
            if (!this.mouseON) this.shotON = app.keyboard.getKey("Z");

            //ショットタイプ変更（テスト用）
            if (app.keyboard.getKey("X") && this.time > this.changeInterval) {
                this.type = (this.type+1)%3;
                this.openBit(this.type);
                this.changeInterval = this.time+30;
            }

            //移動範囲の制限
            this.x = Math.clamp(this.x, 16, GS_W-16);
            this.y = Math.clamp(this.y, 16, GS_H-16);

            //ショット
            if (this.shotON && this.time % this.shotInterval == 0) this.enterShot();
        }

        //機体ロール
        var x = ~~this.x;
        var bx = ~~this.bx;
        if (bx > x) {
            this.rollcount-=2;
            if (this.rollcount < 0) this.rollcount = 0;
        }
        if (bx < x) {
            this.rollcount+=2;
            if (this.rollcount > 100) this.rollcount = 100;
        }
        var vx = Math.abs(bx - x);
        if (vx < 2) {
            if (this.rollcount < 50) this.rollcount+=2;
            else this.rollcount-=2;
            if (this.rollcount < 0) this.rollcount = 0;
            if (this.rollcount > 100) this.rollcount = 100;
        }
        //機体ロール
        this.setFrameIndex(this.indecies[Math.clamp(~~(this.rollcount/10),0, 9)]);

        this.bx = this.x;
        this.by = this.y;
        this.time++;
        this.timeMuteki--;
    },

    //被弾処理
    damage: function() {
        if (this.timeMuteki>0 || MUTEKI) return;

        pb3.burnParticlePlayer(this.x, this.y).addChildTo(this.parentScene);
        app.playSE("explodePlayer");

        this.parentScene.stageMiss++;
        this.parentScene.life--;
        this.parentScene.dispLife.dec();
        if (this.parentScene.life > -1) {
            this.startup();
            this.parentScene.eraseBullet();
            this.parentScene.eraseBulletTime = 60;
        } else {
            this.setPosition(GS_W*0.5, GS_H*3);
            this.control = false;
        }
    },

    //ショット発射
    enterShot: function() {
        var shotPower = this.shotPower;
        //自機から
        pb3.ShotBullet(0, shotPower, 0).addChildTo(this.parentScene).setPosition(this.x   , this.y-16);
        pb3.ShotBullet(0, shotPower, 0).addChildTo(this.parentScene).setPosition(this.x+16, this.y-8);
        pb3.ShotBullet(0, shotPower, 0).addChildTo(this.parentScene).setPosition(this.x-16, this.y-8);
    },

    //ビット展開
    openBit: function(type) {
        switch (type) {
            case 0:
                //赤（前方集中型）
                this.bits[0].tweener.clear().to({ x:  5, y:-32, rotation: 2, alpha:1}, 300).call(function(){this.tweener.clear().moveBy(-40,0,500,"easeInOutSine").moveBy( 40,0,500,"easeInOutSine").setLoop(true);}.bind(this.bits[0]));
                this.bits[1].tweener.clear().to({ x: -5, y:-32, rotation:-2, alpha:1}, 300).call(function(){this.tweener.clear().moveBy( 40,0,500,"easeInOutSine").moveBy(-40,0,500,"easeInOutSine").setLoop(true);}.bind(this.bits[1]));
                this.bits[2].tweener.clear().to({ x: 20, y:-24, rotation: 2, alpha:1}, 300).call(function(){this.tweener.clear().moveBy(-50,0,500,"easeInOutSine").moveBy( 50,0,500,"easeInOutSine").setLoop(true);}.bind(this.bits[2]));
                this.bits[3].tweener.clear().to({ x:-20, y:-24, rotation:-2, alpha:1}, 300).call(function(){this.tweener.clear().moveBy( 50,0,500,"easeInOutSine").moveBy(-50,0,500,"easeInOutSine").setLoop(true);}.bind(this.bits[3]));
                break;
            case 1:
                //緑（方向変更型）
                this.bits[0].tweener.clear().to({ x: 36, y:0, rotation:0, alpha:1}, 300);
                this.bits[1].tweener.clear().to({ x:-36, y:0, rotation:0, alpha:1}, 300);
                this.bits[2].tweener.clear().to({ x: 48, y:0, rotation:0, alpha:1}, 300);
                this.bits[3].tweener.clear().to({ x:-48, y:0, rotation:0, alpha:1}, 300);
                break;
            case 2:
                //青（広範囲型）
                this.bits[0].tweener.clear().to({ x: 36, y:16, rotation:  5, alpha:1}, 300);
                this.bits[1].tweener.clear().to({ x:-36, y:16, rotation: -5, alpha:1}, 300);
                this.bits[2].tweener.clear().to({ x: 60, y:24, rotation: 10, alpha:1}, 300);
                this.bits[3].tweener.clear().to({ x:-60, y:24, rotation:-10, alpha:1}, 300);
                break;
        }
    },

    //ビット収納
    closeBit: function() {
        if (this.bits.status == 0) return;
        this.bits.status = 0;
        this.bits[0].tweener.clear().to({ x:0, y: 0, alpha:0}, 300);
        this.bits[1].tweener.clear().to({ x:0, y: 0, alpha:0}, 300);
        this.bits[2].tweener.clear().to({ x:0, y: 0, alpha:0}, 300);
        this.bits[3].tweener.clear().to({ x:0, y: 0, alpha:0}, 300);
    },

    //プレイヤー投入時演出
    startup: function() {
        this.x = GS_W/2;
        this.y = GS_H+128;
        this.tweener.clear()
            .wait(2000)
            .to({x: GS_W/2, y: GS_H-128}, 2000, "easeOutQuint")
            .call(function(){
                this.shotON = true;
                this.control = true;
                this.isCollision = true;
                this.timeMuteki = 180;
            }.bind(this));
        this.shotON = false;
        this.control = false;
        this.isCollision = false;
        this.parentScene.timeVanish = 300;
    },

    //ステージ開始時演出
    stageStartup: function() {
        this.x = GS_W/2;
        this.y = GS_H+128;
        this.tweener.clear()
            .to({x: GS_W/2, y: GS_H/2+32}, 1000, "easeOutCubic")
            .to({x: GS_W/2, y: GS_H-64  }, 1000)
            .call(function(){
                this.shotON = true;
                this.control = true;
                this.isCollision = true;
                this.timeMuteki = 180;
            }.bind(this));
        this.shotON = false;
        this.control = false;
        this.isCollision = false;
    },
});

//ビット
tm.define("pb3.PlayerBit", {
    superClass: "tm.display.Sprite",

    id: 0,
    active: false,

    init: function(id) {
        this.superInit("bit", 32, 32);
        this.setScale(0.8);
        this.parentScene = app.currentScene;
        this.index = 0;
        this.id = id;

        this.alpha = 1;

        this.beforeX = 0;
        this.beforeY = 0;

        this.time = 0;
    },

    update: function() {
        if (this.time % 2 == 0) {
            if (this.id % 2 == 0) {
                this.index--;
                if (this.index < 0) this.index = 8;
            } else {
                this.index = (this.index+1)%9;
            }
            this.setFrameIndex(this.index);
        }
        var player = app.player;
        if (player.shotON) {
            if (this.time % player.shotInterval == 0) {
                var x = this.x + player.x;
                var y = this.y + player.y;
                pb3.ShotBullet(this.rotation, player.shotPower).addChildTo(player.parentScene).setPosition(x, y-4);
            }
        }

        if (player.type == 1) {
        }
        this.time++;
    },
});

//プレイヤー操作用ポインタ
tm.define("pb3.PlayerPointer", {
    superClass: "tm.display.Shape",
    layer: LAYER_OBJECT_LOWER,

    init: function() {
        this.superInit(32, 32);
        this.canvas.lineWidth = 3;
        this.canvas.globalCompositeOperation = "lighter";
        this.canvas.strokeStyle = "rgb(255, 255, 255)";
        this.canvas.strokeArc(16, 16, 8, Math.PI*2, 0, true);
    },

    update: function() {
        var p = app.pointing;
        if (app.player.control && p.getPointing()) {
            if (~~(this.x) == ~~(app.player.x) && ~~(this.y) == ~~(app.player.y)) {
                this.alpha = 0;
            } else {
                this.alpha = 0.5;
            }
            this.x += (p.position.x - p.prevPosition.x);
            this.y += (p.position.y - p.prevPosition.y);
            this.x = Math.clamp(this.x, 16, GS_W-16);
            this.y = Math.clamp(this.y, 16, GS_H-16);
        } else {
            this.x = app.player.x;
            this.y = app.player.y;
            this.alpha = 0;
        }
    },
});

})();<|endoftext|>


<commit_before>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @class
 * @constructor
 * @description
 * The openlayers map object wrapper
 */
Ext.define ("viewer.viewercontroller.openlayers.OpenLayersMap",{
    extend: "viewer.viewercontroller.controller.Map",
    layersLoading : null,
    utils:null,
    config:{
        viewerController:null
    },
    constructor: function(config){
        viewer.viewercontroller.openlayers.OpenLayersMap.superclass.constructor.call(this, config);
        this.initConfig(config);
        this.utils = Ext.create("viewer.viewercontroller.openlayers.Utils");
        var maxBounds=null;
        if (config.options.fullextent){
            var fullExtent = Ext.create("viewer.viewercontroller.controller.Extent",config.options.fullextent);
            maxBounds = new OpenLayers.Bounds(fullExtent.minx, fullExtent.miny, fullExtent.maxx, fullExtent.maxy);
        }
        else{
            //fallback for bounds: the extent of the Netherlands
            maxBounds= new OpenLayers.Bounds(12000,304000,280000,620000);
        }
        config["center"] = maxBounds.getCenterLonLat();

        config.maxExtent = maxBounds;

        this.frameworkMap=new OpenLayers.Map(config.domId,config);
        this.frameworkMap.centerLayerContainer();

        this.layersLoading = 0;
        this.markerLayer=null;
        this.defaultIcon=null;
        this.markers=new Object();
        this.getFeatureInfoControl = null;
        this.addListener(viewer.viewercontroller.controller.Event.ON_LAYER_REMOVED,this.layerRemoved, this);
        return this;
    },

    /**
    *See @link Map.getAllWMSLayers
    */
    getAllWMSLayers : function(){
        var lagen = new Array();
        for(var i = 0 ; i < this.layers.length;i++){
            if(this.layers[i] instanceof OpenLayersWMSLayer){
                lagen.push(this.layers[i]);
            }
        }
        return lagen;
    },

    /**
    *See @link Map.getAllVectorLayers
    */
    getAllVectorLayers : function(){
        var lagen = new Array();
        for(var i = 0 ; i < this.layers.length;i++){
            if(this.layers[i] instanceof OpenLayersVectorLayer){
                lagen.push(this.layers[i]);
            }
        }
        return lagen;
    },

    /**
    *See @link Map.remove
    */
    remove : function(){
        this.getFrameworkMap().destroy();
    },

    /**
    *Add a layer. Also see @link Map.addLayer
    **/
    addLayer : function(layer){
        this.superclass.addLayer.call(this,layer);
        this.getFrameworkMap().addLayer(layer.getFrameworkLayer());
    },

    /**
    *remove the specific layer. See @link Map.removeLayer
    **/
    removeLayer : function(layer){
        // don't call super function, but manually manage the removal of layers from this.layers

        if (layer instanceof viewer.viewercontroller.openlayers.OpenLayersWMSLayer){
            if(layer.getGetFeatureInfoControl()!=null){
                layer.getGetFeatureInfoControl().destroy();
            }
            if (layer.getMapTipControl()!=null){
                layer.getMapTipControl().destroy();
            }
        }
        layer.getFrameworkLayer().destroy(false);
    },

    layerRemoved : function (map, options){
        var l = options.layer.getFrameworkLayer();
        for ( var i = 0 ; i < this.layers.length ;i++){
            var frameworkLayer = this.layers[i].getFrameworkLayer();
            if(frameworkLayer.id == l.id){
                this.layers.splice(i,1);
                break;
            }
        }
    },

    setLayerVisible : function (layer, visible){
        this.superclass.setLayerVisible.call(this,layer,visible);
        layer.setVisible(visible);
    },

    /**
    * see @link Map.setLayerIndex
    */
    setLayerIndex : function (layer, newIndex){
        if (!(layer instanceof OpenLayersLayer)){
            throw("OpenLayersMap.setLayerIndex(): Given layer not of type OpenLayersLayer.");
        }
        this.getFrameworkMap().setLayerIndex(layer.getFrameworkLayer(),newIndex);
        return Map.prototype.setLayerIndex(layer,newIndex);
    },

    /**
    * Sets the getfeatureinfo control of this map
    */
    setGetFeatureInfoControl : function (control){
        if( control.type != Tool.GET_FEATURE_INFO){
            throw ("Type of given control not of type GET_FEATURE_INFO, but: " + control.type);
        }
        this.getFeatureInfoControl = control;
    },

    /**
    * Move the viewport to the maxExtent. See @link Map.zoomToMaxExtent
    **/
    zoomToMaxExtent : function (){
        this.getFrameworkMap().zoomToExtent(this.getFrameworkMap().getMaxExtent());
    },
    /**
    * See @link Map.zoomToExtent
    **/
    zoomToExtent : function(extent){
        var bounds=Utils.createBounds(extent)
        this.getFrameworkMap().zoomToExtent(bounds);
    },

    /**
    * See @link Map.zoomToScale
    * @deprecated, use zoomToResolution because it zooms to a resolution and not a scale
    */
    zoomToScale : function(scale){
        this.getFrameworkMap().zoomToResolution(scale);
    },

    /**
    * See @link Map.zoomToResolution
    */
    zoomToResolution : function(resolution){
        this.getFrameworkMap().zoomTo(this.getFrameworkMap().getZoomForResolution(resolution));
    },

    /**
    * See @link Map.setMaxExtent
    * WARNING: Bug in openlayers: doesn't change the maxextent
    * As workaround add the maxExtent when initing the map
    */
    setMaxExtent : function(extent){
        if (this.getFrameworkMap()!=null){
            this.getFrameworkMap().setOptions({
                maxExtent: Utils.createBounds(extent)
            });
        }
    },

    /**
    * See @link Map.getMaxExtent
    */
    getMaxExtent : function(){
        return Utils.createExtent(this.getFrameworkMap().getMaxExtent());
    },

    /**
    * See @link Map.getExtent
    */
    getExtent : function(){
        var extent = this.utils.createExtent(this.getFrameworkMap().getExtent());
        return extent;
    },

    /*TODO:
        doIdentify : function(x,y){}
        update : function(){}
        removeMarker : function(markerName){}
        */
    /**
    *see @link Map.setMarker
    *TODO: marker icon path...
    */
    setMarker : function(markerName,x,y,type){
        if (this.markerLayer==null){
            this.markerLayer = new OpenLayers.Layer.Markers("Markers");
            this.frameworkMap.addLayer(this.markerLayer);
            var size = new OpenLayers.Size(17,17);
            var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
            this.defaultIcon= new OpenLayers.Icon('scripts/openlayers/img/marker.png',size,offset);
        }
        /*According the 'type' load a icon: no types yet only default*/
        var icon= this.defaultIcon.clone();
        this.markers[markerName]= new OpenLayers.Marker(new OpenLayers.LonLat(x,y),icon);
        this.markerLayer.addMarker(this.markers[markerName]);
    },

    /**
    * see @link Map.removeMarker
    */
    removeMarker : function(markerName){
        if (this.markers[markerName] && this.markerLayer!=null){
            this.markerLayer.removeMarker(this.markers[markerName]);
        }
    },

    /**
     * @see Ext.util.Observable#addListener
     * @param event the event
     * @param handler the handler
     * @param scope the scope
     * Overwrite the addListener. Register event on the OpenLayers Map (only once)
     * If the event is thrown by the OpenLayers event the given handlers are called.
     */
    addListener : function(event,handler,scope){
        var olSpecificEvent = this.viewerController.mapComponent.getSpecificEventName(event);
        if(olSpecificEvent){
            if(!scope){
                scope = this;
            }
            /* Add event to OpenLayersMap only once, to prevent multiple fired events.
             * count the events for removing the listener again.
             */
            if(this.enabledEvents[olSpecificEvent]){
                this.enabledEvents[olSpecificEvent]++;
            }else{
                this.enabledEvents[olSpecificEvent] = 1;
                this.frameworkMap.events.register(olSpecificEvent, this, this.handleEvent);
            }
        }
        viewer.viewercontroller.openlayers.OpenLayersMap.superclass.addListener.call(this,event,handler,scope);
    },

    /**
     * @see Ext.util.Observable#removeListener
     * @param event the event
     * @param handler the handler
     * @param scope the scope
     * Overwrite the removeListener. Unregister the event on the OpenLayers Map if there
     * are no listeners anymore.
     */
    removeListener : function (event,handler,scope){
        var olSpecificEvent = this.viewerController.mapComponent.getSpecificEventName(event);
        if(olSpecificEvent){
            if(!scope){
                scope = this;
            }
            /* Remove event from OpenLayersMap if the number of events == 0
             * If there are no listeners for the OpenLayers event, remove the listener.
             */
            if(this.enabledEvents[olSpecificEvent]){
                this.enabledEvents[olSpecificEvent]--;
                if (this.enabledEvents[olSpecificEvent] <= 0){
                    this.enabledEvents[olSpecificEvent]=0;
                    this.frameworkMap.events.unregister(olSpecificEvent, this, this.handleEvent);
                }
            }
            viewer.viewercontroller.openlayers.OpenLayersMap.superclass.removeListener.call(this,event,handler,scope);
        }else{
            this.viewerController.logger.warning("Event not listed in OpenLayersMapComponent >"+ event + "<. The application  might not work correctly.");
        }
    },

    /**
     * Handles the events fired by OpenLayers.Map and propagates them to the registered objects.
     *
     */
    handleEvent : function(args){
        var event = args.type;
        var options={};
        var genericEvent = this.viewerController.mapComponent.getGenericEventName(event);
        if (genericEvent==viewer.viewercontroller.controller.Event.ON_LAYER_ADDED){
            options.layer=this.getLayerByOpenLayersId(args.layer.id);
            if (options.layer ==undefined){
                //if no layer found return, dont fire
                return;
            }
        }else if (genericEvent== viewer.viewercontroller.controller.Event.ON_LAYER_VISIBILITY_CHANGED){
            options.layer=this.getLayerByOpenLayersId(args.layer.id);
            if (options.layer ==undefined){
                //if no layer found return, dont fire
                return;
            }
            options.visible=args.layer.visibility;
        }else if (genericEvent==viewer.viewercontroller.controller.Event.ON_LAYER_REMOVED){
            options.layer=this.getLayerByOpenLayersId(args.layer.id);
            if (options.layer ==undefined){
                //if no layer found return, dont fire
                return;
            }
        }else{
            this.viewerController.logger.error("The event "+genericEvent+" is not implemented in the OpenLayersMap.handleEvent()");
        }
        this.fireEvent(genericEvent,this,options);
    },

    //xxx remove
    unRegisterEvent : function (event,handler,thisObj){
        var specificName = this.viewerController.mapComponent.getSpecificEventName(event);
        this.getFrameworkMap().events.unregister(specificName,handler,thisObj);
        this.removeListener(event,handler,thisObj);
    },

    /**
    *See @link Map.getScale
    *@deprecated, use getResolution because it returns the resolution and not the scale
    */
    getScale : function(){
        return this.getResolution();
    },

    /**
    *See @link Map.getResolution
    */
    getResolution : function(){
        return this.getFrameworkMap().getResolution();
    },

    /**
    *See @link Map.coordinateToPixel
    *@returns a OpenLayers.pixel object (has a .x and a .y)
    */
    coordinateToPixel : function(x,y){
        return this.getFrameworkMap().getPixelFromLonLat(new OpenLayers.LonLat(x,y));
    },

    /**
    *see @link Map.getCenter
    *@return a OpenLayers.LonLat object with .x references to .lon and .y references to .lat
    */
    getCenter : function(){
        var lonlat=this.getFrameworkMap().getCenter();
        lonlat.x=lonlat.lon;
        lonlat.y=lonlat.lat;
        return lonlat;
    },

    getWidth : function(){
        var size = this.frameworkMap.getSize();
        return size.w;
    },

    getHeight : function (){
        var size = this.frameworkMap.getSize();
        return size.h;
    },

    layerFinishedLoading : function (id,data,c,d){
        this.layersLoading--;
        if (this.layersLoading==0){
            webMapController.handleEvent(webMapController.eventList[viewer.viewercontroller.controller.Event.ON_ALL_LAYERS_LOADING_COMPLETE]);
        }else if (this.layersLoading < 0){
            this.layersLoading=0;
        }
    },

    layerBeginLoading : function (id,data,c,d){
        this.layersLoading++;
    },

    /**
     * The OpenLayers ID can't be changed. With this function you can get the
     * viewer.viewercontroller.openlayers.OpenLayersLayer with the openlayersid
     * @param olId the openlayers id of the layer
     * @return a viewer.viewercontroller.openlayers.OpenLayersLayer that
     * contains the openlayers layer with the given id.
     */
    getLayerByOpenLayersId: function(olId){
        for (var i=0; i < this.layers.length; i++){
            if (this.layers[i].frameworkLayer){
                if (this.layers[i].frameworkLayer.id == olId){
                    return this.layers[i];
                }
            }
        }
    }
});<commit_msg>Use this.utils instead of Utils Corrected the path to the marker.<commit_after>/*
 * Copyright (C) 2012 B3Partners B.V.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @class
 * @constructor
 * @description
 * The openlayers map object wrapper
 */
Ext.define ("viewer.viewercontroller.openlayers.OpenLayersMap",{
    extend: "viewer.viewercontroller.controller.Map",
    layersLoading : null,
    utils:null,
    config:{
        viewerController:null
    },
    constructor: function(config){
        viewer.viewercontroller.openlayers.OpenLayersMap.superclass.constructor.call(this, config);
        this.initConfig(config);
        this.utils = Ext.create("viewer.viewercontroller.openlayers.Utils");
        var maxBounds=null;
        if (config.options.fullextent){
            var fullExtent = Ext.create("viewer.viewercontroller.controller.Extent",config.options.fullextent);
            maxBounds = new OpenLayers.Bounds(fullExtent.minx, fullExtent.miny, fullExtent.maxx, fullExtent.maxy);
        }
        else{
            //fallback for bounds: the extent of the Netherlands
            maxBounds= new OpenLayers.Bounds(12000,304000,280000,620000);
        }
        config["center"] = maxBounds.getCenterLonLat();

        config.maxExtent = maxBounds;

        this.frameworkMap=new OpenLayers.Map(config.domId,config);
        this.frameworkMap.centerLayerContainer();

        this.layersLoading = 0;
        this.markerLayer=null;
        this.defaultIcon=null;
        this.markers=new Object();
        this.getFeatureInfoControl = null;
        this.addListener(viewer.viewercontroller.controller.Event.ON_LAYER_REMOVED,this.layerRemoved, this);
        return this;
    },

    /**
    *See @link Map.getAllWMSLayers
    */
    getAllWMSLayers : function(){
        var lagen = new Array();
        for(var i = 0 ; i < this.layers.length;i++){
            if(this.layers[i] instanceof OpenLayersWMSLayer){
                lagen.push(this.layers[i]);
            }
        }
        return lagen;
    },

    /**
    *See @link Map.getAllVectorLayers
    */
    getAllVectorLayers : function(){
        var lagen = new Array();
        for(var i = 0 ; i < this.layers.length;i++){
            if(this.layers[i] instanceof OpenLayersVectorLayer){
                lagen.push(this.layers[i]);
            }
        }
        return lagen;
    },

    /**
    *See @link Map.remove
    */
    remove : function(){
        this.getFrameworkMap().destroy();
    },

    /**
    *Add a layer. Also see @link Map.addLayer
    **/
    addLayer : function(layer){
        this.superclass.addLayer.call(this,layer);
        this.getFrameworkMap().addLayer(layer.getFrameworkLayer());
    },

    /**
    *remove the specific layer. See @link Map.removeLayer
    **/
    removeLayer : function(layer){
        // don't call super function, but manually manage the removal of layers from this.layers

        if (layer instanceof viewer.viewercontroller.openlayers.OpenLayersWMSLayer){
            if(layer.getGetFeatureInfoControl()!=null){
                layer.getGetFeatureInfoControl().destroy();
            }
            if (layer.getMapTipControl()!=null){
                layer.getMapTipControl().destroy();
            }
        }
        layer.getFrameworkLayer().destroy(false);
    },

    layerRemoved : function (map, options){
        var l = options.layer.getFrameworkLayer();
        for ( var i = 0 ; i < this.layers.length ;i++){
            var frameworkLayer = this.layers[i].getFrameworkLayer();
            if(frameworkLayer.id == l.id){
                this.layers.splice(i,1);
                break;
            }
        }
    },

    setLayerVisible : function (layer, visible){
        this.superclass.setLayerVisible.call(this,layer,visible);
        layer.setVisible(visible);
    },

    /**
    * see @link Map.setLayerIndex
    */
    setLayerIndex : function (layer, newIndex){
        if (!(layer instanceof OpenLayersLayer)){
            throw("OpenLayersMap.setLayerIndex(): Given layer not of type OpenLayersLayer.");
        }
        this.getFrameworkMap().setLayerIndex(layer.getFrameworkLayer(),newIndex);
        return Map.prototype.setLayerIndex(layer,newIndex);
    },

    /**
    * Sets the getfeatureinfo control of this map
    */
    setGetFeatureInfoControl : function (control){
        if( control.type != Tool.GET_FEATURE_INFO){
            throw ("Type of given control not of type GET_FEATURE_INFO, but: " + control.type);
        }
        this.getFeatureInfoControl = control;
    },

    /**
    * Move the viewport to the maxExtent. See @link Map.zoomToMaxExtent
    **/
    zoomToMaxExtent : function (){
        this.getFrameworkMap().zoomToExtent(this.getFrameworkMap().getMaxExtent());
    },
    /**
    * See @link Map.zoomToExtent
    **/
    zoomToExtent : function(extent){
        var bounds=this.utils.createBounds(extent)
        this.getFrameworkMap().zoomToExtent(bounds);
    },

    /**
    * See @link Map.zoomToScale
    * @deprecated, use zoomToResolution because it zooms to a resolution and not a scale
    */
    zoomToScale : function(scale){
        this.getFrameworkMap().zoomToResolution(scale);
    },

    /**
    * See @link Map.zoomToResolution
    */
    zoomToResolution : function(resolution){
        this.getFrameworkMap().zoomTo(this.getFrameworkMap().getZoomForResolution(resolution));
    },

    /**
    * See @link Map.setMaxExtent
    * WARNING: Bug in openlayers: doesn't change the maxextent
    * As workaround add the maxExtent when initing the map
    */
    setMaxExtent : function(extent){
        if (this.getFrameworkMap()!=null){
            this.getFrameworkMap().setOptions({
                maxExtent: Utils.createBounds(extent)
            });
        }
    },

    /**
    * See @link Map.getMaxExtent
    */
    getMaxExtent : function(){
        return Utils.createExtent(this.getFrameworkMap().getMaxExtent());
    },

    /**
    * See @link Map.getExtent
    */
    getExtent : function(){
        var extent = this.utils.createExtent(this.getFrameworkMap().getExtent());
        return extent;
    },

    /*TODO:
        doIdentify : function(x,y){}
        update : function(){}
        removeMarker : function(markerName){}
        */
    /**
    *see @link Map.setMarker
    *TODO: marker icon path...
    */
    setMarker : function(markerName,x,y,type){
        if (this.markerLayer==null){
            this.markerLayer = new OpenLayers.Layer.Markers("Markers");
            this.frameworkMap.addLayer(this.markerLayer);
            var size = new OpenLayers.Size(17,17);
            var offset = new OpenLayers.Pixel(-(size.w/2), -size.h);
            this.defaultIcon= new OpenLayers.Icon(contextPath+'/viewer-html/common/openlayers/img/marker.png',size,offset);
        }
        /*According the 'type' load a icon: no types yet only default*/
        var icon= this.defaultIcon.clone();
        this.markers[markerName]= new OpenLayers.Marker(new OpenLayers.LonLat(x,y),icon);
        this.markerLayer.addMarker(this.markers[markerName]);
    },

    /**
    * see @link Map.removeMarker
    */
    removeMarker : function(markerName){
        if (this.markers[markerName] && this.markerLayer!=null){
            this.markerLayer.removeMarker(this.markers[markerName]);
        }
    },

    /**
     * @see Ext.util.Observable#addListener
     * @param event the event
     * @param handler the handler
     * @param scope the scope
     * Overwrite the addListener. Register event on the OpenLayers Map (only once)
     * If the event is thrown by the OpenLayers event the given handlers are called.
     */
    addListener : function(event,handler,scope){
        var olSpecificEvent = this.viewerController.mapComponent.getSpecificEventName(event);
        if(olSpecificEvent){
            if(!scope){
                scope = this;
            }
            /* Add event to OpenLayersMap only once, to prevent multiple fired events.
             * count the events for removing the listener again.
             */
            if(this.enabledEvents[olSpecificEvent]){
                this.enabledEvents[olSpecificEvent]++;
            }else{
                this.enabledEvents[olSpecificEvent] = 1;
                this.frameworkMap.events.register(olSpecificEvent, this, this.handleEvent);
            }
        }
        viewer.viewercontroller.openlayers.OpenLayersMap.superclass.addListener.call(this,event,handler,scope);
    },

    /**
     * @see Ext.util.Observable#removeListener
     * @param event the event
     * @param handler the handler
     * @param scope the scope
     * Overwrite the removeListener. Unregister the event on the OpenLayers Map if there
     * are no listeners anymore.
     */
    removeListener : function (event,handler,scope){
        var olSpecificEvent = this.viewerController.mapComponent.getSpecificEventName(event);
        if(olSpecificEvent){
            if(!scope){
                scope = this;
            }
            /* Remove event from OpenLayersMap if the number of events == 0
             * If there are no listeners for the OpenLayers event, remove the listener.
             */
            if(this.enabledEvents[olSpecificEvent]){
                this.enabledEvents[olSpecificEvent]--;
                if (this.enabledEvents[olSpecificEvent] <= 0){
                    this.enabledEvents[olSpecificEvent]=0;
                    this.frameworkMap.events.unregister(olSpecificEvent, this, this.handleEvent);
                }
            }
            viewer.viewercontroller.openlayers.OpenLayersMap.superclass.removeListener.call(this,event,handler,scope);
        }else{
            this.viewerController.logger.warning("Event not listed in OpenLayersMapComponent >"+ event + "<. The application  might not work correctly.");
        }
    },

    /**
     * Handles the events fired by OpenLayers.Map and propagates them to the registered objects.
     *
     */
    handleEvent : function(args){
        var event = args.type;
        var options={};
        var genericEvent = this.viewerController.mapComponent.getGenericEventName(event);
        if (genericEvent==viewer.viewercontroller.controller.Event.ON_LAYER_ADDED){
            options.layer=this.getLayerByOpenLayersId(args.layer.id);
            if (options.layer ==undefined){
                //if no layer found return, dont fire
                return;
            }
        }else if (genericEvent== viewer.viewercontroller.controller.Event.ON_LAYER_VISIBILITY_CHANGED){
            options.layer=this.getLayerByOpenLayersId(args.layer.id);
            if (options.layer ==undefined){
                //if no layer found return, dont fire
                return;
            }
            options.visible=args.layer.visibility;
        }else if (genericEvent==viewer.viewercontroller.controller.Event.ON_LAYER_REMOVED){
            options.layer=this.getLayerByOpenLayersId(args.layer.id);
            if (options.layer ==undefined){
                //if no layer found return, dont fire
                return;
            }
        }else{
            this.viewerController.logger.error("The event "+genericEvent+" is not implemented in the OpenLayersMap.handleEvent()");
        }
        this.fireEvent(genericEvent,this,options);
    },

    //xxx remove
    unRegisterEvent : function (event,handler,thisObj){
        var specificName = this.viewerController.mapComponent.getSpecificEventName(event);
        this.getFrameworkMap().events.unregister(specificName,handler,thisObj);
        this.removeListener(event,handler,thisObj);
    },

    /**
    *See @link Map.getScale
    *@deprecated, use getResolution because it returns the resolution and not the scale
    */
    getScale : function(){
        return this.getResolution();
    },

    /**
    *See @link Map.getResolution
    */
    getResolution : function(){
        return this.getFrameworkMap().getResolution();
    },

    /**
    *See @link Map.coordinateToPixel
    *@returns a OpenLayers.pixel object (has a .x and a .y)
    */
    coordinateToPixel : function(x,y){
        return this.getFrameworkMap().getPixelFromLonLat(new OpenLayers.LonLat(x,y));
    },

    /**
    *see @link Map.getCenter
    *@return a OpenLayers.LonLat object with .x references to .lon and .y references to .lat
    */
    getCenter : function(){
        var lonlat=this.getFrameworkMap().getCenter();
        lonlat.x=lonlat.lon;
        lonlat.y=lonlat.lat;
        return lonlat;
    },

    getWidth : function(){
        var size = this.frameworkMap.getSize();
        return size.w;
    },

    getHeight : function (){
        var size = this.frameworkMap.getSize();
        return size.h;
    },

    layerFinishedLoading : function (id,data,c,d){
        this.layersLoading--;
        if (this.layersLoading==0){
            webMapController.handleEvent(webMapController.eventList[viewer.viewercontroller.controller.Event.ON_ALL_LAYERS_LOADING_COMPLETE]);
        }else if (this.layersLoading < 0){
            this.layersLoading=0;
        }
    },

    layerBeginLoading : function (id,data,c,d){
        this.layersLoading++;
    },

    /**
     * The OpenLayers ID can't be changed. With this function you can get the
     * viewer.viewercontroller.openlayers.OpenLayersLayer with the openlayersid
     * @param olId the openlayers id of the layer
     * @return a viewer.viewercontroller.openlayers.OpenLayersLayer that
     * contains the openlayers layer with the given id.
     */
    getLayerByOpenLayersId: function(olId){
        for (var i=0; i < this.layers.length; i++){
            if (this.layers[i].frameworkLayer){
                if (this.layers[i].frameworkLayer.id == olId){
                    return this.layers[i];
                }
            }
        }
    }
});<|endoftext|>


<commit_before>'use strict';

const http = require('http');
const fs = require('fs');

	giphy: function (target, room, user) {
 		if (!target) return this.parse('/giphyhelp');
 		let tarId = toId(target);
 		let validTargets = ['cat', 'otter', 'dog', 'bunny', 'pokemon', 'kitten', 'puppy', 'anime'];
 		if (room.id === 'lobby' && !user.isStaff) return this.errorReply("This command cannot be broadcasted in the Lobby.");
 		if (!validTargets.includes(tarId)) return this.parse('/giphyhelp');
 		let self = this;
 		let reqOpt = {
 			hostname: 'api.giphy.com', // Do not change this
			path: '/v1/gifs/random?api_key=dc6zaTOxFJmzC&tag=' + tarId,
 			method: 'GET',
        	};
 		let req = http.request(reqOpt, function (res) {
 			res.on('data', function (chunk) {
 				try {
 					let data = JSON.parse(chunk);
 					let output = '';
 					if (!self.runBroadcast()) return;
 					if (data.data["image_url"] === undefined) {
 						self.errorReply("ERROR CODE 404: No images found!");
 						return room.update();
 					} else {
 						self.sendReplyBox(output);
 						return room.update();
 					}
 				} catch (e) {
 					return self.errorReply("ERROR CODE 503: Giphy is unavaliable right now. Try again later.");
 					return room.update();
 				}
 			});
 		});
 		req.end();
 	},
 	giphyhelp: ['Giphy Plugin by DarkNightSkies & Kyv.n(♥)',
 		'/giphy cat - Displays a cat.',
		'/giphy kitten - Displays a kitten.',
 		'/giphy dog - Displays a dog.',
		'/giphy puppy - Displays a puppy.',
 		'/giphy bunny - Displays a bunny.',
 		'/giphy otter - Displays an otter.',
         	'/giphy pokemon - Displays a pokemon.',
 		'/giphy anime - Displays an anime',
 		'/giphy help - Displays this help box.',
 		]
};
<commit_msg>Delete giphy.js<commit_after><|endoftext|>


<commit_before>/**
 * green.js - a plug.dj plugin
 * @licence MIT
 * @author greeny
 */
(function(){
	if(typeof API === 'undefined') {
		alert('You are not at plug.dj. Please use this bookmark at plug.dj.\n\nYou can find more info at greeny.github.io/green.dj');
	}
	if(typeof window.greenDj === 'undefined') {
		function GreenDjObject() {
			this.API = API;
			this.version = '1.0.0';
			this.settings = {};

			var that = this;

			/* EVENTS */

			this.API.on(API.USER_JOIN, function(user) {
				that.onUserJoin(user);
			});

			this.API.on(API.USER_LEFT, function(user) {
				that.onUserLeave(user);
			});

			this.API.on(API.VOTE_UPDATE, function(data) {
				that.onUserVote(data.user, data.vote);
			});

			this.API.on(API.GRAB_UPDATE, function(user) {
				that.onGrab(user);
			});

			this.API.on(API.ADVANCE, function(data) {
				that.onAdvance('advance', data);
			});

			this.API.on(API.USER_SKIP, function(data) {
				that.onAdvance('skip', data);
			});

			this.API.on(API.MOD_SKIP, function(data) {
				that.onAdvance('forceSkip', data);
			});

			/* FUNCTIONALITY */

			this.onUserJoin = function(user) {
				this.info(user.username + ' has joined the room.', 'userJoin');
			};

			this.onUserLeave = function(user) {
				this.info(user.username + ' has left the room.', 'userLeave');
			};

			this.onUserVote = function(user, vote) {
				console.log(vote);
				this.info(user.username + ' had ' + (vote === 1 ? 'Woot!ed' : 'Meh!ed') + ' this song!', 'userVote');
			};

			this.onGrab = function(user) {
				console.log(user);
				this.info(user.username + ' has added this song to his playlist.', 'userGrab');
			};

			this.onAdvance = function(reason, data) {
				if(this.featureEnabled('autoWoot')) {
					this.woot();
				}
			};

			this.woot = function() {
				setTimeout(function() {
					$('#woot').click();
				}, 2000);
			};

			this.grab = function() {
				setTimeout(function() {
					$('#grab').click();
				}, 2000);
			};

			this.meh = function() {
				setTimeout(function() {
					$('#meh').click();
				}, 2000);
			};

			this.info = function(message, required) {
				/*if(message) {
					if(!(required && this.messageEnabled(required))) {*/
						var $el = $('
[green.dj] ' + message + '
');
						var $chat = $("#chat-messages");
						$chat.append($el);
						$chat.scrollTop($chat.scrollTop() + $el.outerHeight(true));
					/*}
				}*/
			};

			/* SETTINGS */

			this.init = function() {
				$('#chat-header').find('.divider').after('
' +
					'' +
					'
');
				$('body [data-greendj-settings]').on('change', function(e) {
					e.preventDefault();
					that.onSettingsChange($(this));
				});
				if(typeof Storage === 'undefined') {
					this.info('green.dj cannot be loaded, because your browser does not support localStorage.');
					return;
				}
				var data = localStorage.getItem('green.dj');
				if(data) {
					this.settings = JSON.parse(data);
				} else {
					this.settings = {};
				}

				this.info('green.dj version ' + this.version + ' loaded. Enjoy!');
			};

			this.onSettingsClick = function() {
				$('#dialog-container').html('
' +
					'
green.dj settings
' +
					'
' + this.getSettingsHtml() + '
' +
					'

Export

OK

' +
					'
').show();
			};

			this.onSettingsChange = function(el) {
				var s = this.getSettings(), key = el.data('greendj-settings'), val = el.attr('name'), checked = el.val();
				if(!s[key]) {
					s[key] = {};
				}
				if(!s[key][val]) {
					s[key][val] = false;
				}
				this.settings[key][val] = !this.settings[key][val];
				el.val(this.settings[key][val]);
				localStorage.setItem('green.dj', JSON.stringify(this.settings));
			};

			this.messageEnabled = function(key) {
				var s = this.getSettings();
				if(!s.messages) {
					s.messages = {};
					return false;
				}
				if(!s.messages[key]) {
					s.messages[key] = true;
				}
				return s.messages[key];
			};

			this.featureEnabled = function(key) {
				var s = this.getSettings();
				if(!s.features) {
					s.features = {};
					return false;
				}
				if(!s.features[key]) {
					s.features[key] = true;
				}
				return s.features[key];
			};

			this.getSettings = function() {
				return this.settings;
			};

			this.closeSettingsDialog = function() {
				$('#dialog-container').html('').hide();
			};

			this.getSettingsHtml = function() {
				return '
' +
					'
Features:
' +
					'
<input type="checkbox" name="autoWoot" data-greendj-settings="features"> AutoWoot
' +
					'
' +
					'
' +
					'
Messages:
' +
					'
<input type="checkbox" name="userVote" data-greendj-settings="messages"> User vote (woot / meh)
' +
					'
<input type="checkbox" name="userJoin" data-greendj-settings="messages"> User join
' +
					'
<input type="checkbox" name="userLeave" data-greendj-settings="messages"> User leave
' +
					'
';
			};

			this.init();
		}
		window.greenDj = new GreenDjObject();
	} else {
		greenDj.info('Already loaded!');
	}
})();
<commit_msg>Updated some stuff<commit_after>/**
 * green.js - a plug.dj plugin
 * @licence MIT
 * @author greeny
 */
(function(){
	if(typeof API === 'undefined') {
		alert('You are not at plug.dj. Please use this bookmark at plug.dj.\n\nYou can find more info at greeny.github.io/green.dj');
	}
	if(typeof window.greenDj === 'undefined') {
		function GreenDjObject() {
			this.API = API;
			this.version = '1.0.0';
			this.settings = {};

			var that = this;

			/* EVENTS */

			this.API.on(API.USER_JOIN, function(user) {
				that.onUserJoin(user);
			});

			this.API.on(API.USER_LEFT, function(user) {
				that.onUserLeave(user);
			});

			this.API.on(API.VOTE_UPDATE, function(data) {
				that.onUserVote(data.user, data.vote);
			});

			this.API.on(API.GRAB_UPDATE, function(user) {
				that.onGrab(user.user);
			});

			this.API.on(API.ADVANCE, function(data) {
				that.onAdvance('advance', data);
			});

			this.API.on(API.USER_SKIP, function(data) {
				that.onAdvance('skip', data);
			});

			this.API.on(API.MOD_SKIP, function(data) {
				that.onAdvance('forceSkip', data);
			});

			/* FUNCTIONALITY */

			this.onUserJoin = function(user) {
				this.info(user.username + ' has joined the room.', 'userJoin');
			};

			this.onUserLeave = function(user) {
				this.info(user.username + ' has left the room.', 'userLeave');
			};

			this.onUserVote = function(user, vote) {
				console.log(vote);
				this.info(user.username + ' had ' + (vote === 1 ? 'Woot!ed' : 'Meh!ed') + ' this song!', 'userVote');
			};

			this.onGrab = function(user) {
				console.log(user);
				this.info(user.username + ' has added this song to his playlist.', 'userGrab');
			};

			this.onAdvance = function(reason, data) {
				if(this.featureEnabled('autoWoot')) {
					/*this.woot();*/
				}
			};

			this.woot = function() {
				setTimeout(function() {
					$('#woot').click();
				}, 2000);
			};

			this.grab = function() {
				setTimeout(function() {
					$('#grab').click();
				}, 2000);
			};

			this.meh = function() {
				setTimeout(function() {
					$('#meh').click();
				}, 2000);
			};

			this.info = function(message, required) {
				/*if(message) {
					if(!(required && this.messageEnabled(required))) {*/
						var $el = $('

Delete
[green.dj] ' + message + '
');
						var $chat = $("#chat-messages");
						$chat.append($el);
						$chat.scrollTop($chat.scrollTop() + $el.outerHeight(true));
					/*}
				}*/
			};

			/* SETTINGS */

			this.init = function() {
				$('#chat-header').find('.divider').after('
' +
					'' +
					'
');
				$('body [data-greendj-settings]').on('change', function(e) {
					e.preventDefault();
					that.onSettingsChange($(this));
				});
				if(typeof Storage === 'undefined') {
					this.info('green.dj cannot be loaded, because your browser does not support localStorage.');
					return;
				}
				var data = localStorage.getItem('green.dj');
				if(data) {
					this.settings = JSON.parse(data);
				} else {
					this.settings = {};
				}

				this.info('green.dj version ' + this.version + ' loaded. Enjoy!');
			};

			this.onSettingsClick = function() {
				$('#dialog-container').html('
' +
					'
green.dj settings
' +
					'
' + this.getSettingsHtml() + '
' +
					'

Export

OK

' +
					'
').show();
			};

			this.onSettingsChange = function(el) {
				var s = this.getSettings(), key = el.data('greendj-settings'), val = el.attr('name'), checked = el.val();
				if(!s[key]) {
					s[key] = {};
				}
				if(!s[key][val]) {
					s[key][val] = false;
				}
				this.settings[key][val] = !this.settings[key][val];
				el.val(this.settings[key][val]);
				localStorage.setItem('green.dj', JSON.stringify(this.settings));
			};

			this.messageEnabled = function(key) {
				var s = this.getSettings();
				if(!s.messages) {
					s.messages = {};
					return false;
				}
				if(!s.messages[key]) {
					s.messages[key] = true;
				}
				return s.messages[key];
			};

			this.featureEnabled = function(key) {
				var s = this.getSettings();
				if(!s.features) {
					s.features = {};
					return false;
				}
				if(!s.features[key]) {
					s.features[key] = true;
				}
				return s.features[key];
			};

			this.getSettings = function() {
				return this.settings;
			};

			this.closeSettingsDialog = function() {
				$('#dialog-container').html('').hide();
			};

			this.getSettingsHtml = function() {
				return '
' +
					'
Features:
' +
					'
<input type="checkbox" name="autoWoot" data-greendj-settings="features"> AutoWoot
' +
					'
' +
					'
' +
					'
Messages:
' +
					'
<input type="checkbox" name="userVote" data-greendj-settings="messages"> User vote (woot / meh)
' +
					'
<input type="checkbox" name="userJoin" data-greendj-settings="messages"> User join
' +
					'
<input type="checkbox" name="userLeave" data-greendj-settings="messages"> User leave
' +
					'
';
			};

			this.init();
		}
		window.greenDj = new GreenDjObject();
	} else {
		greenDj.info('Already loaded!');
	}
})();
<|endoftext|>


<commit_before>'use strict';

const gulp = require('gulp');
const browserSync = require('browser-sync').create();
const reload = browserSync.reload;
const sass = require('gulp-sass');
const cssmin = require('gulp-cssmin');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const globbing = require('gulp-css-globbing');
const filter = require('gulp-filter');
const htmlreplace = require('gulp-html-replace');
const uncss = require('gulp-uncss');
const responsive = require('gulp-responsive');
const hg = require('gulp-hg');
const exec = require('child_process').exec;
const clean = require('gulp-clean');
const debug = require('gulp-debug');
const runSequence = require('run-sequence');
const replace = require('gulp-replace');

var timestamp = new Date();

timestamp = timestamp.getTime();

// compiles the scss files to css
// reinjects the new css into the browser
gulp.task('sass-dev', function () {

    gulp.src('./sass-itcss/app.scss')
        .pipe(globbing({
            extensions: ['.scss']
        }))
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./css'))
        .pipe(filter(['**/*.css']))
        .pipe(reload({stream: true}));

});

// compiles the scss files to css
// write source maps
// removes css classes not used in html files (ignores 'is-*' classes which can be added via JS)
// adds prefixes to support last 2 versions of every browsers
// minifies the CSS
gulp.task('sass-prod', function () {

    return gulp.src('sass-itcss/app.scss')
        .pipe(globbing({
            extensions: ['.scss']
        }))
        .pipe(sourcemaps.init())
        .pipe(debug({title: 'START - SASS TO CSS CONVERSION', showFiles: false}))
        .pipe(sass())
        .pipe(debug({title: 'END - SASS TO CSS CONVERSION', showFiles: false}))
        .pipe(debug({title: 'START - UNCSS APP.CSS', showFiles: false}))
        .pipe(uncss({
            html: ['index.html'],
            ignore: [/\.is-/]
        }))
        .pipe(debug({title: 'END - UNCSS APP.CSS', showFiles: false}))
        .pipe(debug({title: 'START - AUTOPREFIXING APP.CSS', showFiles: false}))
        .pipe(autoprefixer({
            browsers: 'last 2 versions'
        }))
        .pipe(debug({title: 'END - AUTOPREFIXING APP.CSS', showFiles: false}))
        .pipe(debug({title: 'START - MINIFICATION OF APP.CSS', showFiles: false}))
        .pipe(cssmin())
        .pipe(debug({title: 'END - MINIFICATION OF APP.CSS', showFiles: false}))
        .pipe(sourcemaps.write('/'))
        .pipe(gulp.dest('./css'))
        .on('end', function () {
            console.log('FINISHED :) :) :) :) :) :)');
        });

});

// appends a new timestamp to the link's href of the app.css file in index.html
gulp.task('update-html-css-link-timestamp', function () {

    return gulp.src('index.html')
        .pipe(htmlreplace({
            'css': 'css/app.css?v=' + timestamp
        }, {
            keepBlockTags: true
        }))
        .pipe(gulp.dest('.'));

});

// removes current compiled css file
gulp.task('clean-css-files', function () {

    return gulp.src('css/*')
        .pipe(debug({title: 'START - DELETING CURRENT COMPILED CSS FILE', showFiles: false}))
        .pipe(clean({read: false}))
        .pipe(debug({title: 'END - DELETING CURRENT COMPILED CSS FILE', showFiles: false}));

});

// creates desktop, tablet and mobiles version, both normal and retina, for all images in specified folder
gulp.task('responsive-images', function () {
    gulp.src(['img/*.jpg', 'img/*.png', 'img/*.jpeg'])
        .pipe(responsive({
            '*': [
            {
                format: 'jpeg',
                rename: {
                    suffix: '@desktop'
                }
            },
            {
                width: 991,
                format: 'jpeg',
                rename: {
                    suffix: '@tablet'
                }
            },
            {
                width: 480,
                format: 'jpeg',
                rename: {
                    suffix: '@mobile'
                }
            },
            {
                width: 1534,
                format: 'jpeg',
                rename: {
                    suffix: '@tablet-2x'
                }
            },
            {
                width: 960,
                format: 'jpeg',
                rename: {
                    suffix: '@mobile-2x'
                }
            }
            ]
        }))
        .pipe(gulp.dest('img/responsive'));
});

// launches a static server + watching scss files
gulp.task('serve', ['sass-dev'], function() {

    browserSync.init({
        proxy: 'http://localhost:80',
        open: false,
        notify: false
    });

    gulp.watch(['./sass-itcss/**/*.scss'], ['sass-dev']);

});

gulp.task('uncomment-css-file-in-git-ignore', function() {
    gulp.src(['.gitignore'])
        .pipe(replace('#css/app.css', 'css/app.css'))
        .pipe(gulp.dest('.'));
});

gulp.task('comment-css-file-in-git-ignore', function() {
    gulp.src(['.gitignore'])
        .pipe(replace('css/app.css', '#css/app.css'))
        .pipe(gulp.dest('.'));
});

gulp.task('git-add-css-files-to-staging', function (cb) {

    exec('git add css/*', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});

gulp.task('git-commit-css-file', function (cb) {
    exec('git commit  -m "CSS DEPLOYMENT" css', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});

gulp.task('git-push', function (cb) {
    exec('git push', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});

gulp.task('deploy', function() {

    runSequence(
        'sass-prod',
        'update-html-css-link-timestamp',
        'uncomment-css-file-in-git-ignore',
        'git-add-css-files-to-staging',
        'git-commit-css-file',
        'git-push',
        'comment-css-file-in-git-ignore'
    );

});

gulp.task('default', ['serve']);<commit_msg>cleaned up gulp file<commit_after>'use strict';

const gulp = require('gulp');
const browserSync = require('browser-sync').create();
const reload = browserSync.reload;
const sass = require('gulp-sass');
const cssmin = require('gulp-cssmin');
const sourcemaps = require('gulp-sourcemaps');
const autoprefixer = require('gulp-autoprefixer');
const globbing = require('gulp-css-globbing');
const filter = require('gulp-filter');
const htmlreplace = require('gulp-html-replace');
const uncss = require('gulp-uncss');
const responsive = require('gulp-responsive');
const hg = require('gulp-hg');
const exec = require('child_process').exec;
const clean = require('gulp-clean');
const debug = require('gulp-debug');
const runSequence = require('run-sequence');
const replace = require('gulp-replace');

var timestamp = new Date();

timestamp = timestamp.getTime();

// compiles the scss files to css
// reinjects the new css into the browser
gulp.task('sass-dev', function () {

    gulp.src('./sass-itcss/app.scss')
        .pipe(globbing({
            extensions: ['.scss']
        }))
        .pipe(sass().on('error', sass.logError))
        .pipe(gulp.dest('./css'))
        .pipe(filter(['**/*.css']))
        .pipe(reload({stream: true}));

});

// compiles the scss files to css
// write source maps
// removes css classes not used in html files (ignores 'is-*' classes which can be added via JS)
// adds prefixes to support last 2 versions of every browsers
// minifies the CSS
gulp.task('sass-prod', function () {

    return gulp.src('sass-itcss/app.scss')
        .pipe(globbing({
            extensions: ['.scss']
        }))
        .pipe(sourcemaps.init())
        .pipe(debug({title: 'START - SASS TO CSS CONVERSION', showFiles: false}))
        .pipe(sass())
        .pipe(debug({title: 'END - SASS TO CSS CONVERSION', showFiles: false}))
        .pipe(debug({title: 'START - UNCSS APP.CSS', showFiles: false}))
        .pipe(uncss({
            html: ['index.html'],
            ignore: [/\.is-/]
        }))
        .pipe(debug({title: 'END - UNCSS APP.CSS', showFiles: false}))
        .pipe(debug({title: 'START - AUTOPREFIXING APP.CSS', showFiles: false}))
        .pipe(autoprefixer({
            browsers: 'last 2 versions'
        }))
        .pipe(debug({title: 'END - AUTOPREFIXING APP.CSS', showFiles: false}))
        .pipe(debug({title: 'START - MINIFICATION OF APP.CSS', showFiles: false}))
        .pipe(cssmin())
        .pipe(debug({title: 'END - MINIFICATION OF APP.CSS', showFiles: false}))
        .pipe(sourcemaps.write('/'))
        .pipe(gulp.dest('./css'))
        .on('end', function () {
            console.log('FINISHED :) :) :) :) :) :)');
        });

});

// appends a new timestamp to the link's href of the app.css file in index.html
gulp.task('update-html-css-link-timestamp', function () {

    return gulp.src('index.html')
        .pipe(htmlreplace({
            'css': 'css/app.css?v=' + timestamp
        }, {
            keepBlockTags: true
        }))
        .pipe(gulp.dest('.'));

});

// removes current compiled css file
gulp.task('clean-css-files', function () {

    return gulp.src('css/*')
        .pipe(debug({title: 'START - DELETING CURRENT COMPILED CSS FILE', showFiles: false}))
        .pipe(clean({read: false}))
        .pipe(debug({title: 'END - DELETING CURRENT COMPILED CSS FILE', showFiles: false}));

});

// creates desktop, tablet and mobiles version, both normal and retina, for all images in specified folder
gulp.task('responsive-images', function () {
    gulp.src(['img/*.jpg', 'img/*.png', 'img/*.jpeg'])
        .pipe(responsive({
            '*': [
            {
                format: 'jpeg',
                rename: {
                    suffix: '@desktop'
                }
            },
            {
                width: 991,
                format: 'jpeg',
                rename: {
                    suffix: '@tablet'
                }
            },
            {
                width: 480,
                format: 'jpeg',
                rename: {
                    suffix: '@mobile'
                }
            },
            {
                width: 1534,
                format: 'jpeg',
                rename: {
                    suffix: '@tablet-2x'
                }
            },
            {
                width: 960,
                format: 'jpeg',
                rename: {
                    suffix: '@mobile-2x'
                }
            }
            ]
        }))
        .pipe(gulp.dest('img/responsive'));
});

// launches a static server + watching scss files
gulp.task('serve', ['sass-dev'], function() {

    browserSync.init({
        proxy: 'http://localhost:80',
        open: false,
        notify: false
    });

    gulp.watch(['./sass-itcss/**/*.scss'], ['sass-dev']);

});

gulp.task('git-add-css-files-to-staging', function (cb) {

    exec('git add css/*', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});

gulp.task('git-commit-css-file', function (cb) {
    exec('git commit  -m "CSS DEPLOYMENT" css', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});

gulp.task('git-push', function (cb) {
    exec('git push', function (err, stdout, stderr) {
        console.log(stdout);
        console.log(stderr);
        cb(err);
    });
});

gulp.task('deploy', function() {

    runSequence(
        'sass-prod',
        'update-html-css-link-timestamp',
        'git-add-css-files-to-staging',
        'git-commit-css-file',
        'git-push'
    );

});

gulp.task('default', ['serve']);<|endoftext|>


<commit_before>Ext.application({
    name: 'HelloExt',
    appFolder: '/static/minimal_extjs4_app/app',
    launch: function() {
        Ext.create('Ext.container.Viewport', {
            layout: 'fit',
            items: [
                {
                    title: 'Hello Ext',
                    html : 'Hello! Welcome to Ext JS.'
                }
            ]
        });
    }
});
<commit_msg>generic_extjs4_app: Fixed incorrect appFolder.<commit_after>Ext.application({
    name: 'HelloExt',
    appFolder: '/static/generic_extjs4_app/app',
    launch: function() {
        Ext.create('Ext.container.Viewport', {
            layout: 'fit',
            items: [
                {
                    title: 'Hello Ext',
                    html : 'Hello! Welcome to Ext JS.'
                }
            ]
        });
    }
});
<|endoftext|>


<commit_before>import template from './_ngmodule_.html';

export let =ngmodule=Component = {
	template,
	selector: '_ngmodule_',
	bindings: {

	},
	controller: class =ngmodule=Ctrl {
		/* @ngInject */
		constructor () {
			// Object.assign(this, ...arguments);

		}
	}
};
<commit_msg>updated templates<commit_after>import template from './_ngmodule_.html';

export let =ngmodule=Component = {
	templateUrl: template,
	selector: '_ngmodule_',
	bindings: {

	},
	controller: class =ngmodule=Ctrl {
		/* @ngInject */
		constructor () {
			// Object.assign(this, ...arguments);

		}
	}
};
<|endoftext|>


<commit_before>/**
* Generates Audits object with methods using passed api
* @param {object} api Valid api object
* @returns {object} audits Methods to interact with audits on API
*/
export default function Audits(api) {
  return {
    /**
    * Returns all audits, with options.
    * @param {object} opts Options object
    * @param {string} opts.since Modified since date (ISO datestring)
    * @param {string} opts.order Order of audits, default 'asc'
    * @returns {Promise} Resolves to array of audits ids and modified_at fields,
    *                    Rejects with an error from API.
    */
    findAll: ({ since, order } = {}) =>
      api.get('/audits/search', {
        qs: {
          modified_after: since,
          field: ['audit_id', 'modified_at'],
          order: order ? order : 'asc'
        }
      })
      .then(body => body.audits)
  };
}
<commit_msg>Modify CS of audits<commit_after>/**
* Generates Audits object with methods using passed api
* @param {object} api Valid api object
* @returns {object} audits Methods to interact with audits on API
*/
export default function Audits(api) {
  return {
    /**
    * Returns all audits, with options.
    * @param {object} opts Options object
    * @param {string} opts.since Modified since date (ISO datestring)
    * @param {string} opts.order Order of audits, default 'asc'
    * @returns {Promise} Resolves to array of audits ids and modified_at fields,
    *                    Rejects with an error from API.
    */
    findAll: ({ since, order } = {}) => api.get('/audits/search', {
      qs: {
        modified_after: since,
        field: ['audit_id', 'modified_at'],
        order: order ? order : 'asc'
      }
    })
    .then(body => body.audits)
  };
}
<|endoftext|>


<commit_before>var isNavDisplayed = false;

//The navigation bar slides in/out once the trigger is clicked
$( "#navbar-modal-trigger" ).click(function() {

	if (!isNavDisplayed){

		//Display navbar if it is not already displayed
		$( "#navbar-modal" ).animate(

	    	{ left: 0 },
		    'slow',
		    'swing',

		);

		 $("body").addClass("modal-open");

		isNavDisplayed = true;

	}

	else{

		//Hide navbar if it is already displayed
		$( "#navbar-modal" ).animate(

	    	{ left: '-130%' },
		    'slow',
		    'swing',

		);

		$("body").removeClass("modal-open");

		isNavDisplayed = false;

	}

});

//The navigation bar slides out to the left once a navigation link is clicked
$( ".navbar-link" ).click(function() {

	//Hide navbar
	$( "#navbar-modal" ).animate(

    	{ left: '-130%' },
	    'slow',
	    'swing',

	);

	$("body").removeClass("modal-open");

	isNavDisplayed = false;

});<commit_msg>fixed navbar bottom link bug<commit_after>var isNavDisplayed = false;

//The navigation bar slides in/out once the trigger is clicked
$( "#navbar-modal-trigger" ).click(function() {

	if (!isNavDisplayed){

		//Display navbar if it is not already displayed
		$( "#navbar-modal" ).animate(

	    	{ left: 0 },
		    'slow',
		    'swing',

		);

		 $("body").addClass("modal-open");

		isNavDisplayed = true;

	}

	else{

		//Hide navbar if it is already displayed
		$( "#navbar-modal" ).animate(

	    	{ left: '-130%' },
		    'slow',
		    'swing',

		);

		$("body").removeClass("modal-open");

		isNavDisplayed = false;

	}

});

//The navigation bar slides out to the left once a navigation link is clicked
$( "navbar-individual-link-container" ).click(function() {

	//Hide navbar
	$( "#navbar-modal" ).animate(

    	{ left: '-130%' },
	    'slow',
	    'swing',

	);

	$("body").removeClass("modal-open");

	isNavDisplayed = false;

});<|endoftext|>


<commit_before>//= require_directory ./vendor
//= require spreadsheets

// custom JS can go in this file, or another, then you add another require line

'use strict';

function reverseTraitTrigger(trait, value) {
  var $traitInput = $("input[name='"+trait+"']");
  $traitInput.val(value);
  $traitInput.trigger('valueChange');
}

function checkTraitComponents(components) {
  var allMe = true;

  components.forEach(function(component) {
    var $componentInput = $("input[name='"+component+"']");
    var componentValue = $componentInput.val();
    var componentChecked = $componentInput.prop("checked") || $componentInput.attr("type") == 'hidden';
    if(!componentChecked || componentValue != "me") allMe = false;
  });

  return allMe;
}

function setElementFromComponents(element, components) {
  if(checkTraitComponents(components)) {
    $(element).val('me');
  } else {
    $(element).val('not-me');
  }
}

function bindTraitToComponents(element, componentString) {
  var components = JSON.parse(componentString);

  components.forEach(function(component) {
    var $componentInput = $("input[name='"+component+"']");

    if($componentInput.attr("type") == 'hidden') {
      $componentInput.on('valueChange', function() { setElementFromComponents(element, components); });
    } else {
      $componentInput.change(function() { setElementFromComponents(element, components); });
    }
  });
}

function enableSubmitWithRadioChanges() {
  var radioChanged = {};
  $('input:radio').each(function() {
    radioChanged[this.name] = false;
    $(this).change(function() {
      radioChanged[this.name] = true;
      var allChanged = true;
      for (var key in Object.getOwnPropertyNames(radioChanged)) {
        if (radioChanged[key] === false) { allChanged = false; }
      }
      if (allChanged) {
        $('button[type="submit"]').prop('disabled', false);
        $("#assessment .error").hide();
      }
    });
  });
}

// when the page loads, look for hidden compound traits & set up submit validation
$(document).ready(function() {
  $('[data-trait-components]').each(function() {
    bindTraitToComponents(this, $(this).attr('data-trait-components'));
  });

  enableSubmitWithRadioChanges();
});

function showEmailForm(id) {
  $("#email-form-"+id).show();
}

function emailAssessmentResults(id, careerIds) {

  var emailAddress = $("input[name=email-address-"+id+"]").val();

  if(emailAddress) {
    var data = {
      career_ids: careerIds,
      recipient: emailAddress
    };

    $.postJSON('careers/email', data, function() {
      // response is too long for UI to wait for change
    });

    $("input[name=email-address-"+id+"]").val(''); // clear email
    $("#email-form-"+id).hide(); // hide email form
    $("#email-success-message-"+id).fadeIn();
    $("#email-success-message-"+id).fadeOut("slow");
  }
}

// jQuery POST using JSON
$.postJSON = function(url, data, callback) {
    return jQuery.ajax({
        type: "POST",
        url: url,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback
    });
};

function showPrevCareer(currIndex) {
  var newIndex = currIndex - 1;
  if (newIndex > 0) {
    toggleCareer(currIndex, newIndex);
  }
}

function showNextCareer(currIndex, count) {
  var newIndex = currIndex + 1;
  if (newIndex <= count) {
    toggleCareer(currIndex, newIndex);
  }
}

function toggleCareer(oldIndex, newIndex) {
  $('[index='+oldIndex+']').hide();
  $('[index='+newIndex+']').show();
}

function showCareerList() {
  $('.career').hide();
  $('#career-list').show();
}

function showCareer(index) {
  $('#career-list').hide();
  $('[index='+index+']').show();
}
<commit_msg>JS linter fixes<commit_after>//= require_directory ./vendor
//= require spreadsheets

// custom JS can go in this file, or another, then you add another require line

'use strict';

function reverseTraitTrigger(trait, value) {
  var $traitInput = $("input[name='"+trait+"']");
  $traitInput.val(value);
  $traitInput.trigger('valueChange');
}

function checkTraitComponents(components) {
  var allMe = true;

  components.forEach(function(component) {
    var $componentInput = $("input[name='"+component+"']");
    var componentValue = $componentInput.val();
    var componentChecked = $componentInput.prop("checked") || $componentInput.attr("type") == 'hidden';
    if(!componentChecked || componentValue != "me") allMe = false;
  });

  return allMe;
}

function setElementFromComponents(element, components) {
  if(checkTraitComponents(components)) {
    $(element).val('me');
  } else {
    $(element).val('not-me');
  }
}

function bindTraitToComponents(element, componentString) {
  var components = JSON.parse(componentString);

  components.forEach(function(component) {
    var $componentInput = $("input[name='"+component+"']");

    if($componentInput.attr("type") == 'hidden') {
      $componentInput.on('valueChange', function() { setElementFromComponents(element, components); });
    } else {
      $componentInput.change(function() { setElementFromComponents(element, components); });
    }
  });
}

function enableSubmitWithRadioChanges() {
  var radioChanged = {};
  $('input:radio').each(function() {
    radioChanged[this.name] = false;
    $(this).change(function() {
      radioChanged[this.name] = true;
      var allChanged = true;
      for (var key in Object.getOwnPropertyNames(radioChanged)) {
        if (radioChanged[key] === false) { allChanged = false; }
      }
      if (allChanged) {
        $('button[type="submit"]').prop("disabled", false);
        $("#assessment .error").hide();
      }
    });
  });
}

// when the page loads, look for hidden compound traits & set up submit validation
$(document).ready(function() {
  $('[data-trait-components]').each(function() {
    bindTraitToComponents(this, $(this).attr('data-trait-components'));
  });

  enableSubmitWithRadioChanges();
});

function showEmailForm(id) {
  $("#email-form-"+id).show();
}

function emailAssessmentResults(id, careerIds) {

  var emailAddress = $("input[name=email-address-"+id+"]").val();

  if(emailAddress) {
    var data = {
      career_ids: careerIds,
      recipient: emailAddress
    };

    $.postJSON('careers/email', data, function() {
      // response is too long for UI to wait for change
    });

    $("input[name=email-address-"+id+"]").val(''); // clear email
    $("#email-form-"+id).hide(); // hide email form
    $("#email-success-message-"+id).fadeIn();
    $("#email-success-message-"+id).fadeOut("slow");
  }
}

// jQuery POST using JSON
$.postJSON = function(url, data, callback) {
    return jQuery.ajax({
        type: "POST",
        url: url,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        dataType: "json",
        success: callback
    });
};

function showPrevCareer(currIndex) {
  var newIndex = currIndex - 1;
  if (newIndex > 0) {
    toggleCareer(currIndex, newIndex);
  }
}

function showNextCareer(currIndex, count) {
  var newIndex = currIndex + 1;
  if (newIndex <= count) {
    toggleCareer(currIndex, newIndex);
  }
}

function toggleCareer(oldIndex, newIndex) {
  $('[index='+oldIndex+']').hide();
  $('[index='+newIndex+']').show();
}

function showCareerList() {
  $('.career').hide();
  $('#career-list').show();
}

function showCareer(index) {
  $('#career-list').hide();
  $('[index='+index+']').show();
}
<|endoftext|>


<commit_before>// pathNodes store the costs during the route calculation, with parents
function pathNode(position, costModifier, passable) {
    this.position = position;
    this.costModifier = costModifier;
    this.passable = passable;
    this.Gcost = 0;
    this.Hcost = 0;
    this.pathparent = null;

    this.totalCost = function() {
        return this.Gcost + this.Hcost;
    }
}

function pathNodeScore(node) {
    return node.totalCost();
}

function pathNodeEqual(n1, n2) {
    return (n1.position.x == n2.position.x &&
            n1.position.y == n2.position.y &&
            n1.Gcost == n2.Gcost && n1.Hcost == n2.Hcost);
}

function PathFinder(world, start) {
    this.GCost = function(current, neighbor) {
        // I don't really want to do the square root
        var xsq = (current.position.x - neighbor.position.x) *
                  (current.position.x - neighbor.position.x);
        var ysq = (current.position.y - neighbor.position.y) *
                  (current.position.y - neighbor.position.y);
        return Math.sqrt(xsq + ysq) * neighbor.costModifier;
    }

    // current and goal are pathNodes
    this.ManhattanDistance = function(current, goal) {
        return (Math.abs(goal.position.x - current.position.x) +
                Math.abs(goal.position.y - current.position.y));
    }

    this.findPath = function(goal) {
        // the openlist is pathNodes
        var openlist = new BinaryHeap(pathNodeScore, pathNodeEqual);
        // The closedlist does not need to be a heap, but I'm lazy
        var closedlist = new BinaryHeap(pathNodeScore, pathNodeEqual);
        var current = this.start;

        while (!this.atGoal(current, goal)) {
            console.log(current);
            this.updateOpenList(current, goal, openlist, closedlist);
            closedlist.push(current);
            current = openlist.pop();
            if (openlist.size() > 50) {
                break;
            }
        }
        console.log("Found path, retracing steps");
        var path = [];
        while (!this.atGoal(current, this.start)) {
            path.push(current);
            current = current.pathparent;
        }
        path.push(current);
        console.log("Path:", path);

        return path;
    }

    this.updateOpenList = function(current, goal, open, closed) {
        var neighbors = this.getNeighbors(current);
        for (var i in neighbors) {
            this.processNeighbor(current, neighbors[i], goal, open, closed);
        }
    }

    this.processNeighbor = function(current, neighbor, goal, open, closed) {
        if (open.contains(neighbor)) {
        // Recalculate G cost and update parentage if necessary
            var g = this.GCost(current, neighbor) + current.Gcost;
            if (g < neighbor.Gcost) {
                neighbor.Gcost = g;
                neighbor.pathparent = current;
            }
        } else {
            if (neighbor.passable && !closed.contains(neighbor)) {
                // calculate the F = G + H cost of the neighbor
                var g = this.movementCostFunc(current, neighbor) + current.Gcost;
                var h = this.heuristicCostFunc(current, goal);
                neighbor.pathparent = current;
                neighbor.Gcost = g;
                neighbor.Hcost = h;
                // add the neighbor to the open list
                open.push(neighbor);
            }
        }
    }

    this.getNeighbors = function(current) {
        console.log(current);
        var neighbors = [];
        var curpos = current.position;
        var leftpos = {x: curpos.x - 1, y: curpos.y};
        if (this.withinWorld(leftpos)) {
            neighbors.push(this.world[leftpos.x][leftpos.y]);
        }

        var rightpos = {x: curpos.x + 1, y: curpos.y};
        if (this.withinWorld(rightpos)) {
            neighbors.push(this.world[rightpos.x][rightpos.y]);
        }

        var uppos = {x: curpos.x, y: curpos.y - 1};
        if (this.withinWorld(uppos)) {
            neighbors.push(this.world[uppos.x][uppos.y]);
        }

        var downpos = {x: curpos.x, y: curpos.y + 1};
        if (this.withinWorld(downpos)) {
            neighbors.push(this.world[downpos.x][downpos.y]);
        }
        return neighbors;
    }

    this.withinWorld = function(position) {
        return position.x >= 0 && position.x < this.world.length &&
               position.y >= 0 && position.y < this.world[0].length;
    }

    this.defaultGoal = function(current, goal) {
        return (current.position.x == goal.position.x &&
                current.position.y == goal.position.y);
    }

    // world is a 2d array of pathNodes
    this.world = world;
    this.start = start;
    this.movementCostFunc = this.GCost;
    this.heuristicCostFunc = this.ManhattanDistance;
    this.atGoal = this.defaultGoal;
}

var pathworld;
var pf;
function testpath() {
    var width = 5;
    var height = 5;
    pathworld = new Array(width);
    for (var x = 0; x < width; x++) {
        pathworld[x] = new Array(height);
    }
    for (var y = 0; y < height; y++){
        for (var x = 0; x < width; x++) {
            pathworld[x][y] = new pathNode({x: x, y: y}, 1.0, true);
        }
    }
    pf = new PathFinder(pathworld, pathworld[0][0]);
}
<commit_msg>Refactor path reconstruction<commit_after>// pathNodes store the costs during the route calculation, with parents
function pathNode(position, costModifier, passable) {
    this.position = position;
    this.costModifier = costModifier;
    this.passable = passable;
    this.Gcost = 0;
    this.Hcost = 0;
    this.pathparent = null;

    this.totalCost = function() {
        return this.Gcost + this.Hcost;
    }
}

function pathNodeScore(node) {
    return node.totalCost();
}

function pathNodeEqual(n1, n2) {
    return (n1.position.x == n2.position.x &&
            n1.position.y == n2.position.y &&
            n1.Gcost == n2.Gcost && n1.Hcost == n2.Hcost);
}

function PathFinder(world, start) {
    this.GCost = function(current, neighbor) {
        // I don't really want to do the square root
        var xsq = (current.position.x - neighbor.position.x) *
                  (current.position.x - neighbor.position.x);
        var ysq = (current.position.y - neighbor.position.y) *
                  (current.position.y - neighbor.position.y);
        return Math.sqrt(xsq + ysq) * neighbor.costModifier;
    }

    // current and goal are pathNodes
    this.ManhattanDistance = function(current, goal) {
        return (Math.abs(goal.position.x - current.position.x) +
                Math.abs(goal.position.y - current.position.y));
    }

    this.findPath = function(goal) {
        // the openlist is pathNodes
        var openlist = new BinaryHeap(pathNodeScore, pathNodeEqual);
        // The closedlist does not need to be a heap, but I'm lazy
        var closedlist = new BinaryHeap(pathNodeScore, pathNodeEqual);
        var current = this.start;

        while (!this.atGoal(current, goal)) {
            this.updateOpenList(current, goal, openlist, closedlist);
            closedlist.push(current);
            current = openlist.pop();
        }

        return this.reconstructPath(current, this.start);
    }

    this.reconstructPath = function(goal, start) {
        var current = goal;
        var path = [];
        while (!this.atGoal(current, start)) {
            path.push(current);
            current = current.pathparent;
        }
        path.push(current);

        return path;
    }

    this.updateOpenList = function(current, goal, open, closed) {
        var neighbors = this.getNeighbors(current);
        for (var i in neighbors) {
            this.processNeighbor(current, neighbors[i], goal, open, closed);
        }
    }

    this.processNeighbor = function(current, neighbor, goal, open, closed) {
        if (open.contains(neighbor)) {
        // Recalculate G cost and update parentage if necessary
            var g = this.GCost(current, neighbor) + current.Gcost;
            if (g < neighbor.Gcost) {
                neighbor.Gcost = g;
                neighbor.pathparent = current;
            }
        } else {
            if (neighbor.passable && !closed.contains(neighbor)) {
                // calculate the F = G + H cost of the neighbor
                var g = this.movementCostFunc(current, neighbor) + current.Gcost;
                var h = this.heuristicCostFunc(current, goal);
                neighbor.pathparent = current;
                neighbor.Gcost = g;
                neighbor.Hcost = h;
                // add the neighbor to the open list
                open.push(neighbor);
            }
        }
    }

    this.getNeighbors = function(current) {
        console.log(current);
        var neighbors = [];
        var curpos = current.position;
        var leftpos = {x: curpos.x - 1, y: curpos.y};
        if (this.withinWorld(leftpos)) {
            neighbors.push(this.world[leftpos.x][leftpos.y]);
        }

        var rightpos = {x: curpos.x + 1, y: curpos.y};
        if (this.withinWorld(rightpos)) {
            neighbors.push(this.world[rightpos.x][rightpos.y]);
        }

        var uppos = {x: curpos.x, y: curpos.y - 1};
        if (this.withinWorld(uppos)) {
            neighbors.push(this.world[uppos.x][uppos.y]);
        }

        var downpos = {x: curpos.x, y: curpos.y + 1};
        if (this.withinWorld(downpos)) {
            neighbors.push(this.world[downpos.x][downpos.y]);
        }
        return neighbors;
    }

    this.withinWorld = function(position) {
        return position.x >= 0 && position.x < this.world.length &&
               position.y >= 0 && position.y < this.world[0].length;
    }

    this.defaultGoal = function(current, goal) {
        return (current.position.x == goal.position.x &&
                current.position.y == goal.position.y);
    }

    // world is a 2d array of pathNodes
    this.world = world;
    this.start = start;
    this.movementCostFunc = this.GCost;
    this.heuristicCostFunc = this.ManhattanDistance;
    this.atGoal = this.defaultGoal;
}

var pathworld;
var pf;
function testpath() {
    var width = 5;
    var height = 5;
    pathworld = new Array(width);
    for (var x = 0; x < width; x++) {
        pathworld[x] = new Array(height);
    }
    for (var y = 0; y < height; y++){
        for (var x = 0; x < width; x++) {
            pathworld[x][y] = new pathNode({x: x, y: y}, 1.0, true);
        }
    }
    pf = new PathFinder(pathworld, pathworld[0][0]);
}
<|endoftext|>


<commit_before>function saveStudent(studentId) {

	var modal = $('#myModal-' + studentId);

	modal.find('.errors').html('').removeClass('eroare-edit');

	$.post( "/students/update",
		$("#form-update-student-" + studentId).serialize()
	)
	  .done(function( data ) {
	  	response = JSON.parse(data);
	  	if (response.status == 'success') {
	  		modal..on('hidden', function () {
		        $(this).remove();
		    });
			$('#status-update-student').removeClass('hidden').addClass('reusit').html('Studentul a fost salvat cu succes!');

	  	} else {
	  		var str = "";
	  		for(x in response.errors){
	  			str = str.concat(response.errors[x], "
");
	  		}
	  		modal.find('.errors').removeClass('hidden').addClass('eroare-edit').html(str);
  		}
  	});

}
<commit_msg>change js<commit_after>function saveStudent(studentId) {

	var modal = $('#myModal-' + studentId);

	modal.find('.errors').html('').removeClass('eroare-edit');

	$.post( "/students/update",
		$("#form-update-student-" + studentId).serialize()
	)
	  .done(function( data ) {
	  	response = JSON.parse(data);
	  	if (response.status == 'success') {
	  		modal.on('hidden', function () {
		        $(this).remove();
		    });
			$('#status-update-student').removeClass('hidden').addClass('reusit').html('Studentul a fost salvat cu succes!');

	  	} else {
	  		var str = "";
	  		for(x in response.errors){
	  			str = str.concat(response.errors[x], "
");
	  		}
	  		modal.find('.errors').removeClass('hidden').addClass('eroare-edit').html(str);
  		}
  	});

}
<|endoftext|>