<commit_before>/**
 * Created by Thomas on 1/25/14.
 */

// Initialization functions
loadFiles();

window.onload = function () {
    setTimeout(function () {
        mainPhaser();
    }, 3000);
};

// JS file preloader
function loadFiles() {
    var head = document.getElementsByTagName("head")[0];
    for (var i = 0; i < files.length; i++) {
        var js = document.createElement("script");
        js.type = "text/javascript";
        js.src = "src/" + files[i];
        head.appendChild(js);
    }
}

function mainPhaser() {
    var game = new Phaser.Game($(window).width(), $(window).height(), Phaser.CANVAS, 'gameCanvas', { preload: preload, create: create, update: update, render: render });
    var maxColor = 2;

    game.focus = false;
    game.createSprite = function (x, y, key) {
        return this.add.sprite(x, y, String(key));
    };
    $(window).focus(function () {
        game.focus = true;
    }).blur(function () {
            game.focus = false;
        });

    setInterval(function () {
        // console.log(game.focus);
    }, 1000);

    game.changeZone = changeZone;

    var map;
    var camera;
    var player1, player2, inputsKeyboard, inputsMouse;
    var charger = new Array();

    function gofull() {
        game.stage.scale.startFullScreen();
    }

    function preload() {
        game.load.image('h_red', 'img/h_red.png');

        game.load.image('w_red', 'img/wave_red.png');
        game.load.image('w_blue', 'img/wave_blue.png');
        game.load.image('w_green', 'img/wave_green.png');
        game.load.image('w_yellow', 'img/wave_yellow.png');
        game.load.image('w_purple', 'img/wave_purple.png');

        game.load.image('obstacle', 'img/obstacle.png');
        game.load.image('greenline', 'img/greenline.png');
        game.load.image('meteor', 'img/meteor.png');

        game.load.image('stream', 'img/stream.png');
        game.load.image('charger', 'img/charger.png');
        game.load.image('charger_dead', 'img/charger_dead.png');

        game.load.audio('main1', 'sound/main1.m4a');
        game.load.audio('main2', 'sound/main2.m4a');
        game.load.audio('main3', 'sound/main3.m4a');
        game.load.audio('mainFinal', 'sound/mainFinal.m4a');

        game.load.audio('level1', 'sound/level1.m4a');
        game.load.audio('level2', 'sound/level2.m4a');
        game.load.audio('level3', 'sound/level3.m4a');
        game.load.audio('levelFinal', 'sound/finalLevel.m4a');

        game.load.audio('blop1', 'sound/blop1.m4a');
        game.load.audio('blop2', 'sound/blop2.m4a');
        game.load.audio('blop3', 'sound/blop3.m4a');
        game.load.audio('blop4', 'sound/blop4.m4a');
        game.load.audio('blop5', 'sound/blop5.m4a');

        game.load.audio('ambiance', 'sound/ambiance.m4a');
        //game.load.image('spammer','img/spammer.png');

        /*game.load.spritesheet('greenline', 'img/greenline.png', 100, 64, 30);
         game.load.spritesheet('meteor', 'img/meteor.png', 50, 50, 30);*/
    }

    function create() {

        main = [
            game.add.audio('main1'),
            game.add.audio('main2'),
            game.add.audio('main3'),
            game.add.audio('mainFinal')
        ];
        // main[0].play('',0,1,true);

        level = [
            game.add.audio('level1', 1, true),
            game.add.audio('level2', 1, true),
            game.add.audio('level3', 1, true),
            game.add.audio('levelFinal', 1, true)
        ];

        ambiance = game.add.audio('ambiance', 1, true);
        ambiance.play('', 0, 0.5, true);

        blop = {
            red: game.add.audio('blop1'),
            blue: game.add.audio('blop2'),
            green: game.add.audio('blop3'),
            yellow: game.add.audio('blop4'),
            purple: game.add.audio('blop5')
        };

        //todo Change 2 to nbPlayer when define
        map = createMapProcedural(game, 1);

//        console.debug(map);

        player1 = new Player(COLORS.RED, game);
        player1.setSprite(game.add.sprite(0, 0, 'w_red'));
        player1.sprite.scale = new Phaser.Point(2 * player1.life, 2 * player1.life);
        player1.sonar(game);
        player1.sprite.body.collideWorldBounds = true;
        player1.maxColor = maxColor;

        player2 = new Player(COLORS.BLUE, game);
        player2.setSprite(game.add.sprite(0, 0, 'w_blue'));
        player2.sprite.scale = new Phaser.Point(2 * player1.life, 2 * player1.life);
        player2.sonar(game);
        player2.sprite.body.collideWorldBounds = true;

        game.camera.follow(player1.sprite);

        inputsKeyboard = game.input.keyboard;
        inputsMouse = game.input.mousePointer;
    }

    function changeZone(newZone) {
        for (var i = 0; i < 4; i++) {
            if (i == newZone) {
                level[i].resume();
                main[i].play('', 0, 1, true);
            } else {
                console.log("pause : ", i);
                main[i].pause();
            }
        }
        ;

        if (newZone == 3) {
            ambiance.pause();
        } else {
            ambiance.resume();
        }
    }

    function update() {
        // if(!game.focus) return;
        player1.moveK(inputsKeyboard, game);
        //player2.moveM(inputsMouse);
        for (var i = 0; i < charger.length; i++) {
            if (charger[i].dead == false)
                charger[i].reachable(player1, game);
            game.physics.collide(player1.sonarPts, charger[i].sprite, charger[i].getDmg(Math.random()));

            //charger[i].reachable(player2, game);
        }
        ;

        var monsters = map.getMonsters();
        for (var i = 0; i < monsters.length; i++) {
            if (monsters.getAt(i).name == "charger")
                monsters[i].reachable(player1, game);
//            monsters[i].reachable(player2, game);
        }
        ;
//        console.log("position : " + player1.sprite.body.x + " | " + player1.sprite.body.y);
        for (var i = 0; i < charger.length; i++) {
            if (charger[i].hp <= 0 && (charger[i].dead == false)) {
                charger[i].dead = true;
                charger[i].sprite.loadTexture('charger_dead');
                charger[i].sprite.body.velocity.x = 0;
                charger[i].sprite.body.velocity.y = 0;
            }
        }
        ;

        player1.updateSector(map, game);
        // player1.farAway(game, player1);

        // check for collision over the player1's sonar
        collideHandler(player1, game);
        //collideHandler(player2,game);
    }

    function collideHandler(player, game) {
        if (player.type.name == 'red') {
            game.physics.collide(player.sonarPts, map.obstaclesRed, function (pt, ob) {
                player.sonarCollision(pt, game);
            });
        }

        if (player.type.name == 'blue') {
            game.physics.collide(player.sonarPts, map.obstaclesBlue, function (pt, ob) {
                player.sonarCollision(pt, game);
            });
        }

        if (player.type.name == 'green') {
            game.physics.collide(player.sonarPts, map.obstaclesGreen, function (pt, ob) {
                player.sonarCollision(pt, game);
            });
        }

        // console.log(player.sprite,map.obstaclesRed);
        game.physics.collide(player.sprite, map.obstaclesRed, function (pl, ob) {
            player.loseLife();
            blop[player.type.name].play();

        });
        game.physics.collide(player.sprite, map.obstaclesBlue, function (pl, ob) {
            player.loseLife();
            blop[player.type.name].play();
        });
        game.physics.collide(player.sprite, map.obstaclesGreen, function (pl, ob) {
            player.loseLife();
            blop[player.type.name].play();
        });

        map.streams.forEach(function (stream) {
            var minDist = 100;
            var param = stream.getForce(player1.sprite, game);
            if (param.distance < minDist) {
                minDist = param.distance;
                player1.applyForce(param.force, stream.x, stream.y, game);
            }
        });
    }

    function render() {

        // map.obstacles.forEachAlive(function(ob){
        //     // console.log(ob);
        //    game.debug.renderRectangle(ob,'#022ff22');
        // },this)
        // // console.log(map.obstacles);
        // // for(var i = 0; i < map.obstacles.lenght; ++i){
        // //     console.log(i);
        // // }

        // console.log("X : "+player.sprite.x+" | Y : "+player.sprite.y);
        //var m = map.getObstacles();

        // //         console.log("size = " + m.total);
        // //        console.debug(m);

        //             {
        // //                console.log("obs = " + i);
        // //                console.log(m.getAt(i));
        //                 game.debug.renderSpriteBody(m.getAt(i), '#022ff22');
        //             }
        //         }
    }
}

<commit_msg>Fix Collision Detection<commit_after>/**
 * Created by Thomas on 1/25/14.
 */

// Initialization functions
loadFiles();

window.onload = function () {
    setTimeout(function () {
        mainPhaser();
    }, 3000);
};

// JS file preloader
function loadFiles() {
    var head = document.getElementsByTagName("head")[0];
    for (var i = 0; i < files.length; i++) {
        var js = document.createElement("script");
        js.type = "text/javascript";
        js.src = "src/" + files[i];
        head.appendChild(js);
    }
}

