<commit_before>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

var dragComponent = null;
var dragitem = null;
var currentView = null;
var currentItem = null
var startPos = null;

function playlistNameValidate(parm,val) {
    if (parm == "") return true;
    for (var i=0; i<parm.length; i++) {
        if (val.indexOf(parm.charAt(i),0) != -1) return false;
    }
    return true;
}

function startDrag(mouse,view,item) {
    if (view == null || item == null)
        return;

    if (dragitem != null) {
        dragitem.destroy();
        dragitem = null;
    }

     dragComponent = view.delegate;

    currentView = view;
    currentItem = item;
    startPos = item.mapToItem(scene,mouse.x, mouse.y);

    if (dragComponent.status == Component.Loading) {
        component.statusChanged.connect(createItem);
    }else{
        createItem();
    }
}

// this function will return type SONG(2),ARTIST(3),ALBUM(4) or PLAYLIST(5) from MediaItem
// depending on the input type, which is one of the ModelType
// we can't access MediaItem from here, so hardcoded the enum value
function convertListType(type) {
    switch (type) {
    case MusicListModel.ListofSongs:
            return 2;

    case MusicListModel.ListofAlbums:
            return 4;

    case MusicListModel.ListofArtists:
            return 3;

    case MusicListModel.ListofPlaylists:
            return 5;

    case MusicListModel.ListofAlbumsForArtist:
            return 4;

    case MusicListModel.ListofSongsForAlbum:
            return 2;

    case MusicListModel.ListofSongsForArtist:
            return 2;

    case MusicListModel.ListofRecentlyPlayed:
            // special case
            return currentItem.mtype;

    case MusicListModel.MusicPlaylist:
            return 5;

    default:
            return -1;
    }
}

function createItem() {
    dragitem = dragComponent.createObject(scene);
    // set dragitem position:

    dragitem.x = startPos.x;
    dragitem.y = startPos.y;

    dragitem.mtitle = currentItem.mtitle;
    dragitem.mthumburi = currentItem.mthumburi;
    dragitem.mitemid = currentItem.mitemid;
    dragitem.mitemtype = currentItem.mitemtype;
    dragitem.opacity = 0.8;
    dragitem.mcount = currentItem.mcount;
    dragitem.martist = currentItem.martist;
}

// return true if the point is in item's area,
// the point should be in the item's coordinate system.
function itemContainsPoint(item, point) {
    if ( point.x >=0 && point.x < item.width
         && point.y >= 0 && point.y < item.height) {
        return true;
    }
    return false;
}

function moveDragItem(mouse,item) {

    if (dragitem == null)
        return;

    var pos = item.mapToItem(scene,mouse.x, mouse.y);
    dragitem.x = pos.x;
    dragitem.y = pos.y;

    if (sideContentStrip.activeContent.tabs) {
        for (var i = 0;  i < sideContentStrip.activeContent.tabs.length -1; i++) {
            var it = sideContentStrip.activeContent.tabs[i];
            var pt = item.mapToItem(it,mouse.x, mouse.y);
            if (itemContainsPoint(it,pt)) {
                sideContentStrip.activeContent.selectTabAtIndex(i);
                sideContentStrip.activeContent.open();
                return;
            }
        }

        // specific code for landingscreen side content
        if (sideContentStrip.activeContent.currentTabIndex == 1) {
            var view = sideContentStrip.activeContent.currentTab.playlistList;
            var map = item.mapToItem(view, mouse.x, mouse.y);
            var targetIndex = view.indexAt(map.x  , map.y + view.contentY);
            if (targetIndex != -1) {
                view.currentIndex = targetIndex;

               view.highlightItem.opacity = 0.4;
            }else {
               view.highlightItem.opacity = 0;
            }
        }
    }

}

function endDrag(mouse,item) {
    if (!dragitem) {
        return;
    }

    // check if dropped at now playing button,
    // if yes, add to now playing list
    var dropPos = item.mapToItem(npRect,mouse.x,mouse.y);
    if (dropPos.x > 0 && dropPos.x < npRect.width
        && dropPos.y > 0 && dropPos.y < npRect.height)
    {
        addToPlayqueue(item);
    }else {
        if (sideContentStrip.activeContent.currentTabIndex == 1) {
            var view = sideContentStrip.activeContent.currentTab.playlistList;
            var map = item.mapToItem(view, mouse.x, mouse.y) ;
            var targetIndex = view.indexAt(map.x  , map.y + view.contentY);
            if (targetIndex != -1) {
                appendItemToPlaylist(item,view.currentItem);
            }
            view.highlightItem.opacity = 0;
        }
    }

    if (dragitem != null) {
        dragitem.destroy(dragitem.animation == true? 500: 0);
        dragitem = null;
        currentView = null;
        currentItem = null;
        startPos = null;
        dragComponent == null
    }else {
        return;
    }
    updateNowNextPlaying();
}

function addToPlayqueue(item) {
    playqueueModel.addItems(item.mitemid);
    editorModel.setViewed(item.mitemid);
    updateNowNextPlaying();
}