function mainPhaser() {
    var game = new Phaser.Game($(window).width(), $(window).height(), Phaser.CANVAS, 'gameCanvas', { preload: preload, create: create, update: update, render: render });
    var maxColor = 2;

    game.focus = false;
    game.createSprite = function (x, y, key) {
        return this.add.sprite(x, y, String(key));
    };
    $(window).focus(function () {
        game.focus = true;
    }).blur(function () {
            game.focus = false;
        });

    setInterval(function () {
        // console.log(game.focus);
    }, 1000);

    game.changeZone = changeZone;

    var map;
    var camera;
    var player1, player2, inputsKeyboard, inputsMouse;
    var charger = new Array();

    function gofull() {
        game.stage.scale.startFullScreen();
    }

    function preload() {
        game.load.image('h_red', 'img/h_red.png');

        game.load.image('w_red', 'img/wave_red.png');
        game.load.image('w_blue', 'img/wave_blue.png');
        game.load.image('w_green', 'img/wave_green.png');
        game.load.image('w_yellow', 'img/wave_yellow.png');
        game.load.image('w_purple', 'img/wave_purple.png');

        game.load.image('obstacle', 'img/obstacle.png');
        game.load.image('greenline', 'img/greenline.png');
        game.load.image('meteor', 'img/meteor.png');

        game.load.image('stream', 'img/stream.png');
        game.load.image('charger', 'img/charger.png');
        game.load.image('charger_dead', 'img/charger_dead.png');

        game.load.audio('main1', 'sound/main1.m4a');
        game.load.audio('main2', 'sound/main2.m4a');
        game.load.audio('main3', 'sound/main3.m4a');
        game.load.audio('mainFinal', 'sound/mainFinal.m4a');

        game.load.audio('level1', 'sound/level1.m4a');
        game.load.audio('level2', 'sound/level2.m4a');
        game.load.audio('level3', 'sound/level3.m4a');
        game.load.audio('levelFinal', 'sound/finalLevel.m4a');

        game.load.audio('blop1', 'sound/blop1.m4a');
        game.load.audio('blop2', 'sound/blop2.m4a');
        game.load.audio('blop3', 'sound/blop3.m4a');
        game.load.audio('blop4', 'sound/blop4.m4a');
        game.load.audio('blop5', 'sound/blop5.m4a');

        game.load.audio('ambiance', 'sound/ambiance.m4a');
        //game.load.image('spammer','img/spammer.png');

        /*game.load.spritesheet('greenline', 'img/greenline.png', 100, 64, 30);
         game.load.spritesheet('meteor', 'img/meteor.png', 50, 50, 30);*/
    }

    function create() {

        main = [
            game.add.audio('main1'),
            game.add.audio('main2'),
            game.add.audio('main3'),
            game.add.audio('mainFinal')
        ];
        // main[0].play('',0,1,true);

        level = [
            game.add.audio('level1', 1, true),
            game.add.audio('level2', 1, true),
            game.add.audio('level3', 1, true),
            game.add.audio('levelFinal', 1, true)
        ];

        ambiance = game.add.audio('ambiance', 1, true);
        ambiance.play('', 0, 0.5, true);

        blop = {
            red: game.add.audio('blop1'),
            blue: game.add.audio('blop2'),
            green: game.add.audio('blop3'),
            yellow: game.add.audio('blop4'),
            purple: game.add.audio('blop5')
        };

        //todo Change 2 to nbPlayer when define
        map = createMapProcedural(game, 1);

//        console.debug(map);

        player1 = new Player(COLORS.RED, game);
        player1.setSprite(game.add.sprite(0, 0, 'w_red'));
        player1.sprite.scale = new Phaser.Point(2 * player1.life, 2 * player1.life);
        player1.sonar(game);
        player1.sprite.body.collideWorldBounds = true;
        player1.maxColor = maxColor;

        player2 = new Player(COLORS.BLUE, game);
        player2.setSprite(game.add.sprite(0, 0, 'w_blue'));
        player2.sprite.scale = new Phaser.Point(2 * player1.life, 2 * player1.life);
        player2.sonar(game);
        player2.sprite.body.collideWorldBounds = true;

        game.camera.follow(player1.sprite);

        inputsKeyboard = game.input.keyboard;
        inputsMouse = game.input.mousePointer;
    }

    function changeZone(newZone) {
        for (var i = 0; i < 4; i++) {
            if (i == newZone) {
                level[i].resume();
                main[i].play('', 0, 1, true);
            } else {
                console.log("pause : ", i);
                main[i].pause();
            }
        }
        ;

        if (newZone == 3) {
            ambiance.pause();
        } else {
            ambiance.resume();
        }
    }

    function update() {
        // if(!game.focus) return;
        player1.moveK(inputsKeyboard, game);
        //player2.moveM(inputsMouse);
        for (var i = 0; i < charger.length; i++) {
            if (charger[i].dead == false)
                charger[i].reachable(player1, game);
           if(game.physics.collide(player1.sonarPts,charger[i].sprite))
            {
                charger[i].getDmg(1);
            }

            //charger[i].reachable(player2, game);
        }
        ;

        var monsters = map.getMonsters();
        for (var i = 0; i < monsters.length; i++) {
            if (monsters.getAt(i).name == "charger")
                monsters[i].reachable(player1, game);
//            monsters[i].reachable(player2, game);
        }
        ;
//        console.log("position : " + player1.sprite.body.x + " | " + player1.sprite.body.y);
        for (var i = 0; i < charger.length; i++) {
            if (charger[i].hp <= 0 && (charger[i].dead == false)) {
                charger[i].dead = true;
                charger[i].sprite.loadTexture('charger_dead');
                charger[i].sprite.body.velocity.x = 0;
                charger[i].sprite.body.velocity.y = 0;
            }
        }
        ;

        player1.updateSector(map, game);
        // player1.farAway(game, player1);

        // check for collision over the player1's sonar
        collideHandler(player1, game);
        //collideHandler(player2,game);
    }

    function collideHandler(player, game) {
        if (player.type.name == 'red') {
            game.physics.collide(player.sonarPts, map.obstaclesRed, function (pt, ob) {
                player.sonarCollision(pt, game);
            });
        }

        if (player.type.name == 'blue') {
            game.physics.collide(player.sonarPts, map.obstaclesBlue, function (pt, ob) {
                player.sonarCollision(pt, game);
            });
        }

        if (player.type.name == 'green') {
            game.physics.collide(player.sonarPts, map.obstaclesGreen, function (pt, ob) {
                player.sonarCollision(pt, game);
            });
        }

        // console.log(player.sprite,map.obstaclesRed);
        game.physics.collide(player.sprite, map.obstaclesRed, function (pl, ob) {
            player.loseLife();
            blop[player.type.name].play();

        });
        game.physics.collide(player.sprite, map.obstaclesBlue, function (pl, ob) {
            player.loseLife();
            blop[player.type.name].play();
        });
        game.physics.collide(player.sprite, map.obstaclesGreen, function (pl, ob) {
            player.loseLife();
            blop[player.type.name].play();
        });

        map.streams.forEach(function (stream) {
            var minDist = 100;
            var param = stream.getForce(player1.sprite, game);
            if (param.distance < minDist) {
                minDist = param.distance;
                player1.applyForce(param.force, stream.x, stream.y, game);
            }
        });
    }

    function render() {

        // map.obstacles.forEachAlive(function(ob){
        //     // console.log(ob);
        //    game.debug.renderRectangle(ob,'#022ff22');
        // },this)
        // // console.log(map.obstacles);
        // // for(var i = 0; i < map.obstacles.lenght; ++i){
        // //     console.log(i);
        // // }

        // console.log("X : "+player.sprite.x+" | Y : "+player.sprite.y);
        //var m = map.getObstacles();

        // //         console.log("size = " + m.total);
        // //        console.debug(m);

        //             {
        // //                console.log("obs = " + i);
        // //                console.log(m.getAt(i));
        //                 game.debug.renderSpriteBody(m.getAt(i), '#022ff22');
        //             }
        //         }
    }
}

<|endoftext|>


<commit_before>import { dialog, app, Menu } from 'electron';

const kernelspecs = require('kernelspecs');

import { launchFilename, launchNewNotebook } from './launch';

import * as path from 'path';

function send(focusedWindow, eventName, obj) {
  if (!focusedWindow) {
    console.error('renderer window not in focus (are your devtools open?)');
    return;
  }
  focusedWindow.webContents.send(eventName, obj);
}

function createSender(eventName, obj) {
  return (item, focusedWindow) => {
    send(focusedWindow, eventName, obj);
  };
}

export const fileSubMenus = {
  new: {
    label: '&New',
    accelerator: 'CmdOrCtrl+N',
  },
  open: {
    label: '&Open',
    click: () => {
      const opts = {
        title: 'Open a notebook',
        filters: [
          { name: 'Notebooks', extensions: ['ipynb'] },
        ],
        properties: [
          'openFile',
        ],
        // TODO: This should be based on the currently opened notebook
        defaultPath: process.cwd(),
      };
      dialog.showOpenDialog(opts, (fname) => {
        if (fname) {
          launchFilename(fname[0]);
        }
      });
    },
    accelerator: 'CmdOrCtrl+O',
  },
  save: {
    label: '&Save',
    click: createSender('menu:save'),
    accelerator: 'CmdOrCtrl+S',
  },
  saveAs: {
    label: 'Save &As',
    click: (item, focusedWindow) => {
      const opts = {
        title: 'Save Notebook As',
        filters: [{ name: 'Notebooks', extensions: ['ipynb'] }],
      };
      dialog.showSaveDialog(opts, (filename) => {
        if (!filename) {
          return;
        }

        const ext = path.extname(filename) === '' ? '.ipynb' : '';
        send(focusedWindow, 'menu:save-as', `${filename}${ext}`);
      });
    },
    accelerator: 'CmdOrCtrl+Shift+S',
  },
};

export const file = {
  label: '&File',
  submenu: [
    fileSubMenus.new,
    fileSubMenus.open,
    fileSubMenus.save,
    fileSubMenus.saveAs,
  ],
};

export const edit = {
  label: 'Edit',
  submenu: [
    {
      label: 'Undo',
      accelerator: 'CmdOrCtrl+Z',
      role: 'undo',
    },
    {
      label: 'Redo',
      accelerator: 'Shift+CmdOrCtrl+Z',
      role: 'redo',
    },
    {
      type: 'separator',
    },
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
    },
    {
      label: 'Copy',
      accelerator: 'CmdOrCtrl+C',
      role: 'copy',
    },
    {
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    },
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    },
  ],
};

export const cell = {
  label: 'Cell',
  submenu: [
    {
      label: 'Run All',
      click: createSender('menu:run-all')
    },
  ],
};

export const view = {
  label: 'View',
  submenu: [
    {
      label: 'Reload',
      accelerator: 'CmdOrCtrl+R',
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.reload();
        }
      },
    },
    {
      label: 'Toggle Full Screen',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Ctrl+Command+F';
        }
        return 'F11';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
    },
    {
      label: 'Toggle Developer Tools',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Alt+Command+I';
        }
        return 'Ctrl+Shift+I';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.toggleDevTools();
        }
      },
    },
    {
      label: 'Zoom In',
      accelerator: 'CmdOrCtrl+=',
      click: createSender('menu:zoom-in')
    },
    {
      label: 'Zoom Out',
      accelerator: 'CmdOrCtrl+-',
      click: createSender('menu:zoom-out')
    },
    {
      label: 'Theme',
      submenu: [
        {
          label: 'Light',
          click: createSender('menu:theme', 'light'),
        },
        {
          label: 'Dark',
          click: createSender('menu:theme', 'dark'),
        },
      ],
    },
  ],
};

export const publish = {
  label: 'Publish',
  submenu: [
    {
      label: 'to Gist...',
      click: createSender('menu:publish:gist'),
    },
  ],
};

const windowDraft = {
  label: 'Window',
  role: 'window',
  submenu: [
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize',
    },
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+W',
      role: 'close',
    },
  ],
};

if (process.platform === 'darwin') {
  windowDraft.submenu.push(
    {
      type: 'separator',
    },
    {
      label: 'Bring All to Front',
      role: 'front',
    }
  );
}

export const window = windowDraft;

export const help = {
  label: 'Help',
  role: 'help',
  submenu: [
    {
      label: 'Learn More',
      click: () => { require('electron').shell.openExternal('http://github.com/nteract/nteract'); },
    },
  ],
};

const name = 'nteract';
app.setName(name);

export const named = {
  label: name,
  submenu: [
    {
      label: `About ${name}`,
      role: 'about',
    },
    {
      type: 'separator',
    },
    {
      label: 'Services',
      role: 'services',
      submenu: [],
    },
    {
      type: 'separator',
    },
    {
      label: `Hide ${name}`,
      accelerator: 'Command+H',
      role: 'hide',
    },
    {
      label: 'Hide Others',
      accelerator: 'Command+Alt+H',
      role: 'hideothers',
    },
    {
      label: 'Show All',
      role: 'unhide',
    },
    {
      type: 'separator',
    },
    {
      label: 'Quit',
      accelerator: 'Command+Q',
      click: () => app.quit(),
    },
  ],
};

export function generateDefaultTemplate() {
  const template = [];

  if (process.platform === 'darwin') {
    template.push(named);
  }

  template.push(file);
  template.push(edit);
  template.push(view);
  template.push(publish);
  template.push(window);
  template.push(help);

  return template;
}

export const defaultMenu = Menu.buildFromTemplate(generateDefaultTemplate());

export function loadFullMenu() {
  return kernelspecs.findAll().then(kernelSpecs => {
    function generateSubMenu(kernelName) {
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: createSender('menu:new-kernel', kernelName),
      };
    }

    const kernelMenuItems = Object.keys(kernelSpecs).map(generateSubMenu);

    const newNotebookItems = Object.keys(kernelSpecs).map(kernelName => {
      const kernelSpec = kernelSpecs[kernelName];
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: () => launchNewNotebook(kernelSpec),
      };
    });

    const languageMenu = {
      label: '&Language',
      submenu: [
        {
          label: '&Kill Running Kernel',
          click: createSender('menu:kill-kernel'),
        },
        {
          type: 'separator',
        },
        // All the available kernels
        ...kernelMenuItems,
      ],
    };
    const template = [];

    if (process.platform === 'darwin') {
      template.push(named);
    }

    const fileWithNew = {
      label: '&File',
      submenu: [
        {
          label: '&New',
          submenu: [
            ...newNotebookItems,
          ],
        },
        fileSubMenus.open,
        fileSubMenus.save,
        fileSubMenus.saveAs,
      ],
    };

    template.push(fileWithNew);
    template.push(edit);
    template.push(cell);
    template.push(view);

    // Application specific functionality should go before window and help
    template.push(languageMenu);
    template.push(publish);
    template.push(window);
    template.push(help);

    const menu = Menu.buildFromTemplate(template);
    return menu;
  });
}
<commit_msg>lint main/menu<commit_after>import { dialog, app, shell, Menu } from 'electron';

const kernelspecs = require('kernelspecs');

import { launchFilename, launchNewNotebook } from './launch';

import * as path from 'path';

function send(focusedWindow, eventName, obj) {
  if (!focusedWindow) {
    console.error('renderer window not in focus (are your devtools open?)');
    return;
  }
  focusedWindow.webContents.send(eventName, obj);
}

function createSender(eventName, obj) {
  return (item, focusedWindow) => {
    send(focusedWindow, eventName, obj);
  };
}

export const fileSubMenus = {
  new: {
    label: '&New',
    accelerator: 'CmdOrCtrl+N',
  },
  open: {
    label: '&Open',
    click: () => {
      const opts = {
        title: 'Open a notebook',
        filters: [
          { name: 'Notebooks', extensions: ['ipynb'] },
        ],
        properties: [
          'openFile',
        ],
        // TODO: This should be based on the currently opened notebook
        defaultPath: process.cwd(),
      };
      dialog.showOpenDialog(opts, (fname) => {
        if (fname) {
          launchFilename(fname[0]);
        }
      });
    },
    accelerator: 'CmdOrCtrl+O',
  },
  save: {
    label: '&Save',
    click: createSender('menu:save'),
    accelerator: 'CmdOrCtrl+S',
  },
  saveAs: {
    label: 'Save &As',
    click: (item, focusedWindow) => {
      const opts = {
        title: 'Save Notebook As',
        filters: [{ name: 'Notebooks', extensions: ['ipynb'] }],
      };
      dialog.showSaveDialog(opts, (filename) => {
        if (!filename) {
          return;
        }

        const ext = path.extname(filename) === '' ? '.ipynb' : '';
        send(focusedWindow, 'menu:save-as', `${filename}${ext}`);
      });
    },
    accelerator: 'CmdOrCtrl+Shift+S',
  },
};

export const file = {
  label: '&File',
  submenu: [
    fileSubMenus.new,
    fileSubMenus.open,
    fileSubMenus.save,
    fileSubMenus.saveAs,
  ],
};

export const edit = {
  label: 'Edit',
  submenu: [
    {
      label: 'Undo',
      accelerator: 'CmdOrCtrl+Z',
      role: 'undo',
    },
    {
      label: 'Redo',
      accelerator: 'Shift+CmdOrCtrl+Z',
      role: 'redo',
    },
    {
      type: 'separator',
    },
    {
      label: 'Cut',
      accelerator: 'CmdOrCtrl+X',
      role: 'cut',
    },
    {
      label: 'Copy',
      accelerator: 'CmdOrCtrl+C',
      role: 'copy',
    },
    {
      label: 'Paste',
      accelerator: 'CmdOrCtrl+V',
      role: 'paste',
    },
    {
      label: 'Select All',
      accelerator: 'CmdOrCtrl+A',
      role: 'selectall',
    },
  ],
};

export const cell = {
  label: 'Cell',
  submenu: [
    {
      label: 'Run All',
      click: createSender('menu:run-all'),
    },
  ],
};

export const view = {
  label: 'View',
  submenu: [
    {
      label: 'Reload',
      accelerator: 'CmdOrCtrl+R',
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.reload();
        }
      },
    },
    {
      label: 'Toggle Full Screen',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Ctrl+Command+F';
        }
        return 'F11';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
        }
      },
    },
    {
      label: 'Toggle Developer Tools',
      accelerator: (() => {
        if (process.platform === 'darwin') {
          return 'Alt+Command+I';
        }
        return 'Ctrl+Shift+I';
      })(),
      click: (item, focusedWindow) => {
        if (focusedWindow) {
          focusedWindow.toggleDevTools();
        }
      },
    },
    {
      label: 'Zoom In',
      accelerator: 'CmdOrCtrl+=',
      click: createSender('menu:zoom-in'),
    },
    {
      label: 'Zoom Out',
      accelerator: 'CmdOrCtrl+-',
      click: createSender('menu:zoom-out'),
    },
    {
      label: 'Theme',
      submenu: [
        {
          label: 'Light',
          click: createSender('menu:theme', 'light'),
        },
        {
          label: 'Dark',
          click: createSender('menu:theme', 'dark'),
        },
      ],
    },
  ],
};