function addMultipleToPlayqueue(list) {
    playqueueModel.addItems(list.getSelectedIDs());
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function removeFromPlayqueue(item) {
    if(playqueueView.currentIndex == playqueueModel.itemIndex(item.mitemid))
    {
        audio.stop();
    }
    playqueueModel.removeItems(item.mitemid);
    updateNowNextPlaying();
}

function removeMultipleFromPlayqueue(list) {
    var ids = list.getSelectedIDs();
    var i;
    for (i in ids) {
        if(playqueueView.currentIndex == playqueueModel.itemIndex(ids[i]))
        {
            audio.stop();
            break;
        }
    }
    playqueueModel.removeItems(ids);
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function addToPlayqueueAndPlay(item)
{
    addToPlayqueue(item);
    playqueueView.currentIndex = playqueueModel.itemIndex(item.mitemid);
    console.log("Item Index is: " + playqueueModel.itemIndex(item.mitemid) + " " + item.mtitle);
    playNewSong();
    updateNowNextPlaying();
}

function addMultipleToPlayqueueAndPlay(list)
{
    var ids = list.getSelectedIDs();
    playqueueModel.addItems(ids);
    editorModel.setViewed(ids[0]);
    playqueueView.currentIndex = playqueueModel.itemIndex(ids[0]);
    playNewSong();
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function changeItemFavorite(item, val) {
    editorModel.setFavorite(item.mitemid,val);
}

function changeMultipleItemFavorite(list, val) {
    var ids = list.getSelectedIDs();
    var i;
    for (i in ids) {
        editorModel.setFavorite(ids[i], val);
    }
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function play()
{
    if (audio.paused ) {
        audio.play();
    } else {
        return playNewSong();
    }
    return true;
}

function playNewSong() {
    audio.stop();

    // if there are no songs or the index is out of range, do nothing
    if((playqueueView.count <= 0)||
       (playqueueView.currentIndex >= playqueueView.count))
    {
        return false;
    }

    if (playqueueView.currentIndex == -1)
        playqueueView.currentIndex = 0;

    var item = playqueueView.currentItem;

    if (item == undefined){
        return false;
    }

    toolbar.trackName = item.mtitle;
    toolbar.artistName = item.martist;

    audio.source = item.muri;
    audio.playing = true;
    return true;
}

function playNextSong() {
    if (shuffle) {
        playqueueView.currentIndex = playqueueModel.shuffleIndex(0);
        playqueueModel.shuffleIncrement();
    }else {
        if (playqueueView.currentIndex < (playqueueView.count -1))
        {
            playqueueView.currentIndex++;
        }
        else
        {
            if (loop){
                playqueueView.currentIndex = 0;
            }else{
                playqueueView.currentIndex = playqueueView.count;
                stop();
                return;
            }
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function playPrevSong() {
    if (shuffle) {
        playqueueView.currentIndex = playqueueModel.shuffleIndex(0);
        playqueueModel.shuffleIncrement();
    }else {
        if (playqueueView.currentIndex == 0)
        {
            if (loop) {
                playqueueView.currentIndex = playqueueView.count - 1;
            }else {
                stop();
                return;
            }
        }
        else
        {
            playqueueView.currentIndex--;
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function updateNowNextPlaying()
{
    if (dbusControl.state == "stopped") {
        dbusControl.nextItem1 = -1;
        dbusControl.nextItem2 = -1;
    } else if (shuffle) {
        dbusControl.nextItem1 = playqueueModel.shuffleIndex(1);
        dbusControl.nextItem2 = playqueueModel.shuffleIndex(2);
    } else  if (playqueueView.currentIndex == 0) {
        if (playqueueView.count == 1) {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        } else if (playqueueView.count == 2) {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = -1;
        } else {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = 2;
        }
    } else {
        if (playqueueView.currentIndex+1 < playqueueView.count) {
            dbusControl.nextItem1 = playqueueView.currentIndex+1;

            if (dbusControl.nextItem1+1 < playqueueView.count) {
                dbusControl.nextItem2 = dbusControl.nextItem1+1;
            } else if (loop && playqueueView.count > 2) {
                dbusControl.nextItem2 = 0
            } else {
                dbusControl.nextItem2 = -1;
            }

        } else if (loop && playqueueView.count > 1) {
            dbusControl.nextItem1 = 0;
            if (playqueueView.count > 2) {
                dbusControl.nextItem2 = 1;
            } else {
                dbusControl.nextItem2 = -1
            }
        } else {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        }
    }
    dbusControl.updateNowNextTracks();

}

function pause()
{
    audio.pause()
}

function stop()
{
    audio.stop();
}

function formatLength(time)
{
    var val = parseInt(time);
    var dec = parseInt((time-val)*10);
    return (dec == 0)?val:(val + "." + dec)
}

function formatTime(time)
{
    var min = parseInt(time/60);
    var sec = parseInt(time%60);
    return min+ (sec<10 ? ":0":":") + sec
}

function openItemInDetailView(fromPage, item)
{
    switch(item.mitemtype) {
    case 2:
        // type is song
        // no detail view
        break;
    case 3:
        // type is artist
        fromPage.addApplicationPage(artistDetailViewContent);
        labelArtist = item.mtitle;
        break;
    case 4:
        // type is album
        thumbnailUri = item.mthumburi;
        fromPage.addApplicationPage(albumDetailViewContent);
        labelAlbum = item.mtitle;
        albumLength = item.mlength;
        break;
    case 5:
        // type is playlist
        fromPage.addApplicationPage(playlistDetailViewContent);
        thumbnailUri = item.mthumburi;
        labelPlaylist = item.mtitle;
        labelPlaylistURN = item.murn;
        break;
    default:
        break;
    }
}

function appendItemToPlaylist(item, playlistItem)
{
    miscModel.type = MusicListModel.MusicPlaylist;
    miscModel.clear();
    miscModel.playlist = playlistItem.mtitle;
    miscModel.addItems(item.mitemid);
    miscModel.savePlaylist(playlistItem.mtitle);
}
<commit_msg>fixed the issue of the song ending the the pause button not returning to play<commit_after>/*
 * Copyright 2011 Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 */

var dragComponent = null;
var dragitem = null;
var currentView = null;
var currentItem = null
var startPos = null;

function playlistNameValidate(parm,val) {
    if (parm == "") return true;
    for (var i=0; i<parm.length; i++) {
        if (val.indexOf(parm.charAt(i),0) != -1) return false;
    }
    return true;
}

function startDrag(mouse,view,item) {
    if (view == null || item == null)
        return;

    if (dragitem != null) {
        dragitem.destroy();
        dragitem = null;
    }

     dragComponent = view.delegate;

    currentView = view;
    currentItem = item;
    startPos = item.mapToItem(scene,mouse.x, mouse.y);

    if (dragComponent.status == Component.Loading) {
        component.statusChanged.connect(createItem);
    }else{
        createItem();
    }
}

// this function will return type SONG(2),ARTIST(3),ALBUM(4) or PLAYLIST(5) from MediaItem
// depending on the input type, which is one of the ModelType
// we can't access MediaItem from here, so hardcoded the enum value
function convertListType(type) {
    switch (type) {
    case MusicListModel.ListofSongs:
            return 2;

    case MusicListModel.ListofAlbums:
            return 4;

    case MusicListModel.ListofArtists:
            return 3;

    case MusicListModel.ListofPlaylists:
            return 5;

    case MusicListModel.ListofAlbumsForArtist:
            return 4;

    case MusicListModel.ListofSongsForAlbum:
            return 2;

    case MusicListModel.ListofSongsForArtist:
            return 2;

    case MusicListModel.ListofRecentlyPlayed:
            // special case
            return currentItem.mtype;

    case MusicListModel.MusicPlaylist:
            return 5;

    default:
            return -1;
    }
}

function createItem() {
    dragitem = dragComponent.createObject(scene);
    // set dragitem position:

    dragitem.x = startPos.x;
    dragitem.y = startPos.y;

    dragitem.mtitle = currentItem.mtitle;
    dragitem.mthumburi = currentItem.mthumburi;
    dragitem.mitemid = currentItem.mitemid;
    dragitem.mitemtype = currentItem.mitemtype;
    dragitem.opacity = 0.8;
    dragitem.mcount = currentItem.mcount;
    dragitem.martist = currentItem.martist;
}

// return true if the point is in item's area,
// the point should be in the item's coordinate system.
function itemContainsPoint(item, point) {
    if ( point.x >=0 && point.x < item.width
         && point.y >= 0 && point.y < item.height) {
        return true;
    }
    return false;
}

function moveDragItem(mouse,item) {

    if (dragitem == null)
        return;

    var pos = item.mapToItem(scene,mouse.x, mouse.y);
    dragitem.x = pos.x;
    dragitem.y = pos.y;

    if (sideContentStrip.activeContent.tabs) {
        for (var i = 0;  i < sideContentStrip.activeContent.tabs.length -1; i++) {
            var it = sideContentStrip.activeContent.tabs[i];
            var pt = item.mapToItem(it,mouse.x, mouse.y);
            if (itemContainsPoint(it,pt)) {
                sideContentStrip.activeContent.selectTabAtIndex(i);
                sideContentStrip.activeContent.open();
                return;
            }
        }

        // specific code for landingscreen side content
        if (sideContentStrip.activeContent.currentTabIndex == 1) {
            var view = sideContentStrip.activeContent.currentTab.playlistList;
            var map = item.mapToItem(view, mouse.x, mouse.y);
            var targetIndex = view.indexAt(map.x  , map.y + view.contentY);
            if (targetIndex != -1) {
                view.currentIndex = targetIndex;

               view.highlightItem.opacity = 0.4;
            }else {
               view.highlightItem.opacity = 0;
            }
        }
    }

}

function endDrag(mouse,item) {
    if (!dragitem) {
        return;
    }

    // check if dropped at now playing button,
    // if yes, add to now playing list
    var dropPos = item.mapToItem(npRect,mouse.x,mouse.y);
    if (dropPos.x > 0 && dropPos.x < npRect.width
        && dropPos.y > 0 && dropPos.y < npRect.height)
    {
        addToPlayqueue(item);
    }else {
        if (sideContentStrip.activeContent.currentTabIndex == 1) {
            var view = sideContentStrip.activeContent.currentTab.playlistList;
            var map = item.mapToItem(view, mouse.x, mouse.y) ;
            var targetIndex = view.indexAt(map.x  , map.y + view.contentY);
            if (targetIndex != -1) {
                appendItemToPlaylist(item,view.currentItem);
            }
            view.highlightItem.opacity = 0;
        }
    }

    if (dragitem != null) {
        dragitem.destroy(dragitem.animation == true? 500: 0);
        dragitem = null;
        currentView = null;
        currentItem = null;
        startPos = null;
        dragComponent == null
    }else {
        return;
    }
    updateNowNextPlaying();
}

function addToPlayqueue(item) {
    playqueueModel.addItems(item.mitemid);
    editorModel.setViewed(item.mitemid);
    updateNowNextPlaying();
}

function addMultipleToPlayqueue(list) {
    playqueueModel.addItems(list.getSelectedIDs());
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function removeFromPlayqueue(item) {
    if(playqueueView.currentIndex == playqueueModel.itemIndex(item.mitemid))
    {
        audio.stop();
    }
    playqueueModel.removeItems(item.mitemid);
    updateNowNextPlaying();
}

function removeMultipleFromPlayqueue(list) {
    var ids = list.getSelectedIDs();
    var i;
    for (i in ids) {
        if(playqueueView.currentIndex == playqueueModel.itemIndex(ids[i]))
        {
            audio.stop();
            break;
        }
    }
    playqueueModel.removeItems(ids);
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function addToPlayqueueAndPlay(item)
{
    addToPlayqueue(item);
    playqueueView.currentIndex = playqueueModel.itemIndex(item.mitemid);
    console.log("Item Index is: " + playqueueModel.itemIndex(item.mitemid) + " " + item.mtitle);
    playNewSong();
    updateNowNextPlaying();
}

function addMultipleToPlayqueueAndPlay(list)
{
    var ids = list.getSelectedIDs();
    playqueueModel.addItems(ids);
    editorModel.setViewed(ids[0]);
    playqueueView.currentIndex = playqueueModel.itemIndex(ids[0]);
    playNewSong();
    updateNowNextPlaying();
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function changeItemFavorite(item, val) {
    editorModel.setFavorite(item.mitemid,val);
}

function changeMultipleItemFavorite(list, val) {
    var ids = list.getSelectedIDs();
    var i;
    for (i in ids) {
        editorModel.setFavorite(ids[i], val);
    }
    list.clearSelected();
    multibar.sharing.clearItems();
    multiSelectMode = false;
}

function play()
{
    if (audio.paused ) {
        audio.play();
    } else {
        return playNewSong();
    }
    return true;
}

function playNewSong() {
    audio.stop();

    // if there are no songs or the index is out of range, do nothing
    if((playqueueView.count <= 0)||
       (playqueueView.currentIndex >= playqueueView.count))
    {
        return false;
    }

    if (playqueueView.currentIndex == -1)
        playqueueView.currentIndex = 0;

    var item = playqueueView.currentItem;

    if (item == undefined){
        return false;
    }

    toolbar.trackName = item.mtitle;
    toolbar.artistName = item.martist;

    audio.source = item.muri;
    audio.playing = true;
    return true;
}

function playNextSong() {
    if (shuffle) {
        playqueueView.currentIndex = playqueueModel.shuffleIndex(0);
        playqueueModel.shuffleIncrement();
    }else {
        if (playqueueView.currentIndex < (playqueueView.count -1))
        {
            playqueueView.currentIndex++;
        }
        else
        {
            if (loop){
                playqueueView.currentIndex = 0;
            }else{
                stop();
                return;
            }
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function playPrevSong() {
    if (shuffle) {
        playqueueView.currentIndex = playqueueModel.shuffleIndex(0);
        playqueueModel.shuffleIncrement();
    }else {
        if (playqueueView.currentIndex == 0)
        {
            if (loop) {
                playqueueView.currentIndex = playqueueView.count - 1;
            }else {
                stop();
                return;
            }
        }
        else
        {
            playqueueView.currentIndex--;
        }
    }
    audio.source = "";
    playNewSong();
    updateNowNextPlaying();
}

function updateNowNextPlaying()
{
    if (dbusControl.state == "stopped") {
        dbusControl.nextItem1 = -1;
        dbusControl.nextItem2 = -1;
    } else if (shuffle) {
        dbusControl.nextItem1 = playqueueModel.shuffleIndex(1);
        dbusControl.nextItem2 = playqueueModel.shuffleIndex(2);
    } else  if (playqueueView.currentIndex == 0) {
        if (playqueueView.count == 1) {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        } else if (playqueueView.count == 2) {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = -1;
        } else {
            dbusControl.nextItem1 = 1;
            dbusControl.nextItem2 = 2;
        }
    } else {
        if (playqueueView.currentIndex+1 < playqueueView.count) {
            dbusControl.nextItem1 = playqueueView.currentIndex+1;

            if (dbusControl.nextItem1+1 < playqueueView.count) {
                dbusControl.nextItem2 = dbusControl.nextItem1+1;
            } else if (loop && playqueueView.count > 2) {
                dbusControl.nextItem2 = 0
            } else {
                dbusControl.nextItem2 = -1;
            }

        } else if (loop && playqueueView.count > 1) {
            dbusControl.nextItem1 = 0;
            if (playqueueView.count > 2) {
                dbusControl.nextItem2 = 1;
            } else {
                dbusControl.nextItem2 = -1
            }
        } else {
            dbusControl.nextItem1 = -1;
            dbusControl.nextItem2 = -1;
        }
    }
    dbusControl.updateNowNextTracks();

}

function pause()
{
    audio.pause()
}

function stop()
{
    audio.stop();
}

function formatLength(time)
{
    var val = parseInt(time);
    var dec = parseInt((time-val)*10);
    return (dec == 0)?val:(val + "." + dec)
}

function formatTime(time)
{
    var min = parseInt(time/60);
    var sec = parseInt(time%60);
    return min+ (sec<10 ? ":0":":") + sec
}

function openItemInDetailView(fromPage, item)
{
    switch(item.mitemtype) {
    case 2:
        // type is song
        // no detail view
        break;
    case 3:
        // type is artist
        fromPage.addApplicationPage(artistDetailViewContent);
        labelArtist = item.mtitle;
        break;
    case 4:
        // type is album
        thumbnailUri = item.mthumburi;
        fromPage.addApplicationPage(albumDetailViewContent);
        labelAlbum = item.mtitle;
        albumLength = item.mlength;
        break;
    case 5:
        // type is playlist
        fromPage.addApplicationPage(playlistDetailViewContent);
        thumbnailUri = item.mthumburi;
        labelPlaylist = item.mtitle;
        labelPlaylistURN = item.murn;
        break;
    default:
        break;
    }
}

function appendItemToPlaylist(item, playlistItem)
{
    miscModel.type = MusicListModel.MusicPlaylist;
    miscModel.clear();
    miscModel.playlist = playlistItem.mtitle;
    miscModel.addItems(item.mitemid);
    miscModel.savePlaylist(playlistItem.mtitle);
}
<|endoftext|>


<commit_before>const TeeworldsConnection = require('./teeworlds-connection');
const protocol = require('./protocol');
const { chunk } = require('./utils');

class TeeworldsServer {

  /**
   * Teeworlds server class constructor
   *
   * @param  {String} host Server FQDN or IP
   * @param  {Integer} port Server port
   */
  constructor(host, port) {
    if (!host) throw new Error('Undefined host');
    if (!port) throw new Error('Undefined port');

    this.client = new TeeworldsConnection(host, parseInt(port));
  }

  /**
   * Get server information
   *
   * @param  {Integer} timeout Timeout
   * @return {Object}          Server information
   */
  getInfo(timeout = 30000) {
    return this.client.request(protocol.SERVERBROWSE_GETINFO, protocol.SERVERBROWSE_INFO, timeout).then((response) => {
      return this.parseResponse(response);
    });
  }

  /**
   * Ping server
   *
   * @param  {Integer} timeout Timeout
   * @return {Integer}         Ping time in milliseconds
   */
  ping(timeout = 30000) {
    const start = new Date();
    return this.sendRequest(timeout).then(() => {
      const end = new Date();
      return end - start;
    });
  }

  parseResponse(response) {
    const data = response.map((buffer) => buffer.toString());

    let players = chunk(data.slice(9, -1), 5).map((player) => {
      return {
        name: player[0],
        clan: player[1] == '' ? null : player[1],
        flag: protocol.FLAGS[player[2]] ? protocol.FLAGS[player[2]] : null,
        score: parseInt(player[3]),
        spectator: parseInt(player[4]) == 0 ? true : false,
      };
    });

    return {
      host: this.client.host,
      port: this.client.port,
      version: data[0],
      name: data[1],
      map: data[2],
      gametype: data[3],
      online: parseInt(data[5]),
      maxOnline: parseInt(data[6]),
      spectators: parseInt(data[7]) - parseInt(data[5]),
      players: players,
    };
  }

}

module.exports = TeeworldsServer;
<commit_msg>Fix ping<commit_after>const TeeworldsConnection = require('./teeworlds-connection');
const protocol = require('./protocol');
const { chunk } = require('./utils');

class TeeworldsServer {

  /**
   * Teeworlds server class constructor
   *
   * @param  {String} host Server FQDN or IP
   * @param  {Integer} port Server port
   */
  constructor(host, port) {
    if (!host) throw new Error('Undefined host');
    if (!port) throw new Error('Undefined port');

    this.client = new TeeworldsConnection(host, parseInt(port));
  }

  /**
   * Get server information
   *
   * @param  {Integer} timeout Timeout
   * @return {Object}          Server information
   */
  getInfo(timeout = 30000) {
    return this.client.request(protocol.SERVERBROWSE_GETINFO, protocol.SERVERBROWSE_INFO, timeout).then((response) => {
      return this.parseResponse(response);
    });
  }

  /**
   * Ping server
   *
   * @param  {Integer} timeout Timeout
   * @return {Integer}         Ping time in milliseconds
   */
  ping(timeout = 30000) {
    const start = new Date();
    return this.getInfo(timeout).then(() => {
      const end = new Date();
      return end - start;
    });
  }

  parseResponse(response) {
    const data = response.map((buffer) => buffer.toString());

    let players = chunk(data.slice(9, -1), 5).map((player) => {
      return {
        name: player[0],
        clan: player[1] == '' ? null : player[1],
        flag: protocol.FLAGS[player[2]] ? protocol.FLAGS[player[2]] : null,
        score: parseInt(player[3]),
        spectator: parseInt(player[4]) == 0 ? true : false,
      };
    });

    return {
      host: this.client.host,
      port: this.client.port,
      version: data[0],
      name: data[1],
      map: data[2],
      gametype: data[3],
      online: parseInt(data[5]),
      maxOnline: parseInt(data[6]),
      spectators: parseInt(data[7]) - parseInt(data[5]),
      players: players,
    };
  }

}

module.exports = TeeworldsServer;
<|endoftext|>


<commit_before>var settingsText;
var settingsText__difficulty;
var settingsText__sound;
var settingsText__colour;

function mainMenu() {
    mainMenu = this;
    DontPanic.background = DontPanic.game.add.image(0, -40, 'home_background');
    DontPanic.startButton = DontPanic.game.add.button(DontPanic.game.world.centerX, DontPanic.game.world.centerY - 120, 'startButton', startGame, this);
    DontPanic.startButton.anchor.set(0.5);
    DontPanic.settingsButton = DontPanic.game.add.button(DontPanic.game.world.centerX, DontPanic.game.world.centerY - 60, 'settingsButton', settingsMenu, this);
    DontPanic.settingsButton.anchor.set(0.5);
}

function settingsMenu() {
    DontPanic.game.world.removeAll(); //this might not be a good idea as all game assets will need to be loaded back in again?
    DontPanic.game.add.image(0, 0, 'background1');
    settingsText = DontPanic.game.add.group();

    const currentSettings = getCurrentSettings();

    addText(DontPanic.game.world.centerX, 75, "Settings", config.style.fontSize_title, false, "", false);

    settingsText__difficulty = DontPanic.game.add.group();
    addText(DontPanic.game.world.centerX, 175, "Difficulty", config.style.fontSize_heading);
    addText(DontPanic.game.world.centerX * 0.75, 220, "Easy", config.style.fontSize_default,  true, "difficulty", currentSettings.easy);
    addText(DontPanic.game.world.centerX * 1.25, 220, "Hard", config.style.fontSize_default,  true, "difficulty", !currentSettings.easy);

    settingsText__sound = DontPanic.game.add.group();
    addText(DontPanic.game.world.centerX, 290, "Sound", config.style.fontSize_heading);
    addText(DontPanic.game.world.centerX * 0.75, 335, "On", config.style.fontSize_default, true, "sound", currentSettings.soundOn);
    addText(DontPanic.game.world.centerX * 1.25, 335, "Off", config.style.fontSize_default,  true, "sound", !currentSettings.soundOn);

    settingsText__colour = DontPanic.game.add.group();
    addText(DontPanic.game.world.centerX, 405, "Ship Colour", config.style.fontSize_heading);
    addText(DontPanic.game.world.centerX * 0.75, 450, "Red", config.style.fontSize_default, true, "colour", currentSettings.red);
    addText(DontPanic.game.world.centerX * 1.25, 450, "Blue", config.style.fontSize_default, true, "colour", !currentSettings.red);

    addText(DontPanic.game.world.centerX, 550, "Back", config.style.fontSize_default, true, "back");

    settingsText.add(settingsText__difficulty);
    settingsText.add(settingsText__sound);
    settingsText.add(settingsText__colour);
}

function addText(x, y, string, size, clickevent, category, selected) {
  var textOb = DontPanic.game.add.text(x, y, string, {
    font: `${size} ${config.style.font}`,
  });
  textOb.anchor.setTo(0.5);
  textOb.align = 'center';
  textOb.fill = config.style.textColour;
  textOb.fontSize = size;
  textOb.padding.set(16, 16);
  textOb.inputEnabled = true;
  addCategorySpecifics(textOb, category);
  if (selected) {
    colourText(textOb);
  }
}

function addCategorySpecifics(textOb, category) {
  switch (category) {
    case "difficulty":
      settingsText__difficulty.add(textOb);
      textOb.events.onInputDown.add(difficultyListener, this);
      textOb.input.useHandCursor = true;
      break;
    case "sound":
      settingsText__sound.add(textOb);
      textOb.events.onInputDown.add(soundListener, this);
      textOb.input.useHandCursor = true;
      break;
    case "colour":
      settingsText__colour.add(textOb);
      textOb.events.onInputDown.add(colourListener, this);
      textOb.input.useHandCursor = true;
      break;
    case "back":
      textOb.events.onInputDown.add(mainMenu, this);
      textOb.input.useHandCursor = true;
      break;
    default: ;
  }
}

function getCurrentSettings() {
  const currentSettings = {};
  currentSettings["easy"] = (config.currentLevel == "easy") ?  true : false;
  currentSettings["soundOn"] = config.soundOn;
  currentSettings["red"] = (config.playerColour == "red") ?  true : false;
  return currentSettings;
}

function difficultyListener(input) {
  let previousSelection = config.currentLevel;
  config.currentLevel = input["_text"].toLowerCase();
  if (config.currentLevel != previousSelection) {
    for (var i = 0; i < settingsText__difficulty.children.length; i++) {
      colourText(settingsText__difficulty.children[i]);
    }
  }
  getCurrentSettings();
}

function soundListener(input) {
  let previousSelection = config.soundOn; //true or false
  config.soundOn = (input["_text"].toLowerCase() == "on") ?  true : false;
  if (config.soundOn != previousSelection) {
    for (var i = 0; i < settingsText__sound.children.length; i++) {
      colourText(settingsText__sound.children[i]);
    }
  }
  getCurrentSettings();
}

function colourListener(input) {
  let previousSelection = config.playerColour;
  config.playerColour = input["_text"].toLowerCase();
  if (config.playerColour != previousSelection) {
    for (var i = 0; i < settingsText__colour.children.length; i++) {
      colourText(settingsText__colour.children[i]);
    }
  }
  getCurrentSettings();
}

function colourText(text) {
  if (text['style']['fill'] == config.style.textColour_highlight) {
    text.fill = config.style.textColour;
    text.strokeThickness = 0;
  } else {
    text.fill = config.style.textColour_highlight;
    text.stroke = config.style.textColour_highlightOutline;
    text.strokeThickness = 3;
  }
}

function playAgainMenu() {
  DontPanic.game.gameOver.destroy();
  DontPanic.game.camera.resetFX();
  const restartButton = DontPanic.game.add.button(DontPanic.game.world.centerX, DontPanic.game.world.centerY, 'playAgainButton', startGame, this);
  restartButton.anchor.set(0.5);
  const settingsButton = DontPanic.game.add.button(DontPanic.game.world.centerX, DontPanic.game.world.centerY + 100, 'settingsButton', settingsMenu, this);
  settingsButton.anchor.set(0.5);
  if (DontPanic.newBestScore) {
    const bestDistanceText = addText(DontPanic.game.world.centerX, 190, `New Best Distance!!\n${DontPanic.bestDistance}`, config.style.fontSize_bestDistance);
  } else {
    const bestDistanceText = addText(DontPanic.game.world.centerX, 190, `Best Distance: ${DontPanic.bestDistance}`, config.style.fontSize_bestDistance);
  }
}
<commit_msg>working pause menu<commit_after>var settingsText;
var settingsText__difficulty;
var settingsText__sound;
var settingsText__colour;
var pauseCalledPreviously = false;
let pausedText;

function mainMenu() {
    DontPanic.background = DontPanic.game.add.image(0, -40, 'home_background');
    DontPanic.startButton = DontPanic.game.add.button(DontPanic.game.world.centerX, DontPanic.game.world.centerY - 120, 'startButton', startGame, this);
    DontPanic.startButton.anchor.set(0.5);
    DontPanic.settingsButton = DontPanic.game.add.button(DontPanic.game.world.centerX, DontPanic.game.world.centerY - 60, 'settingsButton', settingsMenu, this);
    DontPanic.settingsButton.anchor.set(0.5);
}

function settingsMenu() {
    DontPanic.game.world.removeAll(); //this might not be a good idea as all game assets will need to be loaded back in again?
    DontPanic.game.add.image(0, 0, 'background1');
    settingsText = DontPanic.game.add.group();

    const currentSettings = getCurrentSettings();

    addText(DontPanic.game.world.centerX, 75, "Settings", config.style.fontSize_title, false, "", false);

    settingsText__difficulty = DontPanic.game.add.group();
    addText(DontPanic.game.world.centerX, 175, "Difficulty", config.style.fontSize_heading);
    addText(DontPanic.game.world.centerX * 0.75, 220, "Easy", config.style.fontSize_default,  true, "difficulty", currentSettings.easy);
    addText(DontPanic.game.world.centerX * 1.25, 220, "Hard", config.style.fontSize_default,  true, "difficulty", !currentSettings.easy);

    settingsText__sound = DontPanic.game.add.group();
    addText(DontPanic.game.world.centerX, 290, "Sound", config.style.fontSize_heading);
    addText(DontPanic.game.world.centerX * 0.75, 335, "On", config.style.fontSize_default, true, "sound", currentSettings.soundOn);
    addText(DontPanic.game.world.centerX * 1.25, 335, "Off", config.style.fontSize_default,  true, "sound", !currentSettings.soundOn);

    settingsText__colour = DontPanic.game.add.group();
    addText(DontPanic.game.world.centerX, 405, "Ship Colour", config.style.fontSize_heading);
    addText(DontPanic.game.world.centerX * 0.75, 450, "Red", config.style.fontSize_default, true, "colour", currentSettings.red);
    addText(DontPanic.game.world.centerX * 1.25, 450, "Blue", config.style.fontSize_default, true, "colour", !currentSettings.red);

    addText(DontPanic.game.world.centerX, 550, "Play", config.style.fontSize_default, true, "play");

    settingsText.add(settingsText__difficulty);
    settingsText.add(settingsText__sound);
    settingsText.add(settingsText__colour);
}

function addText(x, y, string, size, clickevent, category, selected) {
  var textOb = DontPanic.game.add.text(x, y, string, {
    font: `${size} ${config.style.font}`,
  });
  textOb.anchor.setTo(0.5);
  textOb.align = 'center';
  textOb.fill = config.style.textColour;
  textOb.fontSize = size;
  textOb.padding.set(16, 16);
  textOb.inputEnabled = true;
  textOb.input.useHandCursor = clickevent;
  addCategorySpecifics(textOb, category);
  if (selected) {
    colourText(textOb);
  }
  return textOb;
}

function addCategorySpecifics(textOb, category) {
  switch (category) {
    case "difficulty":
      settingsText__difficulty.add(textOb);
      textOb.events.onInputDown.add(difficultyListener, this);
      break;
    case "sound":
      settingsText__sound.add(textOb);
      textOb.events.onInputDown.add(soundListener, this);
      break;
    case "colour":
      settingsText__colour.add(textOb);
      textOb.events.onInputDown.add(colourListener, this);
      break;
    case "play":
      settingsText.add(textOb);
      textOb.events.onInputDown.add(startGame, this);
      break;
    default: ;
  }
}

function getCurrentSettings() {
  const currentSettings = {};
  currentSettings["easy"] = (config.currentLevel == "easy") ?  true : false;
  currentSettings["soundOn"] = config.soundOn;
  currentSettings["red"] = (config.playerColour == "red") ?  true : false;
  return currentSettings;
}

function difficultyListener(input) {
  let previousSelection = config.currentLevel;
  config.currentLevel = input["_text"].toLowerCase();
  if (config.currentLevel != previousSelection) {
    for (var i = 0; i < settingsText__difficulty.children.length; i++) {
      colourText(settingsText__difficulty.children[i]);
    }
  }
  getCurrentSettings();
}

function soundListener(input) {
  let previousSelection = config.soundOn; //true or false
  config.soundOn = (input["_text"].toLowerCase() == "on") ?  true : false;
  if (config.soundOn != previousSelection) {
    for (var i = 0; i < settingsText__sound.children.length; i++) {
      colourText(settingsText__sound.children[i]);
    }
  }
  getCurrentSettings();
}

function colourListener(input) {
  let previousSelection = config.playerColour;
  config.playerColour = input["_text"].toLowerCase();
  if (config.playerColour != previousSelection) {
    for (var i = 0; i < settingsText__colour.children.length; i++) {
      colourText(settingsText__colour.children[i]);
    }
  }
  getCurrentSettings();
}

function colourText(text) {
  if (text['style']['fill'] == config.style.textColour_highlight) {
    text.fill = config.style.textColour;
    text.strokeThickness = 0;
  } else {
    text.fill = config.style.textColour_highlight;
    text.stroke = config.style.textColour_highlightOutline;
    text.strokeThickness = 3;
  }
}

function playAgainMenu() {
  DontPanic.game.gameOver.destroy();
  DontPanic.game.camera.resetFX();
  const restartButton = DontPanic.game.add.button(DontPanic.game.world.centerX, DontPanic.game.world.centerY, 'playAgainButton', startGame, this);
  restartButton.anchor.set(0.5);
  const settingsButton = DontPanic.game.add.button(DontPanic.game.world.centerX, DontPanic.game.world.centerY + 100, 'settingsButton', settingsMenu, this);
  settingsButton.anchor.set(0.5);
  if (DontPanic.newBestScore) {
    const bestDistanceText = addText(DontPanic.game.world.centerX, 190, `New Best Distance!!\n${DontPanic.bestDistance}`, config.style.fontSize_bestDistance);
  } else {
    const bestDistanceText = addText(DontPanic.game.world.centerX, 190, `Best Distance: ${DontPanic.bestDistance}`, config.style.fontSize_bestDistance);
  }
}

function pauseMenu() {
  if (!DontPanic.game.paused) {
    console.log('calling first one');
    paused = DontPanic.game.add.group();
    pausedText = addText(DontPanic.game.world.centerX, 190, 'Paused', config.style.fontSize_title);
    paused.add(pausedText);
    console.log(pausedText);
    DontPanic.game.paused = true;
    settingsButton = DontPanic.game.add.button(DontPanic.game.world.centerX, DontPanic.game.world.centerY, 'settingsButton', settingsMenu, this);
    settingsButton.anchor.set(0.5);
    settingsButton.input.useHandCursor = true;
    paused.add(settingsButton);
    DontPanic.pauseButton.loadTexture('playIcon');
  } else {
    console.log(pausedText);
    paused.kill();
    DontPanic.game.paused = false;
    DontPanic.pauseButton.loadTexture('pauseIcon');
  }
}
<|endoftext|>


<commit_before>var map;

var projections = [
  "EPSG:3571",
  "EPSG:3572",
  "EPSG:3573",
  "EPSG:3574",
  "EPSG:3575",
  "EPSG:3576"
  ];

// Globally define projections for Proj4js. If not defined here, then they must
// be defined in tile provider definitions below.
proj4.defs([
  ["EPSG:3571","+proj=laea +lat_0=90 +lon_0=180 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3572","+proj=laea +lat_0=90 +lon_0=-150 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3573","+proj=laea +lat_0=90 +lon_0=-100 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3574","+proj=laea +lat_0=90 +lon_0=-40 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3575","+proj=laea +lat_0=90 +lon_0=10 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3576","+proj=laea +lat_0=90 +lon_0=90 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"]
]);

// Create object to define tile provider settings and transformations. Supports
// all Leaflet TileLayer options.
var projectedTiles = {};

$.each(projections, function (index, value) {
  var url = "http://{s}.tiles.arcticconnect.org/osm_" + (3571 + index) + "/{z}/{x}/{y}.png";
  projectedTiles["Arctic Connect: " + value] = L.PolarMap.tileLayer(url, {
    name: "Arctic Connect: " + value,
    crs: value,
    minZoom: 0,
    maxZoom: 18,
    tms: false,
    origin: [-20036842.762, 20036842.762],
    maxResolution: ((20036842.762 - -20036842.762) / 256),
    center: [90,0],
    zoom: 2,
    continuousWorld: false,
    noWrap: true,
    attribution: 'Map © ArcticConnect. Data © OpenStreetMap contributors'
  });
});

// Set up next/prev linked list
$.each(projectedTiles, function (layerName, layer) {
  var keys = Object.keys(projectedTiles);
  var index = keys.indexOf(layerName);
  var prev = (index === 0) ? keys.length - 1 : index - 1;
  var next = (index === keys.length - 1) ? 0 : index + 1;

  layer.prev = projectedTiles[keys[prev]];
  layer.next = projectedTiles[keys[next]];
});

// Initialization
$(document).ready(function() {
  Autosize.enable();

  // Load PolarMap
  map = L.PolarMap.map('xmap', {
    baseLayer: projectedTiles["Arctic Connect: EPSG:3571"]
  });

  // Add a Leaflet layer group. Assumed to be EPSG:3857.
  L.layerGroup([
    L.marker([51.080126, -114.13380900]).bindPopup("University of Calgary"),
    L.marker([90, 100]).bindPopup("North Pole")
  ]).addTo(map);

  var layersControl = L.control.layers(projectedTiles, null, {
    collapsed: false
  });
  layersControl.addTo(map);

  // Wire up rotation controls
  var getBaseLayer = function() {
    var foundLayer = null;
    $.each(projectedTiles, function (layerName, layer) {
      if (map.hasLayer(layer)) {
        foundLayer = layer;
      }
    });
    return foundLayer;
  };

  var rotationControls = L.PolarMap.Control.rotation({
    onRotateCW: function() {
      map.loadTileProjection(getBaseLayer().next);
    },

    onRotateCCW: function() {
      map.loadTileProjection(getBaseLayer().prev);
    }
  });
  rotationControls.addTo(map);

  // Automatic Location and Projection Detection
  var userLocation = L.circle();

  map.on('locationfound', function (e) {
    console.log("Location info", e);
    userLocation.setLatLng(e.latlng);
    userLocation.setRadius(e.accuracy);

    if (!map.hasLayer(userLocation)) {
      userLocation.addTo(map);
    }
    map.setView(e.latlng, 17);
  });

  map.on('locationerror', function (e) {
    console.warn("Location detection error:", e);
  });

  map.locate();
});

<commit_msg>Auto select closest projection by longitude<commit_after>var map;

var projections = [
  "EPSG:3571",
  "EPSG:3572",
  "EPSG:3573",
  "EPSG:3574",
  "EPSG:3575",
  "EPSG:3576"
  ];

// Globally define projections for Proj4js. If not defined here, then they must
// be defined in tile provider definitions below.
proj4.defs([
  ["EPSG:3571","+proj=laea +lat_0=90 +lon_0=180 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3572","+proj=laea +lat_0=90 +lon_0=-150 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3573","+proj=laea +lat_0=90 +lon_0=-100 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3574","+proj=laea +lat_0=90 +lon_0=-40 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3575","+proj=laea +lat_0=90 +lon_0=10 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"],
  ["EPSG:3576","+proj=laea +lat_0=90 +lon_0=90 +x_0=0 +y_0=0 +datum=WGS84 +units=m +no_defs"]
]);

// Create object to define tile provider settings and transformations. Supports
// all Leaflet TileLayer options.
var projectedTiles = {};

$.each(projections, function (index, value) {
  var url = "http://{s}.tiles.arcticconnect.org/osm_" + (3571 + index) + "/{z}/{x}/{y}.png";
  projectedTiles["Arctic Connect: " + value] = L.PolarMap.tileLayer(url, {
    name: "Arctic Connect: " + value,
    crs: value,
    minZoom: 0,
    maxZoom: 18,
    tms: false,
    origin: [-20036842.762, 20036842.762],
    maxResolution: ((20036842.762 - -20036842.762) / 256),
    center: [90,0],
    zoom: 2,
    continuousWorld: false,
    noWrap: true,
    attribution: 'Map © ArcticConnect. Data © OpenStreetMap contributors'
  });
});

// Set up next/prev linked list
$.each(projectedTiles, function (layerName, layer) {
  var keys = Object.keys(projectedTiles);
  var index = keys.indexOf(layerName);
  var prev = (index === 0) ? keys.length - 1 : index - 1;
  var next = (index === keys.length - 1) ? 0 : index + 1;

  layer.prev = projectedTiles[keys[prev]];
  layer.next = projectedTiles[keys[next]];
});

// Initialization
$(document).ready(function() {
  Autosize.enable();

  // Load PolarMap
  map = L.PolarMap.map('xmap', {
    baseLayer: projectedTiles["Arctic Connect: EPSG:3571"]
  });

  // Add a Leaflet layer group. Assumed to be EPSG:3857.
  L.layerGroup([
    L.marker([51.080126, -114.13380900]).bindPopup("University of Calgary"),
    L.marker([90, 100]).bindPopup("North Pole")
  ]).addTo(map);

  var layersControl = L.control.layers(projectedTiles, null, {
    collapsed: false
  });
  layersControl.addTo(map);

  // Wire up rotation controls
  var getBaseLayer = function() {
    var foundLayer = null;
    $.each(projectedTiles, function (layerName, layer) {
      if (map.hasLayer(layer)) {
        foundLayer = layer;
      }
    });
    return foundLayer;
  };

  var rotationControls = L.PolarMap.Control.rotation({
    onRotateCW: function() {
      map.loadTileProjection(getBaseLayer().next);
    },

    onRotateCCW: function() {
      map.loadTileProjection(getBaseLayer().prev);
    }
  });
  rotationControls.addTo(map);

  // Projection Selection
  var setProjectionForLongitude = function (longitude) {
    var value;
    if (longitude >= -180 && longitude <= -165) {
      value = "EPSG:3571";
    } else if (longitude > -165 && longitude <= -125) {
      value = "EPSG:3572";
    } else if (longitude > -125 && longitude <= -70) {
      value = "EPSG:3573";
    } else if (longitude > -70 && longitude <= -15) {
      value = "EPSG:3574";
    } else if (longitude > -15 && longitude <= 50) {
      value = "EPSG:3575";
    } else if (longitude > 50 && longitude <= 135) {
      value = "EPSG:3576";
    } else {
      value = "EPSG:3571";
    }

    map.loadTileProjection(projectedTiles["Arctic Connect: " + value]);
  };

  // Automatic Location and Projection Detection
  var userLocation = L.circle();

  map.on('locationfound', function (e) {
    console.log("Location info", e);
    userLocation.setLatLng(e.latlng);
    userLocation.setRadius(e.accuracy);

    if (!map.hasLayer(userLocation)) {
      userLocation.addTo(map);
    }

    setProjectionForLongitude(e.longitude);
  });

  map.on('locationerror', function (e) {
    console.warn("Location detection error:", e);
  });

  map.locate();
});

<|endoftext|>


<commit_before>function shuffleArray(array) {
				for (var i = array.length - 1; i > 0; i--) {
					var j = Math.floor(Math.random() * (i + 1));
					var temp = array[i];
					array[i] = array[j];
					array[j] = temp;
				}
				return array;
			}

			function ListarOpcoes(Pergunta){
				var tmp_opcao_contador = 1;
				var tmp_opcao_codigo = [];
				var tmp_opcao_descricao = [];
				$.ajax({
				type: "GET",
				url: "res/opcao_resposta.xml",
				dataType: "xml",
				success: function(data) {
					$(data).find('opcao_resposta').each(function(){
						var tmp_pergunta  = $(this).find("opr_pergunta").text();
						if (tmp_pergunta  == Pergunta) {
							var codigo = $(this).find("opr_cod").text();
							var opcao_resposta = $(this).find("opr_descricao").text();
							tmp_opcao_codigo.push(codigo);
							tmp_opcao_descricao.push(opcao_resposta);
						}
					});

					for (i = 0; i < 5; i++) {
						$('#opcao' + tmp_opcao_contador + '_rotulo').html(tmp_opcao_descricao[i]);
						$('#opcao' + tmp_opcao_contador).val(tmp_opcao_codigo[i]);
						tmp_opcao_contador++;
					}
					}
				});
			}

			function ValidarResposta(Resposta, Matriz){
				var retorno = "ERRO";
				for (w = 0; w < Matriz.length; w++) {
					if (Math.abs(Resposta) == Math.abs(Matriz[w])) {
						retorno = "ACERTO";
					}
				}
				return retorno;
			}

			function DescricaoResposta(Resposta, Matriz){
				var retorno = "";
				for (w = 0; w < Matriz.length; w++) {
					var conteudo = Matriz[w];
					var tmp_matriz = conteudo.split('*');
					if (Math.abs(Resposta) == Math.abs(tmp_matriz[0])) {
						retorno = tmp_matriz[1];
					}
				}
				return retorno;
			}

			//var perguntas = ["Pergunta1", "Pergunta2", "Pergunta3", "Pergunta4","Pergunta5"];
			var quantidade_acertos = 0;
			var codigo_pergunta = 612;
			var contador = 1;
			var perguntas = [];
			var opcoes_corretas = [];
			var opcoes_descricoes = [];
			var tmp_respostas = [];
			var tmp_acertos = [];

			 $(document).ready(function(){
				$.ajax({
				type: "GET",
				url: "res/perguntas.xml",
				dataType: "xml",
				success: function(data) {
					$(data).find('pergunta').each(function(){
						var codigo = $(this).find("per_cod").text();
						var pergunta = $(this).find("per_pergunta").text();
						var tmp_array = [codigo, pergunta];
						var tmp_conteudo = codigo + '*' + pergunta;
						perguntas.push(tmp_conteudo);
					});
					perguntas = shuffleArray(perguntas);
					var tmp_conteudo = perguntas[0];
					var tmp_matriz = tmp_conteudo.split('*');
					$('#pergunta').html(tmp_matriz[1]);
					codigo_pergunta = tmp_matriz[0];
					}
				});
				//Puxando as opcoes de respostas
				$.ajax({
				type: "GET",
				url: "res/opcao_resposta.xml",
				dataType: "xml",
				success: function(data) {
					$(data).find('opcao_resposta').each(function(){
						var codigo = $(this).find("opr_cod").text();
						var descricao = $(this).find("opr_descricao").text();
						var valida = $(this).find("opr_valida").text();
						var tmp_conteudo = codigo + '*' + descricao;
						if (Math.abs(valida)==1){
							opcoes_corretas.push(codigo);
						}
						opcoes_descricoes.push(tmp_conteudo);
					});
					opcoes_descricoes = shuffleArray(opcoes_descricoes);
					}
				});

				//Carga inicial do sistema
				ListarOpcoes(codigo_pergunta);

				$('#btn_responder').click(function(){
					contador = $('#contador').val();
					var tmp_contador = Math.abs(contador) - 1;
					var tmp_resposta_atual = $('input:radio[name=opcao]:checked').val();

					if (tmp_resposta_atual !=""){
						tmp_respostas.push(tmp_resposta_atual);
						//Validar se a resposta esta certa
						//tmp_acertos.push("ERRO");
						if (ValidarResposta(tmp_resposta_atual, opcoes_corretas)=="ACERTO"){
							quantidade_acertos++;
						}

						//Incrementando o contador e mostrando a proxima pergunta
						contador++;
						var tmp_conteudo = perguntas[tmp_contador];
						var tmp_matriz = tmp_conteudo.split('*');

						$('#pergunta').html(contador + ' -  ' + tmp_matriz[1]);
						//Atualizado as opcoes
						codigo_pergunta = tmp_matriz[0];
						ListarOpcoes(codigo_pergunta);
						$('#contador').val(contador);
						if (contador == 6) {
							//Exibir o resultado na mesma pagina
							//alert(tmp_respostas);
							//,Montando o painel de respostas
							var tmp_tabela;
							tmp_tabela = '
';
							tmp_tabela += '
Voce acertou ' + quantidade_acertos + ' de 5
';
							tmp_tabela += '
';
							tmp_tabela += 'Pergunta	';
							tmp_tabela += 'Sua resposta	';
							tmp_tabela += 'Resultado	';
							tmp_tabela += '
';

							for (i = 0; i < 5; i++) {
								var tmp_conteudo = perguntas[i];
								var tmp_matriz = tmp_conteudo.split('*');
								tmp_tabela += '
';
								tmp_tabela += '' + tmp_matriz[1]  +'	';
								tmp_tabela += '' + DescricaoResposta(tmp_respostas[i], opcoes_descricoes) + '	';
								tmp_tabela += '' + ValidarResposta(tmp_respostas[i], opcoes_corretas) + '	';
								tmp_tabela += '
';
							}

							tmp_tabela += '
';
							$('#tabela_respostas').html(tmp_tabela);
							$("#painel_perguntas").hide();
							$("#painel_respostas").show();
						}
					} else {
						alert('Voc nao selecionou nenhuma opcao!');
					}
				});
			 });
			<commit_msg>2015-05-01<commit_after>function shuffleArray(array) {
				for (var i = array.length - 1; i > 0; i--) {
					var j = Math.floor(Math.random() * (i + 1));
					var temp = array[i];
					array[i] = array[j];
					array[j] = temp;
				}
				return array;
			}

			function ListarOpcoes(Pergunta){
				var tmp_opcao_contador = 1;
				var tmp_opcao_codigo = [];
				var tmp_opcao_descricao = [];
				$.ajax({
				type: "GET",
				url: "res/opcao_resposta.xml",
				dataType: "xml",
				success: function(data) {
					alert('1');
					$(data).find('opcao_resposta').each(function(){
						alert('2');
						var tmp_pergunta  = $(this).find("opr_pergunta").text();
						if (tmp_pergunta  == Pergunta) {
							var codigo = $(this).find("opr_cod").text();
							var opcao_resposta = $(this).find("opr_descricao").text();
							tmp_opcao_codigo.push(codigo);
							tmp_opcao_descricao.push(opcao_resposta);
						}
					});

					for (i = 0; i < 5; i++) {
						$('#opcao' + tmp_opcao_contador + '_rotulo').html(tmp_opcao_descricao[i]);
						$('#opcao' + tmp_opcao_contador).val(tmp_opcao_codigo[i]);
						tmp_opcao_contador++;
					}
					}
				});
			}

			function ValidarResposta(Resposta, Matriz){
				var retorno = "ERRO";
				for (w = 0; w < Matriz.length; w++) {
					if (Math.abs(Resposta) == Math.abs(Matriz[w])) {
						retorno = "ACERTO";
					}
				}
				return retorno;
			}

			function DescricaoResposta(Resposta, Matriz){
				var retorno = "";
				for (w = 0; w < Matriz.length; w++) {
					var conteudo = Matriz[w];
					var tmp_matriz = conteudo.split('*');
					if (Math.abs(Resposta) == Math.abs(tmp_matriz[0])) {
						retorno = tmp_matriz[1];
					}
				}
				return retorno;
			}

			//var perguntas = ["Pergunta1", "Pergunta2", "Pergunta3", "Pergunta4","Pergunta5"];
			var quantidade_acertos = 0;
			var codigo_pergunta = 612;
			var contador = 1;
			var perguntas = [];
			var opcoes_corretas = [];
			var opcoes_descricoes = [];
			var tmp_respostas = [];
			var tmp_acertos = [];

			 $(document).ready(function(){
				$.ajax({
				type: "GET",
				url: "res/perguntas.xml",
				dataType: "xml",
				success: function(data) {
					alert('3');
					$(data).find('pergunta').each(function(){
						alert('4');
						var codigo = $(this).find("per_cod").text();
						var pergunta = $(this).find("per_pergunta").text();
						var tmp_array = [codigo, pergunta];
						var tmp_conteudo = codigo + '*' + pergunta;
						perguntas.push(tmp_conteudo);
					});
					perguntas = shuffleArray(perguntas);
					var tmp_conteudo = perguntas[0];
					var tmp_matriz = tmp_conteudo.split('*');
					$('#pergunta').html(tmp_matriz[1]);
					codigo_pergunta = tmp_matriz[0];
					}
				});
				//Puxando as opcoes de respostas
				$.ajax({
				type: "GET",
				url: "res/opcao_resposta.xml",
				dataType: "xml",
				success: function(data) {
					alert('5');
					$(data).find('opcao_resposta').each(function(){
						alert('6');
						var codigo = $(this).find("opr_cod").text();
						var descricao = $(this).find("opr_descricao").text();
						var valida = $(this).find("opr_valida").text();
						var tmp_conteudo = codigo + '*' + descricao;
						if (Math.abs(valida)==1){
							opcoes_corretas.push(codigo);
						}
						opcoes_descricoes.push(tmp_conteudo);
					});
					opcoes_descricoes = shuffleArray(opcoes_descricoes);
					}
				});

				//Carga inicial do sistema
				ListarOpcoes(codigo_pergunta);

				$('#btn_responder').click(function(){
					alert('7');
					contador = $('#contador').val();
					var tmp_contador = Math.abs(contador) - 1;
					var tmp_resposta_atual = $('input:radio[name=opcao]:checked').val();

					if (tmp_resposta_atual !=""){
						alert('8');
						tmp_respostas.push(tmp_resposta_atual);
						//Validar se a resposta esta certa
						//tmp_acertos.push("ERRO");
						if (ValidarResposta(tmp_resposta_atual, opcoes_corretas)=="ACERTO"){
							quantidade_acertos++;
						}

						//Incrementando o contador e mostrando a proxima pergunta
						contador++;
						var tmp_conteudo = perguntas[tmp_contador];
						var tmp_matriz = tmp_conteudo.split('*');

						$('#pergunta').html(contador + ' -  ' + tmp_matriz[1]);
						//Atualizado as opcoes
						codigo_pergunta = tmp_matriz[0];
						ListarOpcoes(codigo_pergunta);
						$('#contador').val(contador);
						if (contador == 6) {
							alert('9');
							//Exibir o resultado na mesma pagina
							alert(tmp_respostas);
							//,Montando o painel de respostas
							var tmp_tabela;
							tmp_tabela = '
';
							tmp_tabela += '
Voce acertou ' + quantidade_acertos + ' de 5
';
							tmp_tabela += '
';
							tmp_tabela += 'Pergunta	';
							tmp_tabela += 'Sua resposta	';
							tmp_tabela += 'Resultado	';
							tmp_tabela += '
';

							for (i = 0; i < 5; i++) {
								var tmp_conteudo = perguntas[i];
								var tmp_matriz = tmp_conteudo.split('*');
								tmp_tabela += '
';
								tmp_tabela += '' + tmp_matriz[1]  +'	';
								tmp_tabela += '' + DescricaoResposta(tmp_respostas[i], opcoes_descricoes) + '	';
								tmp_tabela += '' + ValidarResposta(tmp_respostas[i], opcoes_corretas) + '	';
								tmp_tabela += '
';
							}

							tmp_tabela += '
';
							$('#tabela_respostas').html(tmp_tabela);
							$("#painel_perguntas").hide();
							$("#painel_respostas").show();
						}
					} else {
						alert('Voc nao selecionou nenhuma opcao!');
					}
				});
			 });
			<|endoftext|>


<commit_before>window.onload = function () {

  var sendModalBtn = document.getElementById('send_modal');
  var sendBtns = document.querySelectorAll('.send');
  var sendCloseBtns = document.querySelectorAll('.send_form_close');

  var receiveModalBtn = document.getElementById('receive_modal');
  var receiveCloseBtns = document.querySelectorAll('.receive_form_close');

  // Get the dialogs.
  var sendModal = document.getElementById('send_form');
  var receiveModal = document.getElementById('receive_form');

  // Setup Event Listeners
  sendModalBtn.addEventListener('click', function(e) {

    e.preventDefault();
    sendModal.showModal();

  });

  for (var i = 0; i < sendCloseBtns.length; i++) {
    sendCloseBtns[i].addEventListener('click', function(e) {
      this.parentNode.close();
    });
  }

  for (var i = 0; i < sendBtns.length; i++) {
        sendBtns[i].addEventListener('click', function(e) {

           var address = document.getElementById('receive_address').value;

          //var address= 0x1359821c5a98e7d5aab0fa3819a47b74e0411b2e
          if(address.search(/0x[a-zA-Z0-9]{40}/) != -1) {

              var contractAddress = '0xb20083039a3b7b76c0dc3884c6e5f41c3784671d';
              var abi = [{"constant":false,"inputs":[{"name":"_receiver","type":"address"},{"name":"_message","type":"string"}],"name":"sendMsg","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"getMsg","outputs":[{"name":"","type":"uint256"},{"name":"","type":"address"},{"name":"","type":"string"},{"name":"","type":"bool"}],"payable":false,"type":"function"}];
              var sendMessage;

              window.web3 = new Web3(web3.currentProvider);

              sendMessage = web3.eth.contract(abi).at(contractAddress);
              sendMessage.sendMsg(address, document.getElementById('receive_contents').value, {gasPrice:web3.toWei(2, 'Gwei')}, function(e,r) {

                alert("TXID Copy to clipboard: Ctrl+C, Enter\n" + r);

              });

              document.getElementById('receive_address').value = "";
              document.getElementById('receive_contents').value = "";
              this.parentNode.close();

            }
            else {

                alert('Please, recheck your sending address.');

             }
        });
    }

    receiveModalBtn.addEventListener('click', function(e) {

      var contractAddress = '0xb20083039a3b7b76c0dc3884c6e5f41c3784671d';
      var abi = [{"constant":false,"inputs":[{"name":"_receiver","type":"address"},{"name":"_message","type":"string"}],"name":"sendMsg","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"getMsg","outputs":[{"name":"","type":"uint256"},{"name":"","type":"address"},{"name":"","type":"string"},{"name":"","type":"bool"}],"payable":false,"type":"function"}];
      var message;

      window.web3 = new Web3(web3.currentProvider);
      message = web3.eth.contract(abi).at(contractAddress);

      message.getMsg(function(e,r) {

        document.getElementById('send_address').value = r[1];
        document.getElementById('send_contents').value = r[2];

      });

      e.preventDefault();
      receiveModal.showModal();

    });

  for (var i = 0; i < receiveCloseBtns.length; i++) {
    receiveCloseBtns[i].addEventListener('click', function(e) {
        document.getElementById('receive_new_img').style.display = "none";
        this.parentNode.close();
    });
  }

};

<commit_msg>Update modal.js<commit_after>window.onload = function () {

  var sendModalBtn = document.getElementById('send_modal');
  var sendBtns = document.querySelectorAll('.send');
  var sendCloseBtns = document.querySelectorAll('.send_form_close');

  var receiveModalBtn = document.getElementById('receive_modal');
  var receiveCloseBtns = document.querySelectorAll('.receive_form_close');

  // Get the dialogs.
  var sendModal = document.getElementById('send_form');
  var receiveModal = document.getElementById('receive_form');

  // Setup Event Listeners
  sendModalBtn.addEventListener('click', function(e) {

    e.preventDefault();
    sendModal.showModal();

  });

  for (var i = 0; i < sendCloseBtns.length; i++) {
    sendCloseBtns[i].addEventListener('click', function(e) {
      this.parentNode.close();
    });
  }

  for (var i = 0; i < sendBtns.length; i++) {
        sendBtns[i].addEventListener('click', function(e) {

           //var address = document.getElementById('receive_address').value;

          var address= "0x1359821c5a98e7d5aab0fa3819a47b74e0411b2e";
          if(address.search(/0x[a-zA-Z0-9]{40}/) != -1) {

              var contractAddress = '0xb20083039a3b7b76c0dc3884c6e5f41c3784671d';
              var abi = [{"constant":false,"inputs":[{"name":"_receiver","type":"address"},{"name":"_message","type":"string"}],"name":"sendMsg","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"getMsg","outputs":[{"name":"","type":"uint256"},{"name":"","type":"address"},{"name":"","type":"string"},{"name":"","type":"bool"}],"payable":false,"type":"function"}];
              var sendMessage;

              window.web3 = new Web3(web3.currentProvider);

              sendMessage = web3.eth.contract(abi).at(contractAddress);
              sendMessage.sendMsg(address, document.getElementById('receive_contents').value, {gasPrice:web3.toWei(2, 'Gwei')}, function(e,r) {

                alert("TXID Copy to clipboard: Ctrl+C, Enter\n" + r);

              });

              document.getElementById('receive_address').value = "";
              document.getElementById('receive_contents').value = "";
              this.parentNode.close();

            }
            else {

                alert('Please, recheck your sending address.');

             }
        });
    }

    receiveModalBtn.addEventListener('click', function(e) {

      var contractAddress = '0xb20083039a3b7b76c0dc3884c6e5f41c3784671d';
      var abi = [{"constant":false,"inputs":[{"name":"_receiver","type":"address"},{"name":"_message","type":"string"}],"name":"sendMsg","outputs":[],"payable":false,"type":"function"},{"constant":true,"inputs":[],"name":"getMsg","outputs":[{"name":"","type":"uint256"},{"name":"","type":"address"},{"name":"","type":"string"},{"name":"","type":"bool"}],"payable":false,"type":"function"}];
      var message;

      window.web3 = new Web3(web3.currentProvider);
      message = web3.eth.contract(abi).at(contractAddress);

      message.getMsg(function(e,r) {

        document.getElementById('send_address').value = r[1];
        document.getElementById('send_contents').value = r[2];

      });

      e.preventDefault();
      receiveModal.showModal();

    });

  for (var i = 0; i < receiveCloseBtns.length; i++) {
    receiveCloseBtns[i].addEventListener('click', function(e) {
        document.getElementById('receive_new_img').style.display = "none";
        this.parentNode.close();
    });
  }

};

<|endoftext|>


<commit_before><commit_msg>Removing peripheral extensions from Corelib<commit_after><|endoftext|>


<commit_before>'use strict';
$(window).on("load resize", (ev) => {
  if (960 < window.innerWidth) {
    $('body').addClass("show-side-nav");
  } else {
    $('body').removeClass("show-side-nav");
  }
})

function closeSidebar() {
  window.history.back();
  $('body').removeClass("show-side-panel");
}

var KelbyOne = KelbyOne || {
  host: 'https://kelbynew.staging.wpengine.com',
  namespace: 'wp-json/ko/v2',
  data: {
    categories: [],
    courses: [],
    course: {}
  },
  hasAuth: function () {
    return getCookie('_ko-session_token');
  },
  retrieveCategories: function () {
    var url = KelbyOne.host + '/' + KelbyOne.namespace + '/categories';
    var $template = $("#category-list-template").html();
    return this.load('categories', url, $template, '#nav');
  },
  retrieveCourses: function (category = null) {
    if (960 > window.innerWidth) {
      $('body').removeClass("show-side-nav");
    }
    $('body').removeClass("show-side-panel");
    var url = KelbyOne.host + '/' + KelbyOne.namespace + '/courses?per_page=12';
    if (category) {
      url = KelbyOne.host + '/' + KelbyOne.namespace + '/categories/' + category + '/courses?per_page=12';
    }
    var $template = $("#course-list-template").html();
    return this.load('courses', url, $template, '#list');
  },
  viewCourse: function (course = null) {
    if (!course) {
      return;
    }
    if (960 > window.innerWidth) {
      $('body').removeClass("show-side-nav");
    }
    $('body').addClass("show-side-panel");
    var url = KelbyOne.host + '/' + KelbyOne.namespace + '/courses/' + course;
    var $template = $("#course-detail-template").html();
    return this.load('course', url, $template, '#item');
  },
  authorize: function (data, resource) {
    var url = KelbyOne.host + '/' + KelbyOne.namespace + '/users/' + resource;

    $.ajax({
      type: "GET",
      url: url,
      contentType: 'application/json',
      beforeSend: function (request) {
        // lock the form to avoid multiple submit
        $('#login').find('input').attr('disabled', true);
        $('#login').find('input[type="submit"]').val('Loading...');
        request.setRequestHeader("Authorization", "Basic " + btoa(data.username + ":" + data.password));
      },
      success: function (response) {
        setCookie('_ko-session_token', response.data.token);
        KelbyOne.loadDynamic();
        KelbyOne.retrieveCategories();

        return KelbyOne.hideLoginForm();
      },
      error: function (response) {
        console.error(response, 'error')
        $('#error').html(response.responseJSON.data);
      }
    }).done(function () {
      $('#login').find('input').attr('disabled', false);
      $('#login').find('input[type="submit"]').val('Submit');
    });
  },
  bindLoginSubmit: function () {
    var self = this;

    $('#login').on('submit', function (ev) {
      ev.preventDefault();
      var data = normalizeFormData($('#login').serializeArray());
      self.authorize(data, 'login');
    });
  },
  showLoginForm: function () {
    history.pushState("", document.title, window.location.pathname + window.location.search);
    $('body').addClass('show-overlay');
  },
  hideLoginForm: function () {
    $('body').removeClass('show-overlay');
  },
  load: function (resource, url, $template, target) {
    if (!KelbyOne.hasAuth()) {
      return KelbyOne.showLoginForm();
    }
    var self = this;

    $.ajax({
      type: "GET",
      url: url,
      contentType: 'application/json',
      beforeSend: function () {
        // Clear existing
        $('.active').removeClass('active');
        $(target).addClass('loading').empty();
      },
      success: function (response) {
        self.data[resource] = response.data;
        if ('course' === resource) {
          // get and append lesson data
          url = KelbyOne.host + '/' + KelbyOne.namespace + '/courses/' + response.data.id + '/lessons';
          $.ajax({
            type: "GET",
            url: url,
            contentType: 'application/json',
            success: function (response) {
              self.data[resource]['lessons'] = response.data;
              var template = Handlebars.compile($template);

              $(target).removeClass('loading');
              $(target).html(template(self.data));
            }
          })
        } else {
          var template = Handlebars.compile($template);

          $(target).removeClass('loading');
          $(target).html(template(self.data));
        }
      }
    }).done(function () {
      $('#nav a').each(function () {
        var $this = $(this);
        // if the current path is like this link, make it active
        if (location.hash && $this.attr('href') == location.hash) {
          $this.parents('.item').addClass('active');
        }
      })
    });
  },
  loadDynamic: function () {
    if (!KelbyOne.hasAuth()) {
      return KelbyOne.showLoginForm();
    }
    var hash = window.location.hash;
    var parts = hash.split('/');

    if ('#category' === parts[0]) {
      return KelbyOne.retrieveCourses(parts[1]);
    }

    if ('#course' === parts[0]) {
      return KelbyOne.viewCourse(parts[1]);
    }

    return KelbyOne.retrieveCourses();
  }
}

KelbyOne.bindLoginSubmit();
KelbyOne.retrieveCategories();
window.onload = KelbyOne.loadDynamic;
window.onhashchange = KelbyOne.loadDynamic;

/*
      Helper Functions.
**************************************/
function normalizeFormData(data) {
  var normalized = data.reduce(function (obj, item) {
    obj[item.name] = item.value;
    return obj;
  }, {});
  return normalized;
}

function setCookie(key, value) {
  var expires = new Date();
  expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
  document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

function getCookie(key) {
  var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
  return keyValue ? keyValue[2] : null;
}

function removeCookie(key) {
  KelbyOne.showLoginForm();
  console.log(key, $.cookie(key));
  if ($.cookie(key) === undefined) {
    return false;
  }
  // Must not alter options, thus extending a fresh object...
  $.cookie(key, '', $.extend({}, {}, {
    expires: -1
  }));
  return !$.cookie(key);
}

function toggleSidebar() {
  $('body').toggleClass("show-side-panel");
}

function toggleSidenav() {
  $('body').toggleClass("show-side-nav");
}

// if ('serviceWorker' in navigator) {
//   navigator.serviceWorker
//     .register('./service-worker.js')
//     .then(function () {
//       console.log('Service Worker Registered');
//     });
// }<commit_msg>removed log<commit_after>'use strict';
$(window).on("load resize", (ev) => {
  if (960 < window.innerWidth) {
    $('body').addClass("show-side-nav");
  } else {
    $('body').removeClass("show-side-nav");
  }
})

function closeSidebar() {
  window.history.back();
  $('body').removeClass("show-side-panel");
}

var KelbyOne = KelbyOne || {
  host: 'https://kelbynew.staging.wpengine.com',
  namespace: 'wp-json/ko/v2',
  data: {
    categories: [],
    courses: [],
    course: {}
  },
  hasAuth: function () {
    return getCookie('_ko-session_token');
  },
  retrieveCategories: function () {
    var url = KelbyOne.host + '/' + KelbyOne.namespace + '/categories';
    var $template = $("#category-list-template").html();
    return this.load('categories', url, $template, '#nav');
  },
  retrieveCourses: function (category = null) {
    if (960 > window.innerWidth) {
      $('body').removeClass("show-side-nav");
    }
    $('body').removeClass("show-side-panel");
    var url = KelbyOne.host + '/' + KelbyOne.namespace + '/courses?per_page=12';
    if (category) {
      url = KelbyOne.host + '/' + KelbyOne.namespace + '/categories/' + category + '/courses?per_page=12';
    }
    var $template = $("#course-list-template").html();
    return this.load('courses', url, $template, '#list');
  },
  viewCourse: function (course = null) {
    if (!course) {
      return;
    }
    if (960 > window.innerWidth) {
      $('body').removeClass("show-side-nav");
    }
    $('body').addClass("show-side-panel");
    var url = KelbyOne.host + '/' + KelbyOne.namespace + '/courses/' + course;
    var $template = $("#course-detail-template").html();
    return this.load('course', url, $template, '#item');
  },
  authorize: function (data, resource) {
    var url = KelbyOne.host + '/' + KelbyOne.namespace + '/users/' + resource;

    $.ajax({
      type: "GET",
      url: url,
      contentType: 'application/json',
      beforeSend: function (request) {
        // lock the form to avoid multiple submit
        $('#login').find('input').attr('disabled', true);
        $('#login').find('input[type="submit"]').val('Loading...');
        request.setRequestHeader("Authorization", "Basic " + btoa(data.username + ":" + data.password));
      },
      success: function (response) {
        setCookie('_ko-session_token', response.data.token);
        KelbyOne.loadDynamic();
        KelbyOne.retrieveCategories();

        return KelbyOne.hideLoginForm();
      },
      error: function (response) {
        console.error(response, 'error')
        $('#error').html(response.responseJSON.data);
      }
    }).done(function () {
      $('#login').find('input').attr('disabled', false);
      $('#login').find('input[type="submit"]').val('Submit');
    });
  },
  bindLoginSubmit: function () {
    var self = this;

    $('#login').on('submit', function (ev) {
      ev.preventDefault();
      var data = normalizeFormData($('#login').serializeArray());
      self.authorize(data, 'login');
    });
  },
  showLoginForm: function () {
    history.pushState("", document.title, window.location.pathname + window.location.search);
    $('body').addClass('show-overlay');
  },
  hideLoginForm: function () {
    $('body').removeClass('show-overlay');
  },
  load: function (resource, url, $template, target) {
    if (!KelbyOne.hasAuth()) {
      return KelbyOne.showLoginForm();
    }
    var self = this;

    $.ajax({
      type: "GET",
      url: url,
      contentType: 'application/json',
      beforeSend: function () {
        // Clear existing
        $('.active').removeClass('active');
        $(target).addClass('loading').empty();
      },
      success: function (response) {
        self.data[resource] = response.data;
        if ('course' === resource) {
          // get and append lesson data
          url = KelbyOne.host + '/' + KelbyOne.namespace + '/courses/' + response.data.id + '/lessons';
          $.ajax({
            type: "GET",
            url: url,
            contentType: 'application/json',
            success: function (response) {
              self.data[resource]['lessons'] = response.data;
              var template = Handlebars.compile($template);

              $(target).removeClass('loading');
              $(target).html(template(self.data));
            }
          })
        } else {
          var template = Handlebars.compile($template);

          $(target).removeClass('loading');
          $(target).html(template(self.data));
        }
      }
    }).done(function () {
      $('#nav a').each(function () {
        var $this = $(this);
        // if the current path is like this link, make it active
        if (location.hash && $this.attr('href') == location.hash) {
          $this.parents('.item').addClass('active');
        }
      })
    });
  },
  loadDynamic: function () {
    if (!KelbyOne.hasAuth()) {
      return KelbyOne.showLoginForm();
    }
    var hash = window.location.hash;
    var parts = hash.split('/');

    if ('#category' === parts[0]) {
      return KelbyOne.retrieveCourses(parts[1]);
    }

    if ('#course' === parts[0]) {
      return KelbyOne.viewCourse(parts[1]);
    }

    return KelbyOne.retrieveCourses();
  }
}

KelbyOne.bindLoginSubmit();
KelbyOne.retrieveCategories();
window.onload = KelbyOne.loadDynamic;
window.onhashchange = KelbyOne.loadDynamic;

/*
      Helper Functions.
**************************************/
function normalizeFormData(data) {
  var normalized = data.reduce(function (obj, item) {
    obj[item.name] = item.value;
    return obj;
  }, {});
  return normalized;
}

function setCookie(key, value) {
  var expires = new Date();
  expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
  document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

function getCookie(key) {
  var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
  return keyValue ? keyValue[2] : null;
}

function removeCookie(key) {
  KelbyOne.showLoginForm();
  if ($.cookie(key) === undefined) {
    return false;
  }
  // Must not alter options, thus extending a fresh object...
  $.cookie(key, '', $.extend({}, {}, {
    expires: -1
  }));
  return !$.cookie(key);
}

function toggleSidebar() {
  $('body').toggleClass("show-side-panel");
}

function toggleSidenav() {
  $('body').toggleClass("show-side-nav");
}

// if ('serviceWorker' in navigator) {
//   navigator.serviceWorker
//     .register('./service-worker.js')
//     .then(function () {
//       console.log('Service Worker Registered');
//     });
// }<|endoftext|>