export const publish = {
  label: 'Publish',
  submenu: [
    {
      label: 'to Gist...',
      click: createSender('menu:publish:gist'),
    },
  ],
};

const windowDraft = {
  label: 'Window',
  role: 'window',
  submenu: [
    {
      label: 'Minimize',
      accelerator: 'CmdOrCtrl+M',
      role: 'minimize',
    },
    {
      label: 'Close',
      accelerator: 'CmdOrCtrl+W',
      role: 'close',
    },
  ],
};

if (process.platform === 'darwin') {
  windowDraft.submenu.push(
    {
      type: 'separator',
    },
    {
      label: 'Bring All to Front',
      role: 'front',
    }
  );
}

export const window = windowDraft;

export const help = {
  label: 'Help',
  role: 'help',
  submenu: [
    {
      label: 'Learn More',
      click: () => { shell.openExternal('http://github.com/nteract/nteract'); },
    },
  ],
};

const name = 'nteract';
app.setName(name);

export const named = {
  label: name,
  submenu: [
    {
      label: `About ${name}`,
      role: 'about',
    },
    {
      type: 'separator',
    },
    {
      label: 'Services',
      role: 'services',
      submenu: [],
    },
    {
      type: 'separator',
    },
    {
      label: `Hide ${name}`,
      accelerator: 'Command+H',
      role: 'hide',
    },
    {
      label: 'Hide Others',
      accelerator: 'Command+Alt+H',
      role: 'hideothers',
    },
    {
      label: 'Show All',
      role: 'unhide',
    },
    {
      type: 'separator',
    },
    {
      label: 'Quit',
      accelerator: 'Command+Q',
      click: () => app.quit(),
    },
  ],
};

export function generateDefaultTemplate() {
  const template = [];

  if (process.platform === 'darwin') {
    template.push(named);
  }

  template.push(file);
  template.push(edit);
  template.push(view);
  template.push(publish);
  template.push(window);
  template.push(help);

  return template;
}

export const defaultMenu = Menu.buildFromTemplate(generateDefaultTemplate());

export function loadFullMenu() {
  return kernelspecs.findAll().then(kernelSpecs => {
    function generateSubMenu(kernelName) {
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: createSender('menu:new-kernel', kernelName),
      };
    }

    const kernelMenuItems = Object.keys(kernelSpecs).map(generateSubMenu);

    const newNotebookItems = Object.keys(kernelSpecs).map(kernelName => {
      const kernelSpec = kernelSpecs[kernelName];
      return {
        label: kernelSpecs[kernelName].spec.display_name,
        click: () => launchNewNotebook(kernelSpec),
      };
    });

    const languageMenu = {
      label: '&Language',
      submenu: [
        {
          label: '&Kill Running Kernel',
          click: createSender('menu:kill-kernel'),
        },
        {
          type: 'separator',
        },
        // All the available kernels
        ...kernelMenuItems,
      ],
    };
    const template = [];

    if (process.platform === 'darwin') {
      template.push(named);
    }

    const fileWithNew = {
      label: '&File',
      submenu: [
        {
          label: '&New',
          submenu: [
            ...newNotebookItems,
          ],
        },
        fileSubMenus.open,
        fileSubMenus.save,
        fileSubMenus.saveAs,
      ],
    };

    template.push(fileWithNew);
    template.push(edit);
    template.push(cell);
    template.push(view);

    // Application specific functionality should go before window and help
    template.push(languageMenu);
    template.push(publish);
    template.push(window);
    template.push(help);

    const menu = Menu.buildFromTemplate(template);
    return menu;
  });
}
<|endoftext|>


<commit_before>import { Events, Styler, UICorePlugin, template } from 'clappr'
import pluginHtml from './public/level-selector.html'
import pluginStyle from './public/style.scss'

const AUTO = -1

export default class LevelSelector extends UICorePlugin {

  static get version() { return VERSION }

  get name() { return 'level_selector' }
  get template() { return template(pluginHtml) }

  get attributes() {
    return {
      'class': this.name,
      'data-level-selector': ''
    }
  }

  get events() {
    return {
      'click [data-level-selector-select]': 'onLevelSelect',
      'click [data-level-selector-button]': 'onShowLevelSelectMenu'
    }
  }

  get __container() {
    return this.core.activeContainer
      ? this.core.activeContainer
      : this.core.mediaControl.container
  }

  get __playback() {
    return this.core.activePlayback
      ? this.core.activePlayback
      : this.core.getCurrentPlayback()
  }

  bindEvents() {
    this.listenTo(this.core, Events.CORE_READY, this.bindPlaybackEvents)
    if (Events.CORE_ACTIVE_CONTAINER_CHANGED)
      this.listenTo(this.core, Events.CORE_ACTIVE_CONTAINER_CHANGED, this.reload)
    else
      this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.reload)
    this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.render)
    this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_HIDE, this.hideSelectLevelMenu)
  }

  unBindEvents() {
    this.stopListening(this.core, Events.CORE_READY)
    if (Events.CORE_ACTIVE_CONTAINER_CHANGED)
      this.stopListening(this.core, Events.CORE_ACTIVE_CONTAINER_CHANGED)
    else
      this.stopListening(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED)
    this.stopListening(this.core.mediaControl, Events.MEDIACONTROL_RENDERED)
    this.stopListening(this.core.mediaControl, Events.MEDIACONTROL_HIDE)
    this.stopListening(this.__playback, Events.PLAYBACK_LEVELS_AVAILABLE)
    this.stopListening(this.__playback, Events.PLAYBACK_LEVEL_SWITCH_START)
    this.stopListening(this.__playback, Events.PLAYBACK_LEVEL_SWITCH_END)
    this.stopListening(this.__playback, Events.PLAYBACK_BITRATE)
  }

  bindPlaybackEvents() {
    this.listenTo(this.__playback, Events.PLAYBACK_LEVELS_AVAILABLE, this.fillLevels)
    this.listenTo(this.__playback, Events.PLAYBACK_LEVEL_SWITCH_START, this.startLevelSwitch)
    this.listenTo(this.__playback, Events.PLAYBACK_LEVEL_SWITCH_END, this.stopLevelSwitch)
    this.listenTo(this.__playback, Events.PLAYBACK_BITRATE, this.updateCurrentLevel)

    let playbackLevelsAvaialbeWasTriggered = this.__playback.levels && this.__playback.levels.length > 0
    playbackLevelsAvaialbeWasTriggered && this.fillLevels(this.__playback.levels)
  }

  reload() {
    this.unBindEvents()
    this.bindEvents()
    this.bindPlaybackEvents()
  }

  shouldRender() {
    if (!this.__container) return false

    if (!this.__playback) return false

    let respondsToCurrentLevel = this.__playback.currentLevel !== undefined
    // Only care if we have at least 2 to choose from
    let hasLevels = !!(this.levels && this.levels.length > 1)

    return respondsToCurrentLevel && hasLevels
  }

  render() {
    if (this.shouldRender()) {
      let style = Styler.getStyleFor(pluginStyle, { baseUrl: this.core.options.baseUrl })

      this.$el.html(this.template({ 'levels':this.levels, 'title': this.getTitle() }))
      this.$el.append(style)
      this.core.mediaControl.$('.media-control-right-panel').append(this.el)
      this.highlightCurrentLevel()
    }
    return this
  }

  fillLevels(levels, initialLevel = AUTO) {
    if (this.selectedLevelId === undefined) this.selectedLevelId = initialLevel
    this.levels = levels
    this.configureLevelsLabels()
    this.render()
  }

  configureLevelsLabels() {
    if (this.core.options.levelSelectorConfig === undefined) return

    let labelCallback = this.core.options.levelSelectorConfig.labelCallback
    if (labelCallback && typeof labelCallback !== 'function')
      throw new TypeError('labelCallback must be a function')

    let hasLabels = this.core.options.levelSelectorConfig.labels
    let labels = hasLabels ? this.core.options.levelSelectorConfig.labels : {}

    if (labelCallback || hasLabels) {
      let level
      let label
      for (let levelId in this.levels) {
        level = this.levels[levelId]
        label = labels[level.id]
        if (labelCallback)
          level.label = labelCallback(level,label)
        else if (label)
          level.label = label

      }
    }
  }

  findLevelBy(id) {
    let foundLevel
    this.levels.forEach((level) => { if (level.id === id) foundLevel = level })
    return foundLevel
  }

  onLevelSelect(event) {
    this.selectedLevelId = parseInt(event.target.dataset.levelSelectorSelect, 10)
    if (this.__playback.currentLevel == this.selectedLevelId) return false
    this.__playback.currentLevel = this.selectedLevelId

    this.toggleContextMenu()

    event.stopPropagation()
    return false
  }

  onShowLevelSelectMenu() { this.toggleContextMenu() }

  hideSelectLevelMenu() { this.$('.level_selector ul').hide() }

  toggleContextMenu() { this.$('.level_selector ul').toggle() }

  buttonElement() { return this.$('.level_selector button') }

  levelElement(id) { return this.$('.level_selector ul a'+(!isNaN(id) ? '[data-level-selector-select="'+id+'"]' : '')).parent() }

  getTitle() { return (this.core.options.levelSelectorConfig || {}).title }

  startLevelSwitch() { this.buttonElement().addClass('changing') }

  stopLevelSwitch() { this.buttonElement().removeClass('changing') }

  updateText(level) {
    if (level === AUTO)
      this.buttonElement().text(this.currentLevel ? 'AUTO (' + this.currentLevel.label + ')' : 'AUTO')

    else
      this.buttonElement().text(this.findLevelBy(level).label)

  }
  updateCurrentLevel(info) {
    let level = this.findLevelBy(info.level)
    this.currentLevel = level ? level : null
    this.highlightCurrentLevel()
  }
  highlightCurrentLevel() {
    this.levelElement().removeClass('current')
    this.currentLevel && this.levelElement(this.currentLevel.id).addClass('current')
    this.updateText(this.selectedLevelId)
  }
}
<commit_msg>style: fix small typo and lint<commit_after>import { Events, Styler, UICorePlugin, template } from 'clappr'
import pluginHtml from './public/level-selector.html'
import pluginStyle from './public/style.scss'

const AUTO = -1

export default class LevelSelector extends UICorePlugin {

  static get version() { return VERSION }

  get name() { return 'level_selector' }
  get template() { return template(pluginHtml) }

  get attributes() {
    return {
      'class': this.name,
      'data-level-selector': ''
    }
  }

  get events() {
    return {
      'click [data-level-selector-select]': 'onLevelSelect',
      'click [data-level-selector-button]': 'onShowLevelSelectMenu'
    }
  }

  get __container() {
    return this.core.activeContainer
      ? this.core.activeContainer
      : this.core.mediaControl.container
  }

  get __playback() {
    return this.core.activePlayback
      ? this.core.activePlayback
      : this.core.getCurrentPlayback()
  }

  bindEvents() {
    this.listenTo(this.core, Events.CORE_READY, this.bindPlaybackEvents)
    if (Events.CORE_ACTIVE_CONTAINER_CHANGED)
      this.listenTo(this.core, Events.CORE_ACTIVE_CONTAINER_CHANGED, this.reload)
    else
      this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.reload)
    this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.render)
    this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_HIDE, this.hideSelectLevelMenu)
  }

  unBindEvents() {
    this.stopListening(this.core, Events.CORE_READY)
    if (Events.CORE_ACTIVE_CONTAINER_CHANGED)
      this.stopListening(this.core, Events.CORE_ACTIVE_CONTAINER_CHANGED)
    else
      this.stopListening(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED)
    this.stopListening(this.core.mediaControl, Events.MEDIACONTROL_RENDERED)
    this.stopListening(this.core.mediaControl, Events.MEDIACONTROL_HIDE)
    this.stopListening(this.__playback, Events.PLAYBACK_LEVELS_AVAILABLE)
    this.stopListening(this.__playback, Events.PLAYBACK_LEVEL_SWITCH_START)
    this.stopListening(this.__playback, Events.PLAYBACK_LEVEL_SWITCH_END)
    this.stopListening(this.__playback, Events.PLAYBACK_BITRATE)
  }

  bindPlaybackEvents() {
    this.listenTo(this.__playback, Events.PLAYBACK_LEVELS_AVAILABLE, this.fillLevels)
    this.listenTo(this.__playback, Events.PLAYBACK_LEVEL_SWITCH_START, this.startLevelSwitch)
    this.listenTo(this.__playback, Events.PLAYBACK_LEVEL_SWITCH_END, this.stopLevelSwitch)
    this.listenTo(this.__playback, Events.PLAYBACK_BITRATE, this.updateCurrentLevel)

    let playbackLevelsAvailableWasTriggered = this.__playback.levels && this.__playback.levels.length > 0
    playbackLevelsAvailableWasTriggered && this.fillLevels(this.__playback.levels)
  }

  reload() {
    this.unBindEvents()
    this.bindEvents()
    this.bindPlaybackEvents()
  }

  shouldRender() {
    if (!this.__container) return false

    if (!this.__playback) return false

    let respondsToCurrentLevel = this.__playback.currentLevel !== undefined
    // Only care if we have at least 2 to choose from
    let hasLevels = !!(this.levels && this.levels.length > 1)

    return respondsToCurrentLevel && hasLevels
  }

  render() {
    if (this.shouldRender()) {
      let style = Styler.getStyleFor(pluginStyle, { baseUrl: this.core.options.baseUrl })

      this.$el.html(this.template({ 'levels':this.levels, 'title': this.getTitle() }))
      this.$el.append(style)
      this.core.mediaControl.$('.media-control-right-panel').append(this.el)
      this.highlightCurrentLevel()
    }
    return this
  }

  fillLevels(levels, initialLevel = AUTO) {
    if (this.selectedLevelId === undefined) this.selectedLevelId = initialLevel
    this.levels = levels
    this.configureLevelsLabels()
    this.render()
  }

  configureLevelsLabels() {
    if (this.core.options.levelSelectorConfig === undefined) return

    let labelCallback = this.core.options.levelSelectorConfig.labelCallback
    if (labelCallback && typeof labelCallback !== 'function')
      throw new TypeError('labelCallback must be a function')

    let hasLabels = this.core.options.levelSelectorConfig.labels
    let labels = hasLabels ? this.core.options.levelSelectorConfig.labels : {}

    if (labelCallback || hasLabels) {
      let level
      let label
      for (let levelId in this.levels) {
        level = this.levels[levelId]
        label = labels[level.id]
        if (labelCallback)
          level.label = labelCallback(level,label)
        else if (label)
          level.label = label

      }
    }
  }

  findLevelBy(id) {
    let foundLevel
    this.levels.forEach((level) => { if (level.id === id) foundLevel = level })
    return foundLevel
  }

  onLevelSelect(event) {
    this.selectedLevelId = parseInt(event.target.dataset.levelSelectorSelect, 10)
    if (this.__playback.currentLevel == this.selectedLevelId) return false
    this.__playback.currentLevel = this.selectedLevelId

    this.toggleContextMenu()

    event.stopPropagation()
    return false
  }

  onShowLevelSelectMenu() { this.toggleContextMenu() }

  hideSelectLevelMenu() { this.$('.level_selector ul').hide() }

  toggleContextMenu() { this.$('.level_selector ul').toggle() }

  buttonElement() { return this.$('.level_selector button') }

  levelElement(id) { return this.$('.level_selector ul a'+(!isNaN(id) ? '[data-level-selector-select="'+id+'"]' : '')).parent() }

  getTitle() { return (this.core.options.levelSelectorConfig || {}).title }

  startLevelSwitch() { this.buttonElement().addClass('changing') }

  stopLevelSwitch() { this.buttonElement().removeClass('changing') }

  updateText(level) {
    if (level === AUTO)
      this.buttonElement().text(this.currentLevel ? 'AUTO (' + this.currentLevel.label + ')' : 'AUTO')

    else
      this.buttonElement().text(this.findLevelBy(level).label)

  }

  updateCurrentLevel(info) {
    let level = this.findLevelBy(info.level)
    this.currentLevel = level ? level : null
    this.highlightCurrentLevel()
  }

  highlightCurrentLevel() {
    this.levelElement().removeClass('current')
    this.currentLevel && this.levelElement(this.currentLevel.id).addClass('current')
    this.updateText(this.selectedLevelId)
  }
}
<|endoftext|>


<commit_before>var transit = (function () {
    return {
        initMap : function () {
            var mapDet = {
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('transitMap'), mapDet);
            return map;
        },

        initMarker : function (coords, mouseoverText, map) {
            mouseoverText = (typeof mouseoverText == 'undefined') ? 'Marker' : mouseoverText;
            var markerPos = new google.maps.LatLng(coords.x, coords.y);

            var markerIcon = {
                path: google.maps.SymbolPath.CIRCLE,
                fillColor: 'red',
                fillOpacity: 0.8,
                scale: 5
            };

            var mouseoverInfo = new google.maps.InfoWindow({
                content: mouseoverText,
                map: map
            });

            var marker = {
                position: markerPos,
                icon: markerIcon
            };

            marker = new google.maps.Marker(marker);

            google.maps.event.addListener(marker, 'mouseover', function() {
            	mouseoverInfo.open(map, this);
            });

            google.maps.event.addListener(marker, 'mouseout', function() {
            	mouseoverInfo.close();
            });

            return marker;
        },

        moveMarkers : function (markerSet, interval, map) {
            interval = (typeof interval == 'undefined') ? 1000 : interval;
            var transition = setInterval(
                    function () {
                        for (var counter = 0; counter < markerSet.length; counter++) {
                            for (var i = 0; i < markerSet.length; i++) {
                                var curPos = new google.maps.LatLng(markerSet[i].coordSet[counter][0],
                                    markerSet[i].coordSet[counter][1]);
                                markerSet[i].marker.position = curPos;
                                markerSet[i].marker.setMap(map);
                            }
                        }
                    },
                    interval);
        },

        constructMarkerSet : function (markers) {
            var markerSet = new Array();
            for (var counter = 0; counter < markers.length; counter++) {
                var markerObj = transit.initMarker(markers[counter].coords[0], markers[counter].title);
                var coordList = markers[counter].coords.slice(1);

                markerSet.push({
                    marker: markerObj,
                    coordSet: coordList
                });
            }
            return markerSet;
        },

        overlayKml : function (kmlUrl, map) {
            var kmlOptions = {
                map: map
            };
            var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);
        },

        routeParser : function (xmlUrl) {
            var lines = {};
            var points = {};

            $.ajax({
                url: xmlUrl,
                dataType: 'xml',
                async: false,
                success : function (data) {
                    var xmlNode = $('Document', data);

                    xmlNode.find('Placemark > LineString > coordinates').each(function () {
                        var simPts = transit.trim($(this).text()).split(' ');
                        var grpPts = new Array();
                        var routeName = $(this).closest('Placemark').find('name').text().toLowerCase();
                        for (eachPt in simPts) {
                            var xy = transit.strip(simPts[eachPt]).split(',');
                            grpPts.push({ x: parseFloat(xy[0], 10), y: parseFloat(xy[1], 10) });
                        }
                        lines[transit.trim(routeName)] = grpPts;
                    });

                    xmlNode.find('Point').each(function () {
                        var parentTag = $(this).closest('Placemark');

                        var xy = transit.strip(parentTag.find('Point').text()).split(',');
                        points[transit.trim(parentTag.find('name').text()).toLowerCase()] = {
                            x: parseFloat(xy[0], 10),
                            y: parseFloat(xy[1], 10)
                        };
                    });
                },
                error : function (data) {
                    console.log('Error');
                }
            });

            return {
                "lines": lines,
                "points": points
            };
        },

        vehicleParser : function (jsonUrl) {
            var vehicleObj = {};

            $.ajax({
                url: jsonUrl,
                dataType: 'json',
                async: false,
                success : function (data) {
                    vehicleObj.timezone = data.timezone;
                    vehicleObj.vehicles = data.vehicles;
                },
                error : function (data) {
                    console.log('Error');
                }
            });

            return vehicleObj;
        },

        schedule : function (vehicleObj, routes, timezone) {
            var vehicleArrivals = {};
            var vehicleDepartures = {};
            var vehicleTravelTimes = new Array();
            var vehicleRoute = vehicleObj.route;
            var stopsObj = vehicleObj.stops;
            var noOfStops = vehicleObj.stops.length;
            var firstStop = stopsObj[0];
            var firstStopName = firstStop.name.toLowerCase();
            var startTime = transit.parseTime(firstStop.departure, firstStop.day, timezone);
            var vehicleStopCoords = {};
            var points = routes.points;
            var opLine = routes.lines[vehicleRoute.toLowerCase()];

            vehicleDepartures[startTime - startTime] = firstStopName;
            vehicleTravelTimes.push(startTime - startTime);
            vehicleStopCoords[firstStopName] = transit.resolvePointToLine(opLine, points[firstStopName]);

            for (var eachStop = 1; eachStop < noOfStops - 1; eachStop++) {
                var temp = stopsObj[eachStop];
                var tempName = temp.name.toLowerCase();
                var currArrivalTime = transit.parseTime(temp.arrival, temp.day, timezone) - startTime;
                var currDepartureTime = transit.parseTime(temp.departure, temp.day, timezone) - startTime;
                vehicleArrivals[currArrivalTime] = tempName;
                vehicleDepartures[currDepartureTime] = tempName;
                vehicleTravelTimes.push(currArrivalTime, currDepartureTime);
                vehicleStopCoords[tempName] = transit.resolvePointToLine(opLine, points[tempName]);
            }

            var lastStop = stopsObj[noOfStops - 1];
            var lastStopName = lastStop.name.toLowerCase();
            var endTime = transit.parseTime(lastStop.arrival, lastStop.day, timezone) - startTime;
            vehicleArrivals[endTime] = lastStopName;
            vehicleTravelTimes.push(endTime);
            vehicleStopCoords[lastStopName] = transit.resolvePointToLine(opLine, points[lastStopName]);
            var line = transit.pointsBetweenStops(opLine,
                                                  vehicleStopCoords[firstStopName],
                                                  vehicleStopCoords[lastStopName]);
            var percentStopDists = transit.hashOfPercentDists(line);

            var percentDists = new Array();
            for (var x in percentStopDists) percentDists.push(x);

            return {
                "name": vehicleObj.name,
                "info": vehicleObj.info,
                "starts": startTime,
                "route": line,
                "stops": vehicleStopCoords,
                "ppoints": percentStopDists,
                "ppercents": percentDists,
                "days": lastStop.day - firstStop.day,
                "arrivals": vehicleArrivals,
                "departures": vehicleDepartures,
                "traveltimes": vehicleTravelTimes
            };
        },

        strip : function (string) {
            return string.replace(/\s+/g, '').replace(/\n/g, '');
        },

        trim : function (string) {
            return string.replace(/^\s+|\s+$/g, '');
        },

        resolvePointToLine : function (line, point) {
            var closestDist = transit.linearDist(line[0], point);
            var currPt = line[0]
            for (var count = 1; count < line.length; count++) {
                var currDist = transit.linearDist(line[count], point);
                if (closestDist > currDist)
                    currPt = line[count];
            }

            return currPt;
        },

        // Reimplemented from http://www.movable-type.co.uk/scripts/latlong.html
        haversine : function (sourceCoords, targetCoords) {
            var R = 6371; // km

            /** Converts numeric degrees to radians */
            if (typeof(Number.prototype.toRad) === "undefined") {
              Number.prototype.toRad = function() {
                return this * Math.PI / 180;
              }
            }

            var dLat = (targetCoords.x - sourceCoords.x).toRad();
            var dLon = (targetCoords.y - sourceCoords.y).toRad();
            var lat1 = sourceCoords.x.toRad();
            var lat2 = targetCoords.x.toRad();

            var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
            var d = R * c;
            return d;
        },

        linearDist : function (sourceCoords, targetCoords) {
            return Math.sqrt(Math.pow((targetCoords.x - sourceCoords.x), 2),
                             Math.pow((targetCoords.y - sourceCoords.y), 2));
        },

        percentDist : function (sourceCoords, targetCoords, percentage) {
            var newCoords = {};
            var ratio = percentage / 100;
            newCoords.x = (1 - ratio) * sourceCoords.x + ratio * targetCoords.x;
            newCoords.y = (1 - ratio) * sourceCoords.y + ratio * targetCoords.y;
            return newCoords;
        },

        percentInRange : function (lower, upper, target) {
            return ((target - lower) / (upper - lower)) * 100;
        },

        pointsBetweenStops: function (route, start, end) {
            return route.slice(route.indexOf(start), route.indexOf(end) + 1);
        },

        hashOfPercentDists : function (points) {
            var start = points[0];
            var routeLength = points.length;
            var end = points[routeLength - 1];
            var distanceHash = {
                0 : points[0]
            };
            var distances = new Array();
            var totalDist = 0;

            for (var x = 0; x < routeLength - 1; x++) {
                totalDist += transit.linearDist(points[x], points[x + 1]);
                distances.push(totalDist);
            }

            for (var x = 0; x < distances.length; x++) {
                distanceHash[transit.percentInRange(0, totalDist, distances[x])] = points[x + 1];
            }

            return distanceHash;
        },

        // Variant of binary search that returns enclosing elements of searchElement in array.
        enclosure : function (searchElement) {
            'use strict';

            var minIndex = 0;
            var maxIndex = this.length - 1;
            var currentIndex;
            var currentElement;

            while (minIndex <= maxIndex) {
                currentIndex = (minIndex + maxIndex) / 2 | 0;
                currentElement = this[currentIndex];

                if (currentElement < searchElement) {
                    minIndex = currentIndex + 1;
                }
                else if (currentElement > searchElement) {
                    maxIndex = currentIndex - 1;
                }
                else {
                    return currentIndex;
                }
            }

            if (searchElement > this[currentIndex]) {
                if (typeof this[currentIndex + 1] != 'undefined')
                    return [currentIndex, currentIndex + 1];
                else
                    return currentIndex;
            } else {
                if (typeof this[currentIndex - 1] !=  'undefined')
                    return [currentIndex - 1, currentIndex];
                else
                    return 0;
            }
        },

        parseTime : function (timeString, day, timezone) {
            var hms = timeString.split(':');
            hms = hms.map(function (x) { return parseInt(x, 10); });

            if (hms.length < 3)
                hms[2] = 0;

            return hms[0] * 3600 + hms[1] * 60 + hms[2] + (day - 1) * 86400 + timezone * 60;
        },

        currTime : function () {
            var t = new Date();
            return t.getHours().toString() + ":" +
                   t.getMinutes().toString() + ":" +
                   t.getSeconds().toString();
        },

        estimateCurrentPosition : function (vehicleObj, timezone) {
            var arrivals = vehicleObj.arrivals;
            var departures = vehicleObj.departures;
            var travelTimes = vehicleObj.traveltimes;
            var noOfDays = vehicleObj.days;
            var ppoints = vehicleObj.ppoints;
            var ppercents = vehicleObj.ppercents;
            var starts = vehicleObj.starts;
            var route = vehicleObj.route;
            var stops = vehicleObj.stops;
            var positions = new Array();

            var currPos = {
                "stationaryAt": "",
                "departureTime": 0,
                "leaving": "",
                "approaching": "",
                "leftTime": 0,
                "approachTime": 0,
                "currentCoords": null
            };

            var time = transit.currTime();

            for (var i = 1; i <= noOfDays + 1; i++) {
                var range = transit.enclosure.call(travelTimes, transit.parseTime(time, i, timezone) - starts);

                if (range[0] % 2 == 0 && range.length == 2) {
                    currPos.leftTime = travelTimes[range[0]];
                    currPos.approachTime = travelTimes[range[1]];
                    var leavingStop = departures[currPos.leftTime];
                    var approachingStop = arrivals[currPos.approachTime];
                    currPos.leaving = leavingStop;
                    currPos.approaching = approachingStop;

                    var timePercent = transit.percentInRange(travelTimes[range[0]], travelTimes[range[1]],
                                                             transit.parseTime(time, i, timezone) - starts);
                    var timeRange = transit.enclosure.call(ppercents, timePercent);
                    currPos.currentCoords = transit.percentDist(ppoints[ppercents[timeRange[0]]],
                                                                ppoints[ppercents[timeRange[1]]], timePercent);
                } else {
                    if (typeof range[1] != 'undefined' && range[0] != 0) {
                        var currentStop = travelTimes[range[1]];
                        currPos.stationaryAt = departures[currentStop];
                        currPos.departureTime = currentStop;
                        currPos.currentCoords = stops[currentStop];
                    }
                }

                positions.push(currPos);
            }

            return positions;
        },

        mouseOverInfo : function (name, info, stationary, departTime, l, a, lT, aT) {
            var base = "Vehicle: " + name + "\n" + info + "\n";
            if (stationary) {
                return base + "\n" + "At: " + stationary + "\n" + "Departs: " + departTime;
            } else {
                return base +
                       "Leaving: " + l + "\n" + " (" + lT + ")" +
                       "Approaching: " + a + " (" + aT + ")";
            }
        },

        main : function (localKmlFile, remoteKmlFile, jsonFile) {
            var map = transit.initMap();
            transit.overlayKml(remoteKmlFile, map);
            var routeObj = transit.routeParser(localKmlFile);
            var routeLines = routeObj.lines;
            var routePoints = routeObj.points;
            var vehicleObj = transit.vehicleParser(jsonFile);
            var timezone = vehicleObj.timezone;
            var vehicles = vehicleObj.vehicles;
            var noOfVehicles = vehicles.length;

            for (var count = 0; count < noOfVehicles; count++) {
                vehicles[count] = transit.schedule(vehicles[count], routeObj, timezone);
            }

            var transition = setInterval(
                    function() {
                        for (var count = 0; count < noOfVehicles; count++) {
                            var vehicle = vehicles[count];

                            if (typeof vehicle.markers == "undefined") {
                                vehicle.markers = new Array();
                            } else {
                                for (var i = 0; i < vehicle.markers.length; i++) {
                                    vehicle.markers[i].setMap(null);
                                }
                            }

                            var currPositions = transit.estimateCurrentPosition(vehicle, timezone);

                            for (var i = 0; i < currPositions.length; i++) {
                                var currPosition = currPositions[i];

                                if (!currPosition.currentCoords) continue;

                                var mouseOverInfo = transit.mouseOverInfo(vehicle.name, vehicle.info,
                                                                          currPosition.stationaryAt,
                                                                          currPosition.departureTime,
                                                                          currPosition.leaving,
                                                                          currPosition.approaching,
                                                                          currPosition.leftTime,
                                                                          currPosition.approachTime);
                                var currMarker = transit.initMarker(currPosition.currentCoords,
                                                                    mouseOverInfo, map);
                                currMarker.setMap(map);
                                vehicle.markers[i] = currMarker;
                            }
                        }
                    }, 0);
        },

        initialize : function (localKmlFile, remoteKmlFile, jsonFile) {
            google.maps.event.addDomListener(window, 'load',
                    function () {
                        transit.main(localKmlFile, remoteKmlFile, jsonFile);
                    });
        }
    };
})();
<commit_msg>invert lat/long because they're of the format y/x currently<commit_after>var transit = (function () {
    return {
        initMap : function () {
            var mapDet = {
                mapTypeId: google.maps.MapTypeId.ROADMAP
            };

            var map = new google.maps.Map(document.getElementById('transitMap'), mapDet);
            return map;
        },

        initMarker : function (coords, mouseoverText, map) {
            mouseoverText = (typeof mouseoverText == 'undefined') ? 'Marker' : mouseoverText;
            var markerPos = new google.maps.LatLng(coords.x, coords.y);

            var markerIcon = {
                path: google.maps.SymbolPath.CIRCLE,
                fillColor: 'red',
                fillOpacity: 0.8,
                scale: 5
            };

            var mouseoverInfo = new google.maps.InfoWindow({
                content: mouseoverText,
                map: map
            });

            var marker = {
                position: markerPos,
                icon: markerIcon
            };

            marker = new google.maps.Marker(marker);

            google.maps.event.addListener(marker, 'mouseover', function() {
            	mouseoverInfo.open(map, this);
            });

            google.maps.event.addListener(marker, 'mouseout', function() {
            	mouseoverInfo.close();
            });

            return marker;
        },

        moveMarkers : function (markerSet, interval, map) {
            interval = (typeof interval == 'undefined') ? 1000 : interval;
            var transition = setInterval(
                    function () {
                        for (var counter = 0; counter < markerSet.length; counter++) {
                            for (var i = 0; i < markerSet.length; i++) {
                                var curPos = new google.maps.LatLng(markerSet[i].coordSet[counter][0],
                                    markerSet[i].coordSet[counter][1]);
                                markerSet[i].marker.position = curPos;
                                markerSet[i].marker.setMap(map);
                            }
                        }
                    },
                    interval);
        },

        constructMarkerSet : function (markers) {
            var markerSet = new Array();
            for (var counter = 0; counter < markers.length; counter++) {
                var markerObj = transit.initMarker(markers[counter].coords[0], markers[counter].title);
                var coordList = markers[counter].coords.slice(1);

                markerSet.push({
                    marker: markerObj,
                    coordSet: coordList
                });
            }
            return markerSet;
        },

        overlayKml : function (kmlUrl, map) {
            var kmlOptions = {
                map: map
            };
            var kmlLayer = new google.maps.KmlLayer(kmlUrl, kmlOptions);
        },

        routeParser : function (xmlUrl) {
            var lines = {};
            var points = {};

            $.ajax({
                url: xmlUrl,
                dataType: 'xml',
                async: false,
                success : function (data) {
                    var xmlNode = $('Document', data);

                    xmlNode.find('Placemark > LineString > coordinates').each(function () {
                        var simPts = transit.trim($(this).text()).split(' ');
                        var grpPts = new Array();
                        var routeName = $(this).closest('Placemark').find('name').text().toLowerCase();
                        for (eachPt in simPts) {
                            var xy = transit.strip(simPts[eachPt]).split(',');
                            grpPts.push({ x: parseFloat(xy[1], 10), y: parseFloat(xy[0], 10) });
                        }
                        lines[transit.trim(routeName)] = grpPts;
                    });

                    xmlNode.find('Point').each(function () {
                        var parentTag = $(this).closest('Placemark');

                        var xy = transit.strip(parentTag.find('Point').text()).split(',');
                        points[transit.trim(parentTag.find('name').text()).toLowerCase()] = {
                            x: parseFloat(xy[1], 10),
                            y: parseFloat(xy[0], 10)
                        };
                    });
                },
                error : function (data) {
                    console.log('Error');
                }
            });

            return {
                "lines": lines,
                "points": points
            };
        },

        vehicleParser : function (jsonUrl) {
            var vehicleObj = {};

            $.ajax({
                url: jsonUrl,
                dataType: 'json',
                async: false,
                success : function (data) {
                    vehicleObj.timezone = data.timezone;
                    vehicleObj.vehicles = data.vehicles;
                },
                error : function (data) {
                    console.log('Error');
                }
            });

            return vehicleObj;
        },

        schedule : function (vehicleObj, routes, timezone) {
            var vehicleArrivals = {};
            var vehicleDepartures = {};
            var vehicleTravelTimes = new Array();
            var vehicleRoute = vehicleObj.route;
            var stopsObj = vehicleObj.stops;
            var noOfStops = vehicleObj.stops.length;
            var firstStop = stopsObj[0];
            var firstStopName = firstStop.name.toLowerCase();
            var startTime = transit.parseTime(firstStop.departure, firstStop.day, timezone);
            var vehicleStopCoords = {};
            var points = routes.points;
            var opLine = routes.lines[vehicleRoute.toLowerCase()];

            vehicleDepartures[startTime - startTime] = firstStopName;
            vehicleTravelTimes.push(startTime - startTime);
            vehicleStopCoords[firstStopName] = transit.resolvePointToLine(opLine, points[firstStopName]);

            for (var eachStop = 1; eachStop < noOfStops - 1; eachStop++) {
                var temp = stopsObj[eachStop];
                var tempName = temp.name.toLowerCase();
                var currArrivalTime = transit.parseTime(temp.arrival, temp.day, timezone) - startTime;
                var currDepartureTime = transit.parseTime(temp.departure, temp.day, timezone) - startTime;
                vehicleArrivals[currArrivalTime] = tempName;
                vehicleDepartures[currDepartureTime] = tempName;
                vehicleTravelTimes.push(currArrivalTime, currDepartureTime);
                vehicleStopCoords[tempName] = transit.resolvePointToLine(opLine, points[tempName]);
            }

            var lastStop = stopsObj[noOfStops - 1];
            var lastStopName = lastStop.name.toLowerCase();
            var endTime = transit.parseTime(lastStop.arrival, lastStop.day, timezone) - startTime;
            vehicleArrivals[endTime] = lastStopName;
            vehicleTravelTimes.push(endTime);
            vehicleStopCoords[lastStopName] = transit.resolvePointToLine(opLine, points[lastStopName]);
            var line = transit.pointsBetweenStops(opLine,
                                                  vehicleStopCoords[firstStopName],
                                                  vehicleStopCoords[lastStopName]);
            var percentStopDists = transit.hashOfPercentDists(line);

            var percentDists = new Array();
            for (var x in percentStopDists) percentDists.push(x);

            return {
                "name": vehicleObj.name,
                "info": vehicleObj.info,
                "starts": startTime,
                "route": line,
                "stops": vehicleStopCoords,
                "ppoints": percentStopDists,
                "ppercents": percentDists,
                "days": lastStop.day - firstStop.day,
                "arrivals": vehicleArrivals,
                "departures": vehicleDepartures,
                "traveltimes": vehicleTravelTimes
            };
        },

        strip : function (string) {
            return string.replace(/\s+/g, '').replace(/\n/g, '');
        },

        trim : function (string) {
            return string.replace(/^\s+|\s+$/g, '');
        },

        resolvePointToLine : function (line, point) {
            var closestDist = transit.linearDist(line[0], point);
            var currPt = line[0]
            for (var count = 1; count < line.length; count++) {
                var currDist = transit.linearDist(line[count], point);
                if (closestDist > currDist)
                    currPt = line[count];
            }

            return currPt;
        },

        // Reimplemented from http://www.movable-type.co.uk/scripts/latlong.html
        haversine : function (sourceCoords, targetCoords) {
            var R = 6371; // km

            /** Converts numeric degrees to radians */
            if (typeof(Number.prototype.toRad) === "undefined") {
              Number.prototype.toRad = function() {
                return this * Math.PI / 180;
              }
            }

            var dLat = (targetCoords.x - sourceCoords.x).toRad();
            var dLon = (targetCoords.y - sourceCoords.y).toRad();
            var lat1 = sourceCoords.x.toRad();
            var lat2 = targetCoords.x.toRad();

            var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
            Math.sin(dLon/2) * Math.sin(dLon/2) * Math.cos(lat1) * Math.cos(lat2);
            var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
            var d = R * c;
            return d;
        },

        linearDist : function (sourceCoords, targetCoords) {
            return Math.sqrt(Math.pow((targetCoords.x - sourceCoords.x), 2),
                             Math.pow((targetCoords.y - sourceCoords.y), 2));
        },

        percentDist : function (sourceCoords, targetCoords, percentage) {
            var newCoords = {};
            var ratio = percentage / 100;
            newCoords.x = (1 - ratio) * sourceCoords.x + ratio * targetCoords.x;
            newCoords.y = (1 - ratio) * sourceCoords.y + ratio * targetCoords.y;
            return newCoords;
        },

        percentInRange : function (lower, upper, target) {
            return ((target - lower) / (upper - lower)) * 100;
        },

        pointsBetweenStops: function (route, start, end) {
            return route.slice(route.indexOf(start), route.indexOf(end) + 1);
        },

        hashOfPercentDists : function (points) {
            var start = points[0];
            var routeLength = points.length;
            var end = points[routeLength - 1];
            var distanceHash = {
                0 : points[0]
            };
            var distances = new Array();
            var totalDist = 0;

            for (var x = 0; x < routeLength - 1; x++) {
                totalDist += transit.linearDist(points[x], points[x + 1]);
                distances.push(totalDist);
            }

            for (var x = 0; x < distances.length; x++) {
                distanceHash[transit.percentInRange(0, totalDist, distances[x])] = points[x + 1];
            }

            return distanceHash;
        },

        // Variant of binary search that returns enclosing elements of searchElement in array.
        enclosure : function (searchElement) {
            'use strict';

            var minIndex = 0;
            var maxIndex = this.length - 1;
            var currentIndex;
            var currentElement;

            while (minIndex <= maxIndex) {
                currentIndex = (minIndex + maxIndex) / 2 | 0;
                currentElement = this[currentIndex];

                if (currentElement < searchElement) {
                    minIndex = currentIndex + 1;
                }
                else if (currentElement > searchElement) {
                    maxIndex = currentIndex - 1;
                }
                else {
                    return currentIndex;
                }
            }

            if (searchElement > this[currentIndex]) {
                if (typeof this[currentIndex + 1] != 'undefined')
                    return [currentIndex, currentIndex + 1];
                else
                    return currentIndex;
            } else {
                if (typeof this[currentIndex - 1] !=  'undefined')
                    return [currentIndex - 1, currentIndex];
                else
                    return 0;
            }
        },

        parseTime : function (timeString, day, timezone) {
            var hms = timeString.split(':');
            hms = hms.map(function (x) { return parseInt(x, 10); });

            if (hms.length < 3)
                hms[2] = 0;

            return hms[0] * 3600 + hms[1] * 60 + hms[2] + (day - 1) * 86400 + timezone * 60;
        },

        currTime : function () {
            var t = new Date();
            return t.getHours().toString() + ":" +
                   t.getMinutes().toString() + ":" +
                   t.getSeconds().toString();
        },

        estimateCurrentPosition : function (vehicleObj, timezone) {
            var arrivals = vehicleObj.arrivals;
            var departures = vehicleObj.departures;
            var travelTimes = vehicleObj.traveltimes;
            var noOfDays = vehicleObj.days;
            var ppoints = vehicleObj.ppoints;
            var ppercents = vehicleObj.ppercents;
            var starts = vehicleObj.starts;
            var route = vehicleObj.route;
            var stops = vehicleObj.stops;
            var positions = new Array();

            var currPos = {
                "stationaryAt": "",
                "departureTime": 0,
                "leaving": "",
                "approaching": "",
                "leftTime": 0,
                "approachTime": 0,
                "currentCoords": null
            };

            var time = transit.currTime();

            for (var i = 1; i <= noOfDays + 1; i++) {
                var range = transit.enclosure.call(travelTimes, transit.parseTime(time, i, timezone) - starts);

                if (range[0] % 2 == 0 && range.length == 2) {
                    currPos.leftTime = travelTimes[range[0]];
                    currPos.approachTime = travelTimes[range[1]];
                    var leavingStop = departures[currPos.leftTime];
                    var approachingStop = arrivals[currPos.approachTime];
                    currPos.leaving = leavingStop;
                    currPos.approaching = approachingStop;

                    var timePercent = transit.percentInRange(travelTimes[range[0]], travelTimes[range[1]],
                                                             transit.parseTime(time, i, timezone) - starts);
                    var timeRange = transit.enclosure.call(ppercents, timePercent);
                    currPos.currentCoords = transit.percentDist(ppoints[ppercents[timeRange[0]]],
                                                                ppoints[ppercents[timeRange[1]]], timePercent);
                } else {
                    if (typeof range[1] != 'undefined' && range[0] != 0) {
                        var currentStop = travelTimes[range[1]];
                        currPos.stationaryAt = departures[currentStop];
                        currPos.departureTime = currentStop;
                        currPos.currentCoords = stops[currentStop];
                    }
                }

                positions.push(currPos);
            }

            return positions;
        },

        mouseOverInfo : function (name, info, stationary, departTime, l, a, lT, aT) {
            var base = "Vehicle: " + name + "\n" + info + "\n";
            if (stationary) {
                return base + "\n" + "At: " + stationary + "\n" + "Departs: " + departTime;
            } else {
                return base +
                       "Leaving: " + l + "\n" + " (" + lT + ")" +
                       "Approaching: " + a + " (" + aT + ")";
            }
        },

        main : function (localKmlFile, remoteKmlFile, jsonFile) {
            var map = transit.initMap();
            transit.overlayKml(remoteKmlFile, map);
            var routeObj = transit.routeParser(localKmlFile);
            var routeLines = routeObj.lines;
            var routePoints = routeObj.points;
            var vehicleObj = transit.vehicleParser(jsonFile);
            var timezone = vehicleObj.timezone;
            var vehicles = vehicleObj.vehicles;
            var noOfVehicles = vehicles.length;

            for (var count = 0; count < noOfVehicles; count++) {
                vehicles[count] = transit.schedule(vehicles[count], routeObj, timezone);
            }

            var transition = setInterval(
                    function() {
                        for (var count = 0; count < noOfVehicles; count++) {
                            var vehicle = vehicles[count];

                            if (typeof vehicle.markers == "undefined") {
                                vehicle.markers = new Array();
                            } else {
                                for (var i = 0; i < vehicle.markers.length; i++) {
                                    vehicle.markers[i].setMap(null);
                                }
                            }

                            var currPositions = transit.estimateCurrentPosition(vehicle, timezone);

                            for (var i = 0; i < currPositions.length; i++) {
                                var currPosition = currPositions[i];

                                if (!currPosition.currentCoords) continue;

                                var mouseOverInfo = transit.mouseOverInfo(vehicle.name, vehicle.info,
                                                                          currPosition.stationaryAt,
                                                                          currPosition.departureTime,
                                                                          currPosition.leaving,
                                                                          currPosition.approaching,
                                                                          currPosition.leftTime,
                                                                          currPosition.approachTime);
                                var currMarker = transit.initMarker(currPosition.currentCoords,
                                                                    mouseOverInfo, map);
                                currMarker.setMap(map);
                                vehicle.markers[i] = currMarker;
                            }
                        }
                    }, 0);
        },

        initialize : function (localKmlFile, remoteKmlFile, jsonFile) {
            google.maps.event.addDomListener(window, 'load',
                    function () {
                        transit.main(localKmlFile, remoteKmlFile, jsonFile);
                    });
        }
    };
})();
<|endoftext|>