<commit_before>/*global $, Whisper, Backbone, textsecure, extension*/
/* vim: ts=4:sw=4:expandtab:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// This script should only be included in background.html
// Whisper.windowMap is defined in background.js
(function () {
    'use strict';

    window.Whisper = window.Whisper || {};

    var windowMap = new Whisper.Bimap('windowId', 'modelId');
    var conversations = new Whisper.ConversationCollection();

    window.getConversationForWindow = function(windowId) {
        return conversations.get(windowMap.modelIdFrom(windowId));
    };

    window.updateConversation = function(conversationId) {
        var conversation = conversations.get(conversationId);
        if (conversation) {
            conversation.fetch();
            conversation.fetchMessages();
        }
    };

    function closeConversation (windowId) {
        windowMap.remove('windowId', windowId);
    }

    window.getConversation = function(attrs) {
        var conversation = window.inbox.get(attrs.id) || attrs;
        conversation = conversations.add(conversation);
        return conversation;
    };

    window.notifyConversation = function(message) {
        if (Whisper.Notifications.isEnabled()) {
            var conversation = getConversation({id: message.get('conversationId')});
            var sender = getConversation({id: message.get('source')});
            conversation.fetch().then(function() {
                sender.fetch().then(function() {
                    var notification = new Notification(sender.getTitle(), {
                        body: message.getDescription(),
                        icon: sender.getAvatarUrl(),
                        tag: conversation.id
                    });
                    notification.onclick = function() {
                        openConversation(conversation.id);
                    };
                });
            });
            conversation.fetchMessages();
        } else {
            openConversation(message.get('conversationId'));
        }
    };

    window.openConversation = function openConversation (modelId) {
        var conversation = getConversation({id: modelId});
        conversation.fetch().then(function() {
            conversation.fetchContacts();
        });
        conversation.fetchMessages();

        var windowId = windowMap.windowIdFrom(modelId);

        // prevent multiple copies of the same conversation from being opened
        if (!windowId) {
            // open the panel
            extension.windows.open({
                id: modelId,
                url: 'conversation.html',
                type: 'panel',
                focused: true,
                width: 300,
                height: 420
            }, function (windowInfo) {
                windowMap.add({ windowId: windowInfo.id, modelId: modelId });

                // close the panel if background.html is refreshed
                extension.windows.beforeUnload(function() {
                    // TODO: reattach after reload instead of closing.
                    extension.windows.remove(windowInfo.id);
                });
            });
        } else {
            // focus the panel
            extension.windows.focus(windowId, function (error) {
                if (error) {
                    closeConversation(windowId); // panel isn't actually open...
                    openConversation(modelId); // ...and so we try again.
                }
            });
        }
    };

    /* Inbox window controller */
    var inboxOpened = false;
    var inboxWindowId = 0;
    window.openInbox = function() {
        if (inboxOpened === false) {
            inboxOpened = true;
            extension.windows.open({
                id: 'inbox',
                url: 'index.html',
                type: 'panel',
                focused: true,
                width: 260, // 280 for chat
                height: 440 // 420 for chat
            }, function (windowInfo) {
                inboxWindowId = windowInfo.id;

                // close the panel if background.html is refreshed
                extension.windows.beforeUnload(function() {
                    // TODO: reattach after reload instead of closing.
                    extension.windows.remove(windowInfo.id);
                });
            });
        } else if (inboxOpened === true) {
            extension.windows.focus(inboxWindowId, function (error) {
                if (error) {
                    inboxOpened = false;
                    openInbox();
                }
            });
        }
    };

    extension.onLaunched(function() {
        if (textsecure.registration.isDone()) {
            openInbox();
        } else {
            extension.install();
        }
    });

    // make sure windows are cleaned up on close
    extension.windows.onClosed(function (windowId) {
        if (windowMap.windowId[windowId]) {
            closeConversation(windowId);
        }

        if (windowId === inboxWindowId) {
            inboxWindowId = 0;
            inboxOpened = false;
        }
    });
})();
<commit_msg>Make conversation windows taller<commit_after>/*global $, Whisper, Backbone, textsecure, extension*/
/* vim: ts=4:sw=4:expandtab:
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

// This script should only be included in background.html
// Whisper.windowMap is defined in background.js
(function () {
    'use strict';

    window.Whisper = window.Whisper || {};

    var windowMap = new Whisper.Bimap('windowId', 'modelId');
    var conversations = new Whisper.ConversationCollection();

    window.getConversationForWindow = function(windowId) {
        return conversations.get(windowMap.modelIdFrom(windowId));
    };

    window.updateConversation = function(conversationId) {
        var conversation = conversations.get(conversationId);
        if (conversation) {
            conversation.fetch();
            conversation.fetchMessages();
        }
    };

    function closeConversation (windowId) {
        windowMap.remove('windowId', windowId);
    }

    window.getConversation = function(attrs) {
        var conversation = window.inbox.get(attrs.id) || attrs;
        conversation = conversations.add(conversation);
        return conversation;
    };

    window.notifyConversation = function(message) {
        if (Whisper.Notifications.isEnabled()) {
            var conversation = getConversation({id: message.get('conversationId')});
            var sender = getConversation({id: message.get('source')});
            conversation.fetch().then(function() {
                sender.fetch().then(function() {
                    var notification = new Notification(sender.getTitle(), {
                        body: message.getDescription(),
                        icon: sender.getAvatarUrl(),
                        tag: conversation.id
                    });
                    notification.onclick = function() {
                        openConversation(conversation.id);
                    };
                });
            });
            conversation.fetchMessages();
        } else {
            openConversation(message.get('conversationId'));
        }
    };

    window.openConversation = function openConversation (modelId) {
        var conversation = getConversation({id: modelId});
        conversation.fetch().then(function() {
            conversation.fetchContacts();
        });
        conversation.fetchMessages();

        var windowId = windowMap.windowIdFrom(modelId);

        // prevent multiple copies of the same conversation from being opened
        if (!windowId) {
            // open the panel
            extension.windows.open({
                id: modelId,
                url: 'conversation.html',
                type: 'panel',
                focused: true,
                width: 300,
                height: 440
            }, function (windowInfo) {
                windowMap.add({ windowId: windowInfo.id, modelId: modelId });

                // close the panel if background.html is refreshed
                extension.windows.beforeUnload(function() {
                    // TODO: reattach after reload instead of closing.
                    extension.windows.remove(windowInfo.id);
                });
            });
        } else {
            // focus the panel
            extension.windows.focus(windowId, function (error) {
                if (error) {
                    closeConversation(windowId); // panel isn't actually open...
                    openConversation(modelId); // ...and so we try again.
                }
            });
        }
    };

    /* Inbox window controller */
    var inboxOpened = false;
    var inboxWindowId = 0;
    window.openInbox = function() {
        if (inboxOpened === false) {
            inboxOpened = true;
            extension.windows.open({
                id: 'inbox',
                url: 'index.html',
                type: 'panel',
                focused: true,
                width: 260, // 280 for chat
                height: 440 // 420 for chat
            }, function (windowInfo) {
                inboxWindowId = windowInfo.id;

                // close the panel if background.html is refreshed
                extension.windows.beforeUnload(function() {
                    // TODO: reattach after reload instead of closing.
                    extension.windows.remove(windowInfo.id);
                });
            });
        } else if (inboxOpened === true) {
            extension.windows.focus(inboxWindowId, function (error) {
                if (error) {
                    inboxOpened = false;
                    openInbox();
                }
            });
        }
    };

    extension.onLaunched(function() {
        if (textsecure.registration.isDone()) {
            openInbox();
        } else {
            extension.install();
        }
    });

    // make sure windows are cleaned up on close
    extension.windows.onClosed(function (windowId) {
        if (windowMap.windowId[windowId]) {
            closeConversation(windowId);
        }

        if (windowId === inboxWindowId) {
            inboxWindowId = 0;
            inboxOpened = false;
        }
    });
})();
<|endoftext|>


<commit_before>var gulp = require('gulp');
var runSequence = require('run-sequence').use(gulp);
var ghPages = require('gulp-gh-pages');
var os = require('os');
var path = require('path');
var fs = require('fs');

gulp.task('deploy', ['deploy:sequence']);

function getName() {
  var pkg = JSON.parse(fs.readFileSync(path.join('./package.json'), 'utf8'));
  return pkg.name;
}

gulp.task('deploy:github:pages', () => {
  return gulp.src('./build/guide/**/*')
    .pipe(ghPages({
      cacheDir: path.join(os.tmpdir(), getName())
    }));
});

var tasks = [
  'concat:vendor',
  'concat:lib',
  'less:dev',
  'copy:images',
  'copy:fonts',
  'copy:js:guide',
  'build'
];

gulp.task('deploy:sequence', () => {
  runSequence(
    'lint',
    ['clean:css', 'clean:js', 'clean:fonts', 'clean:images'],
    tasks,
    'deploy:github:pages'
  );
});
<commit_msg>remove gulp deploy task<commit_after><|endoftext|>


<commit_before>/*global $, Whisper, Backbone, textsecure, extension*/
/*
 * vim: ts=4:sw=4:expandtab
 */

// This script should only be included in background.html
(function () {
    'use strict';

    window.Whisper = window.Whisper || {};

    var conversations = new Whisper.ConversationCollection();
    var inboxCollection = new (Backbone.Collection.extend({
        initialize: function() {
            this.on('change:active_at', this.sort);
            this.on('change:unreadCount', this.updateUnreadCount);

            this.listenTo(conversations, 'add change:active_at', this.addActive);
        },
        comparator: function(model) {
            return -model.get('active_at');
        },
        addActive: function(model) {
            if (model.get('active_at')) {
                this.add(model);
            } else {
                this.remove(model);
            }
        },
        updateUnreadCount: function(model, count) {
            var prev = model.previous('unreadCount') || 0;
            if (count < prev) { // decreased
                var newUnreadCount = storage.get("unreadCount", 0) - (prev - count);
                setUnreadCount(newUnreadCount);
                storage.put("unreadCount", newUnreadCount);
            }
        }
    }))();

    window.getInboxCollection = function() {
        return inboxCollection;
    };

    window.ConversationController = {
        get: function(id) {
            return conversations.get(id);
        },
        create: function(attrs) {
            var conversation = conversations.add(attrs);
            return conversation;
        },
        findOrCreatePrivateById: function(id) {
            var conversation = conversations.add({ id: id, type: 'private' });
            return new Promise(function(resolve, reject) {
                conversation.fetch().then(function() {
                    resolve(conversation);
                }).fail(function() {
                    var saved = conversation.save(); // false or indexedDBRequest
                    if (saved) {
                        saved.then(function() {
                            resolve(conversation);
                        }).fail(reject);
                    } else {
                        reject();
                    }
                });
            });
        },
        updateInbox: function() {
            conversations.fetchActive();
        }
    };

    ConversationController.updateInbox();
    setUnreadCount(storage.get("unreadCount", 0));

    function setUnreadCount(count) {
        if (count > 0) {
            extension.navigator.setBadgeText(count);
        } else {
            extension.navigator.setBadgeText("");
        }
    }

    window.notifyConversation = function(message) {
        var conversationId = message.get('conversationId');
        var conversation = ConversationController.get(conversationId);
        if (!conversation) {
            conversation = conversations.create({id: conversationId});
            conversation.fetch();
        }

        if (inboxOpened) {
            conversation.trigger('newmessages');
            extension.windows.drawAttention(inboxWindowId);
            if (!appWindow.isMinimized()) {
                return;
            }
        }

        if (Whisper.Notifications.isEnabled()) {
            var sender = ConversationController.create({id: message.get('source')});
            conversation.fetch().then(function() {
                sender.fetch().then(function() {
                    sender.getNotificationIcon().then(function(iconUrl) {
                        Whisper.Notifications.add({
                            title    : sender.getTitle(),
                            message  : message.getNotificationText(),
                            iconUrl  : iconUrl,
                            imageUrl : message.getImageUrl(),
                            conversationId: conversation.id
                        });
                    });
                });
            });
        } else {
            openConversation(conversation);
            ConversationController.updateInbox();
        }
    };

    /* Inbox window controller */
    var inboxOpened = false;
    var inboxWindowId = 'inbox';
    var appWindow = null;
    window.openInbox = function() {
        if (inboxOpened === false) {
            inboxOpened = true;
            extension.windows.open({
                id: 'inbox',
                url: 'index.html',
                type: 'panel',
                frame: 'none',
                focused: true,
                width: 580,
                height: 440,
                minWidth: 230,
                minHeight: 150
            }, function (windowInfo) {
                inboxWindowId = windowInfo.id;
                appWindow = windowInfo;

                windowInfo.onClosed.addListener(function () {
                    inboxOpened = false;
                    appWindow = null;
                });

                // close the panel if background.html is refreshed
                extension.windows.beforeUnload(function() {
                    // TODO: reattach after reload instead of closing.
                    extension.windows.remove(inboxWindowId);
                });
            });
        } else if (inboxOpened === true) {
            extension.windows.focus(inboxWindowId, function (error) {
                if (error) {
                    inboxOpened = false;
                    openInbox();
                }
            });
        }
    };

    var open;
    window.openConversation = function(conversation) {
        if (inboxOpened === true) {
            var appWindow = chrome.app.window.get(inboxWindowId);
            appWindow.contentWindow.openConversation(conversation);
        } else {
            open = conversation;
        }
        openInbox();
    };
    window.getOpenConversation = function() {
        var o = open;
        open = null;
        return o;
    };

    extension.onLaunched(function() {
        storage.onready(function() {
            if (textsecure.registration.isDone()) {
                openInbox();
            } else {
                extension.install();
            }
        });
    });
})();
<commit_msg>Fix disappearing contact info<commit_after>/*global $, Whisper, Backbone, textsecure, extension*/
/*
 * vim: ts=4:sw=4:expandtab
 */

// This script should only be included in background.html
(function () {
    'use strict';

    window.Whisper = window.Whisper || {};

    var conversations = new Whisper.ConversationCollection();
    var inboxCollection = new (Backbone.Collection.extend({
        initialize: function() {
            this.on('change:active_at', this.sort);
            this.on('change:unreadCount', this.updateUnreadCount);

            this.listenTo(conversations, 'add change:active_at', this.addActive);
        },
        comparator: function(model) {
            return -model.get('active_at');
        },
        addActive: function(model) {
            if (model.get('active_at')) {
                this.add(model);
            } else {
                this.remove(model);
            }
        },
        updateUnreadCount: function(model, count) {
            var prev = model.previous('unreadCount') || 0;
            if (count < prev) { // decreased
                var newUnreadCount = storage.get("unreadCount", 0) - (prev - count);
                setUnreadCount(newUnreadCount);
                storage.put("unreadCount", newUnreadCount);
            }
        }
    }))();

    window.getInboxCollection = function() {
        return inboxCollection;
    };

    window.ConversationController = {
        get: function(id) {
            return conversations.get(id);
        },
        create: function(attrs) {
            var conversation = conversations.add(attrs);
            return conversation;
        },
        findOrCreatePrivateById: function(id) {
            var conversation = conversations.add({ id: id, type: 'private' });
            return new Promise(function(resolve, reject) {
                conversation.fetch().then(function() {
                    resolve(conversation);
                }).fail(function() {
                    var saved = conversation.save(); // false or indexedDBRequest
                    if (saved) {
                        saved.then(function() {
                            resolve(conversation);
                        }).fail(reject);
                    } else {
                        reject();
                    }
                });
            });
        },
        updateInbox: function() {
            conversations.fetchActive();
        }
    };

    ConversationController.updateInbox();
    setUnreadCount(storage.get("unreadCount", 0));

    function setUnreadCount(count) {
        if (count > 0) {
            extension.navigator.setBadgeText(count);
        } else {
            extension.navigator.setBadgeText("");
        }
    }

    window.notifyConversation = function(message) {
        var conversationId = message.get('conversationId');
        var conversation = ConversationController.get(conversationId);
        if (!conversation) {
            conversation = ConversationController.create({id: conversationId});
            conversation.fetch();
        }

        if (inboxOpened) {
            conversation.trigger('newmessages');
            extension.windows.drawAttention(inboxWindowId);
            if (!appWindow.isMinimized()) {
                return;
            }
        }

        if (Whisper.Notifications.isEnabled()) {
            var sender = ConversationController.create({id: message.get('source')});
            conversation.fetch().then(function() {
                sender.fetch().then(function() {
                    sender.getNotificationIcon().then(function(iconUrl) {
                        Whisper.Notifications.add({
                            title    : sender.getTitle(),
                            message  : message.getNotificationText(),
                            iconUrl  : iconUrl,
                            imageUrl : message.getImageUrl(),
                            conversationId: conversation.id
                        });
                    });
                });
            });
        } else {
            openConversation(conversation);
            ConversationController.updateInbox();
        }
    };

    /* Inbox window controller */
    var inboxOpened = false;
    var inboxWindowId = 'inbox';
    var appWindow = null;
    window.openInbox = function() {
        if (inboxOpened === false) {
            inboxOpened = true;
            extension.windows.open({
                id: 'inbox',
                url: 'index.html',
                type: 'panel',
                frame: 'none',
                focused: true,
                width: 580,
                height: 440,
                minWidth: 230,
                minHeight: 150
            }, function (windowInfo) {
                inboxWindowId = windowInfo.id;
                appWindow = windowInfo;

                windowInfo.onClosed.addListener(function () {
                    inboxOpened = false;
                    appWindow = null;
                });

                // close the panel if background.html is refreshed
                extension.windows.beforeUnload(function() {
                    // TODO: reattach after reload instead of closing.
                    extension.windows.remove(inboxWindowId);
                });
            });
        } else if (inboxOpened === true) {
            extension.windows.focus(inboxWindowId, function (error) {
                if (error) {
                    inboxOpened = false;
                    openInbox();
                }
            });
        }
    };

    var open;
    window.openConversation = function(conversation) {
        if (inboxOpened === true) {
            var appWindow = chrome.app.window.get(inboxWindowId);
            appWindow.contentWindow.openConversation(conversation);
        } else {
            open = conversation;
        }
        openInbox();
    };
    window.getOpenConversation = function() {
        var o = open;
        open = null;
        return o;
    };

    extension.onLaunched(function() {
        storage.onready(function() {
            if (textsecure.registration.isDone()) {
                openInbox();
            } else {
                extension.install();
            }
        });
    });
})();
<|endoftext|>


<commit_before>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

 This Source Code is subject to the terms of the Mozilla Public
 License, v2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 ------------------------------------------------------------------
  The Espruino tutorial
 ------------------------------------------------------------------
**/
"use strict";
(function(){

  var TUTORIALS_DIR = "data/tutorials/";

  var tutorialData = [];
  var tutorialStep = 0;
  var tutorialLastInputLine = undefined;
  var tutorialWatcherInterval = undefined;

  function init() {
    Espruino.Core.App.addIcon({
      id: "help",
      icon: "help",
      title : "Help",
      order: -95,
      area: {
        name: "toolbar",
        position: "right"
      },
      menu: [{
        id: "tutorial",
        icon: "help",
        title: "Tutorial",
        order: 100,
        click: function(){
          if (!hasTutorial()) {
            Espruino.Core.MenuPortSelector.ensureConnected(function() {
              loadTutorialURL(TUTORIALS_DIR+"1.js");
            });
          } else {
            stopTutorial();
          }
        }
      }]
    });

    // if terminal was cleared this may have been to remove the tutorial, so do this if needed
    Espruino.addProcessor("terminalClear", function(data, callback) {
      if (hasTutorial())
        stopTutorial();
      callback(data);
    });
    // If disconnect, stop tutorial too
    Espruino.addProcessor("disconnected", function(data, callback) {
      if (hasTutorial())
        stopTutorial();
      callback(data);
    });
  }

  function loadTutorialText(text) {
    var step = { text : "", code : "" };
    tutorialData = [ ];
    var lines = text.split("\n");
    for (var i in lines) {
      var l = lines[i];
      if (l.substr(0,2)=="//") {
        step.text += l.substr(2).trim()+"\n";
      } else
        step.code += l+"\n";
      if (l=="" && step.text!="") {
        step.code = step.code.trim();
        step.text = step.text.trim();
        tutorialData.push(step);
        step = { text : "", code : "" };
      }
    }
    if (step.text!="")
      tutorialData.push(step);
    // first get a list of declarations
    var DECLS = [];
    var boardData = Espruino.Core.Env.getBoardData();
    if (boardData && boardData.BOARD)
      DECLS.push(boardData.BOARD);
    // detect comments like <PIXLJS>foo</PIXLJS> and <!PIXLJS>foo</!PIXLJS>
    // and crop them out if they don't match our board
    tutorialData.forEach(step => {
      var ifBoardRegex = /<(!?[A-Z]+)>(.*)<\/\1>/;
      var ifBoard = step.text.match(ifBoardRegex);
      while (ifBoard) {
        var decl = ifBoard[1];
        var txt = ifBoard[2];
        var negated = decl[0]=="!";
        if (negated) decl = decl.substring(1);
        if (DECLS.includes(decl) == negated) txt="";
        // replace text and try again
        step.text = step.text.substring(0,ifBoard.index) + txt + step.text.substring(ifBoard.index+ifBoard[0].length);
        ifBoard = step.text.match(ifBoardRegex);
      }
    });

    // test
    displayTutorialStep();
  }

  function loadTutorialURL(url) {
    Espruino.Core.Utils.getURL( url, function(data) {
      loadTutorialText(data);
      if (tutorialWatcherInterval===undefined)
        tutorialWatcherInterval = setInterval(tutorialWatcher, 1000);
    });
  }

  function hasTutorial() {
    return tutorialData.length != 0;
  }

  function stopTutorial() {
    tutorialData = [];
    tutorialStep = 0;
    tutorialLastInputLine = undefined;
    if (tutorialWatcherInterval) clearInterval(tutorialWatcherInterval);
    tutorialWatcherInterval = undefined;
    Espruino.Core.Terminal.clearExtraText();
   }

  function displayTutorialStep() {
    var inputLine = Espruino.Core.Terminal.getInputLine(0);
    var text = '
'+Espruino.Core.HTML.markdownToHTML(tutorialData[tutorialStep].text)+'
';
    if (tutorialData[tutorialStep].code != "")
      text += '
'+Espruino.Core.Utils.escapeHTML(tutorialData[tutorialStep].code).replace(/\n/g,"
")+'
';
    text += '
';
    Espruino.Core.Terminal.setExtraText((inputLine===undefined)?0:inputLine.line, text);
  }

  function isCodeEqual(a,b) {
    console.log("Compare");
    console.log("A> "+JSON.stringify(a));
    console.log("B> "+JSON.stringify(b));
    // now compare streams of tokens
    var la = Espruino.Core.Utils.getLexer(a);
    var tka = la.next();
    var lb = Espruino.Core.Utils.getLexer(b);
    var tkb = lb.next();
    while (tka!==undefined || tkb!==undefined) {
      if (tka==undefined || tkb==undefined || tka.str!=tkb.str) {
        return false;
      }
      tka = la.next();
      tkb = lb.next();
    }
    return true;
  }

  function tutorialWatcher() {
    if (tutorialStep >= tutorialData.length) return;

    // Find out if we've accidentally skipped some input lines
    var linesPast = 0;
    var line = Espruino.Core.Terminal.getInputLine(linesPast);
    if (line===undefined) return;
    var currentInputLine = line.line;
    if (tutorialLastInputLine===undefined) tutorialLastInputLine = line.line;
    while (line!==undefined && line.line>tutorialLastInputLine) {
      linesPast++;
      line = Espruino.Core.Terminal.getInputLine(linesPast);
    }
    tutorialLastInputLine = currentInputLine;
    // if we have, try and handle them
    while (linesPast>0) {
      console.log("Checking previous line "+linesPast);
      line = Espruino.Core.Terminal.getInputLine(linesPast);
      // user has entered the correct command - let's move to next
      if (line!==undefined && isCodeEqual(line.text,tutorialData[tutorialStep].code) &&
          tutorialStep+1 < tutorialData.length) {
        tutorialStep++;
        displayTutorialStep();
      }
      linesPast--;
    }
  }

  Espruino.Plugins.Tutorial = {
    init : init,
  };
}());
<commit_msg>Update tutorial.js<commit_after>/**
 Copyright 2014 Gordon Williams (gw@pur3.co.uk)

 This Source Code is subject to the terms of the Mozilla Public
 License, v2.0. If a copy of the MPL was not distributed with this
 file, You can obtain one at http://mozilla.org/MPL/2.0/.

 ------------------------------------------------------------------
  The Espruino tutorial
 ------------------------------------------------------------------
**/
"use strict";
(function(){

  var TUTORIALS_DIR = "data/tutorials/";

  var tutorialData = [];
  var tutorialStep = 0;
  var tutorialLastInputLine = undefined;
  var tutorialWatcherInterval = undefined;

  function init() {
    Espruino.Core.App.addIcon({
      id: "help",
      icon: "help",
      title : "Help",
      order: -95,
      area: {
        name: "toolbar",
        position: "right"
      },
      menu: [{
        id: "tutorial",
        icon: "help",
        title: "Tutorial",
        order: 100,
        click: function(){
          if (!hasTutorial()) {
            Espruino.Core.MenuPortSelector.ensureConnected(function() {
              loadTutorialURL(TUTORIALS_DIR+"1.js");
            });
          } else {
            stopTutorial();
          }
        }
      }]
    });

    // if terminal was cleared this may have been to remove the tutorial, so do this if needed
    Espruino.addProcessor("terminalClear", function(data, callback) {
      if (hasTutorial())
        stopTutorial();
      callback(data);
    });
    // If disconnect, stop tutorial too
    Espruino.addProcessor("disconnected", function(data, callback) {
      if (hasTutorial())
        stopTutorial();
      callback(data);
    });
  }

  function loadTutorialText(text) {
    var step = { text : "", code : "" };
    tutorialData = [ ];
    var lines = text.split("\n");
    for (var i in lines) {
      var l = lines[i];
      if (l.substr(0,2)=="//") {
        step.text += l.substr(2).trim()+"\n";
      } else
        step.code += l+"\n";
      if (l=="" && step.text!="") {
        step.code = step.code.trim();
        step.text = step.text.trim();
        tutorialData.push(step);
        step = { text : "", code : "" };
      }
    }
    if (step.text!="")
      tutorialData.push(step);
    // first get a list of declarations
    var DECLS = [];
    var boardData = Espruino.Core.Env.getBoardData();
    if (boardData && boardData.BOARD)
      DECLS.push(boardData.BOARD);
    // detect comments like <PIXLJS>foo</PIXLJS> and <!PIXLJS>foo</!PIXLJS>
    // and crop them out if they don't match our board
    tutorialData.forEach(step => {
      var ifBoardRegex = /<(!?[A-Z]+)>(.*?)<\/\1>/s;
      var ifBoard = step.text.match(ifBoardRegex);
      while (ifBoard) {
        var decl = ifBoard[1];
        var txt = ifBoard[2];
        var negated = decl[0]=="!";
        if (negated) decl = decl.substring(1);
        if (DECLS.includes(decl) == negated) txt="";
        // replace text and try again
        step.text = step.text.substring(0,ifBoard.index) + txt + step.text.substring(ifBoard.index+ifBoard[0].length);
        ifBoard = step.text.match(ifBoardRegex);
      }
    });

    // test
    displayTutorialStep();
  }

  function loadTutorialURL(url) {
    Espruino.Core.Utils.getURL( url, function(data) {
      loadTutorialText(data);
      if (tutorialWatcherInterval===undefined)
        tutorialWatcherInterval = setInterval(tutorialWatcher, 1000);
    });
  }

  function hasTutorial() {
    return tutorialData.length != 0;
  }

  function stopTutorial() {
    tutorialData = [];
    tutorialStep = 0;
    tutorialLastInputLine = undefined;
    if (tutorialWatcherInterval) clearInterval(tutorialWatcherInterval);
    tutorialWatcherInterval = undefined;
    Espruino.Core.Terminal.clearExtraText();
   }

  function displayTutorialStep() {
    var inputLine = Espruino.Core.Terminal.getInputLine(0);
    var text = '
'+Espruino.Core.HTML.markdownToHTML(tutorialData[tutorialStep].text)+'
';
    if (tutorialData[tutorialStep].code != "")
      text += '
'+Espruino.Core.Utils.escapeHTML(tutorialData[tutorialStep].code).replace(/\n/g,"
")+'
';
    text += '
';
    Espruino.Core.Terminal.setExtraText((inputLine===undefined)?0:inputLine.line, text);
  }

  function isCodeEqual(a,b) {
    console.log("Compare");
    console.log("A> "+JSON.stringify(a));
    console.log("B> "+JSON.stringify(b));
    // now compare streams of tokens
    var la = Espruino.Core.Utils.getLexer(a);
    var tka = la.next();
    var lb = Espruino.Core.Utils.getLexer(b);
    var tkb = lb.next();
    while (tka!==undefined || tkb!==undefined) {
      if (tka==undefined || tkb==undefined || tka.str!=tkb.str) {
        return false;
      }
      tka = la.next();
      tkb = lb.next();
    }
    return true;
  }

  function tutorialWatcher() {
    if (tutorialStep >= tutorialData.length) return;

    // Find out if we've accidentally skipped some input lines
    var linesPast = 0;
    var line = Espruino.Core.Terminal.getInputLine(linesPast);
    if (line===undefined) return;
    var currentInputLine = line.line;
    if (tutorialLastInputLine===undefined) tutorialLastInputLine = line.line;
    while (line!==undefined && line.line>tutorialLastInputLine) {
      linesPast++;
      line = Espruino.Core.Terminal.getInputLine(linesPast);
    }
    tutorialLastInputLine = currentInputLine;
    // if we have, try and handle them
    while (linesPast>0) {
      console.log("Checking previous line "+linesPast);
      line = Espruino.Core.Terminal.getInputLine(linesPast);
      // user has entered the correct command - let's move to next
      if (line!==undefined && isCodeEqual(line.text,tutorialData[tutorialStep].code) &&
          tutorialStep+1 < tutorialData.length) {
        tutorialStep++;
        displayTutorialStep();
      }
      linesPast--;
    }
  }

  Espruino.Plugins.Tutorial = {
    init : init,
  };
}());
<|endoftext|>


<commit_before>var express = require('express');
var fs = require('fs');
var path = require('path');

var portret = {};
portret.collectionPath = "./collections/";
portret.fileTypes = [".jpg", ".jpeg", ".png", ".gif"];

var app = express();

// configure CORS
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

app.get('/collections', function (req, res, next) {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(portret.getCollections()));
});

app.get('/collection/:name', function (req, res, next) {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(portret.getPics(req.params.name)));
});

var server = app.listen(8081, function () {
   var host = server.address().address;
   var port = server.address().port;
   host = (host == "::") ? "127.0.0.1" : host;
   console.log("Portret REST API listening at http://%s:%s", host, port)
});

/**
 * Return a list of known collections.
 * @return {Array}
 */
portret.getCollections = function () {
    var result = [];
    var files = fs.readdirSync(portret.collectionPath);
    for (var f in files) {
        var curFile =  path.join(portret.collectionPath, files[f]);
        if (fs.statSync(curFile).isDirectory()) {
            var collection = {};
            collection.name = files[f];
            collection.count = portret.getPics(collection.name).count;
            result.push(collection);
        }
    }
    return result;
};

/**
 * Return the list of pics in a collection.
 *
 * @param collection
 * @return {Array}
 */
portret.getPics = function (collection) {
    var result = {};
    result.name = collection;
    result.pics = [];
    function walkDir(curPath) {
        var files = fs.readdirSync(curPath);
        for (var f in files) {
            var curFile = path.join(curPath, files[f]);
            if (fs.statSync(curFile).isFile() && portret.fileTypes.indexOf(path.extname(curFile).toLowerCase()) != -1) {
                result.pics.push(files[f]);
            } else if (fs.statSync(curFile).isDirectory()) {
                walkDir(curFile);
            }
        }
    }
    walkDir(path.join(portret.collectionPath, collection));
    result.count = result.pics.length;
    return result;
};
<commit_msg>fixed picture ordering<commit_after>var express = require('express');
var fs = require('fs');
var path = require('path');

var portret = {};
portret.collectionPath = "./collections/";
portret.fileTypes = [".jpg", ".jpeg", ".png", ".gif"];

var app = express();

// configure CORS
app.use(function(req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    next();
});

app.get('/collections', function (req, res, next) {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(portret.getCollections()));
});

app.get('/collection/:name', function (req, res, next) {
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify(portret.getPics(req.params.name)));
});

var server = app.listen(8081, function () {
   var host = server.address().address;
   var port = server.address().port;
   host = (host == "::") ? "127.0.0.1" : host;
   console.log("Portret REST API listening at http://%s:%s", host, port);
});

/**
 * Return a list of known collections.
 * @return {Array}
 */
portret.getCollections = function () {
    var result = [];
    var files = fs.readdirSync(portret.collectionPath);
    for (var f in files) {
        var curFile =  path.join(portret.collectionPath, files[f]);
        if (fs.statSync(curFile).isDirectory()) {
            var collection = {};
            collection.name = files[f];
            collection.count = portret.getPics(collection.name).count;
            result.push(collection);
        }
    }
    return result;
};

/**
 * Return the list of pics in a collection.
 *
 * @param collection
 * @return {Array}
 */
portret.getPics = function (collection) {
    var result = {},
        numberedFileNames = true;
    result.name = collection;
    result.pics = [];
    function walkDir(curPath) {
        var files = fs.readdirSync(curPath);
        for (var f in files) {
            var curFile = path.join(curPath, files[f]);
            if (fs.statSync(curFile).isFile() && portret.fileTypes.indexOf(path.extname(curFile).toLowerCase()) != -1) {
                numberedFileNames &= portret.isNumberedFileName(files[f]);
                result.pics.push(files[f]);
            } else if (fs.statSync(curFile).isDirectory()) {
                walkDir(curFile);
            }
        }
    }
    walkDir(path.join(portret.collectionPath, collection));
    result.count = result.pics.length;
    if (numberedFileNames) {
        console.log("Files in collection '%s' are numbered and will be played back in that order.", collection);
        result.pics.sort(portret.compareNumberedFileNames);
    }
    return result;
};

portret.isNumberedFileName = function (file) {
    var namepart = path.basename(file, path.extname(file));
    return (namepart.match(/^\d+$/) != null);
};

portret.compareNumberedFileNames = function (a, b) {
    var file_num_a = path.basename(a, path.extname(a));
    var file_num_b = path.basename(b, path.extname(b));
    return file_num_a - file_num_b;
};
<|endoftext|>


<commit_before>(function(root) {
  var Asteroids = root.Asteroids = (root.Asteroids || {});

  var DIM_Y = Asteroids.DIM_Y = 500;
  var DIM_X = Asteroids.DIM_X = 500;
  var FPS = 30;
  var ASTR_CNT = 10;

  // Actually seconds / frame..

  var Game = Asteroids.Game = function(ctx) {
    this.ctx = ctx;
    this.asteroids = this.addAsteroids(ASTR_CNT);
    this.ship = new Asteroids.Ship();
    this.bullets = [];
  }

  Game.prototype.addAsteroids = function(numAsteroids) {
    var asteroids = [];

    for (var i = 0; i < numAsteroids; i++) {
      asteroids.push(Asteroids.randomAsteroid(DIM_X, DIM_Y));
    }

    return asteroids;
  }

  Game.prototype.draw = function() {
    // this.ctx.clearRect(0, 0, DIM_X, DIM_Y);
    this.ctx.fillStyle = "black";
    this.ctx.fillRect(0,0, DIM_X, DIM_Y);

    this.ship.draw(this.ctx);

    for (var i = 0; i < this.bullets.length; i++) {
      this.bullets[i].draw(this.ctx);
    }

    for (var i = 0; i < this.asteroids.length; i++) {
      this.asteroids[i].draw(this.ctx);
    }

  }

  Game.prototype.checkCollisions = function() {
    var collision = false;

    for (var i = 0; i < this.asteroids.length; i++) {
      if (this.asteroids[i].isCollidedWith(this.ship)) {
        this.stop();
        alert("YOU CRASHED!");
      };
    }
  }

  Game.prototype.stop = function() {
    clearInterval(this.intervalID);
  }

  Game.prototype.move = function() {

    this.ship.move();

    for (var i = 0; i < this.bullets.length; i++) {
      this.bullets[i].move();
    }

    for (var i = 0; i < this.asteroids.length; i++) {
      this.asteroids[i].move();
    }
  }

  Game.prototype.step = function() {
    this.clearAsteroids();
    this.clearBullets();
    this.checkCollisions();
    this.draw();
    this.move();
  }

  Game.prototype.start = function() {
    this.bindKeyHandlers();
    game = this;
    this.intervalID = setInterval(game.step.bind(game), FPS);
  }

  Game.prototype.bindKeyHandlers = function() {
    var game = this;
    key("up", this.ship.power.bind(this.ship));
    key("down", this.ship.brake.bind(this.ship));
    key("left", this.ship.turnLeft.bind(this.ship));
    key("right", this.ship.turnRight.bind(this.ship));
    key("space", game.fireBullet.bind(game));
  }

  Game.prototype.fireBullet = function() {
    this.bullets.push(this.ship.fireBullet());
  }

  Game.prototype.clearBullets = function() {
    var validBullets = [];
    var validAsteroids = [];

    for(var i = 0; i < this.bullets.length; i++){
      if(this.isInBounds(this.bullets[i])){
        validBullets.push(this.bullets[i]);
      }
    }

    for(var i = 0; i < this.asteroids.length; i++){
      if(this.isInBounds(this.asteroids[i])){
        validAsteroids.push(this.asteroids[i]);
      }
    }

    this.bullets = validBullets;
    this.asteroids = validAsteroids;
  }

  Game.prototype.clearAsteroids = function() {
    // var validBullets = [];
    // var validAsteroids = [];
    if (this.asteroids.length > 0 && this.bullets.length > 0) {
      for(var i = 0; i < this.bullets.length; i++ ){
        for (var j = 0; j < this.asteroids.length; j++){
          if(this.bullets[i].isCollidedWith(this.asteroids[j])){
            this.asteroids[j].vel.mag = 0;
            this.asteroids[j].pos = [920, 920];
            this.bullets[i].vel.mag = 0;
            this.bullets[i].pos = [1000, 1000];
          }
        }
      }
      // for (var j = 0; j < this.asteroids.length; j++){ // 1 ast
      //   for(var i = 0; i < this.bullets.length; i++ ){ // 2 bullets
      //     if(!this.asteroids[j].isCollidedWith(this.bullets[i])){ // bul 1
      //       if (validAsteroids.indexOf(this.asteroids[j]) == -1) {
      //         validAsteroids.push(this.asteroids[j]);
      //       }
      //     }
      //   }
      // }
      //
      //
      // this.asteroids = validAsteroids;
      // this.bullets = validBullets;
    }
  }

  Game.prototype.isInBounds = function(obj){
    if(obj.pos[0] <= DIM_X && obj.pos[0] >= 0 &&
      obj.pos[1] <= DIM_Y && obj.pos[1] >= 0){
        return true;
    } else {
      return false;
    }
  }

})(this);<commit_msg>Removes comments<commit_after>(function(root) {
  var Asteroids = root.Asteroids = (root.Asteroids || {});

  var DIM_Y = Asteroids.DIM_Y = 500;
  var DIM_X = Asteroids.DIM_X = 500;
  var FPS = 30;
  var ASTR_CNT = 10;

  // Actually seconds / frame..

  var Game = Asteroids.Game = function(ctx) {
    this.ctx = ctx;
    this.asteroids = this.addAsteroids(ASTR_CNT);
    this.ship = new Asteroids.Ship();
    this.bullets = [];
  }

  Game.prototype.addAsteroids = function(numAsteroids) {
    var asteroids = [];

    for (var i = 0; i < numAsteroids; i++) {
      asteroids.push(Asteroids.randomAsteroid(DIM_X, DIM_Y));
    }

    return asteroids;
  }

  Game.prototype.draw = function() {
    this.ctx.fillStyle = "black";
    this.ctx.fillRect(0,0, DIM_X, DIM_Y);

    this.ship.draw(this.ctx);

    for (var i = 0; i < this.bullets.length; i++) {
      this.bullets[i].draw(this.ctx);
    }

    for (var i = 0; i < this.asteroids.length; i++) {
      this.asteroids[i].draw(this.ctx);
    }

  }

  Game.prototype.checkCollisions = function() {
    var collision = false;

    for (var i = 0; i < this.asteroids.length; i++) {
      if (this.asteroids[i].isCollidedWith(this.ship)) {
        this.stop();
        alert("YOU CRASHED!");
      };
    }
  }

  Game.prototype.stop = function() {
    clearInterval(this.intervalID);
  }

  Game.prototype.move = function() {

    this.ship.move();

    for (var i = 0; i < this.bullets.length; i++) {
      this.bullets[i].move();
    }

    for (var i = 0; i < this.asteroids.length; i++) {
      this.asteroids[i].move();
    }
  }

  Game.prototype.step = function() {
    this.clearAsteroids();
    this.clearBullets();
    this.checkCollisions();
    this.draw();
    this.move();
  }

  Game.prototype.start = function() {
    this.bindKeyHandlers();
    game = this;
    this.intervalID = setInterval(game.step.bind(game), FPS);
  }

  Game.prototype.bindKeyHandlers = function() {
    var game = this;
    key("up", this.ship.power.bind(this.ship));
    key("down", this.ship.brake.bind(this.ship));
    key("left", this.ship.turnLeft.bind(this.ship));
    key("right", this.ship.turnRight.bind(this.ship));
    key("space", game.fireBullet.bind(game));
  }

  Game.prototype.fireBullet = function() {
    this.bullets.push(this.ship.fireBullet());
  }

  Game.prototype.clearBullets = function() {
    var validBullets = [];
    var validAsteroids = [];

    for(var i = 0; i < this.bullets.length; i++){
      if(this.isInBounds(this.bullets[i])){
        validBullets.push(this.bullets[i]);
      }
    }

    for(var i = 0; i < this.asteroids.length; i++){
      if(this.isInBounds(this.asteroids[i])){
        validAsteroids.push(this.asteroids[i]);
      }
    }

    this.bullets = validBullets;
    this.asteroids = validAsteroids;
  }

  Game.prototype.clearAsteroids = function() {
    // var validBullets = [];
    // var validAsteroids = [];
    if (this.asteroids.length > 0 && this.bullets.length > 0) {
      for(var i = 0; i < this.bullets.length; i++ ){
        for (var j = 0; j < this.asteroids.length; j++){
          if(this.bullets[i].isCollidedWith(this.asteroids[j])){
            this.asteroids[j].vel.mag = 0;
            this.asteroids[j].pos = [920, 920];
            this.bullets[i].vel.mag = 0;
            this.bullets[i].pos = [1000, 1000];
          }
        }
      }
      // for (var j = 0; j < this.asteroids.length; j++){ // 1 ast
      //   for(var i = 0; i < this.bullets.length; i++ ){ // 2 bullets
      //     if(!this.asteroids[j].isCollidedWith(this.bullets[i])){ // bul 1
      //       if (validAsteroids.indexOf(this.asteroids[j]) == -1) {
      //         validAsteroids.push(this.asteroids[j]);
      //       }
      //     }
      //   }
      // }
      //
      //
      // this.asteroids = validAsteroids;
      // this.bullets = validBullets;
    }
  }

  Game.prototype.isInBounds = function(obj){
    if(obj.pos[0] <= DIM_X && obj.pos[0] >= 0 &&
      obj.pos[1] <= DIM_Y && obj.pos[1] >= 0){
        return true;
    } else {
      return false;
    }
  }

})(this);<|endoftext|>


<commit_before>'use strict';

(function($) {

    var throwError = function(msg) {
        throw new Error('Sign2Pay: ' + msg);
    }

    var Sign2Pay = (function (settings) {

        /**
         * Sign2Pay constructor
         *
         * @param object settings
         */

        function Sign2Pay(settings) {
            this.merchantId = settings.merchantId || throwError('No merchant id');
            this.token = settings.token || throwError('No token');
            this.baseUrl = settings.baseUrl || throwError('No base url');

            // Remove protocol from base url
            this.baseUrl = this.baseUrl.replace(/^http:/, '');

            if (settings.initialize) this.initializePayment();
        }

        /**
         * @var Default options
         */

        Sign2Pay.prototype.defaultOptions = {
            domain: "sign2pay.com",
            el: "#sign2pay"
        }

        /**
         * Initialize Sign2Pay transport with given options
         *
         * @param object options
         */
        Sign2Pay.prototype.initTransport = function(options) {
            window.sign2PayOptions = options;

            if (!this.scriptAttached) {
                this.scriptAttached = true;
                $('head').append('');
            }
        }

        /**
         * Fetches all payment related options
         *
         * @param function callback
         */

        Sign2Pay.prototype.fetchPaymentOptions = function(callback) {
            var self = this;

            $.ajax(this.baseUrl + 'sign2pay/payment/fetchPaymentOptions', {
                type: 'POST',
                dataType: 'json',
                success: function(options) {
                    var options = $.extend(self.defaultOptions, options, {
                        merchant_id: self.merchantId,
                        token: self.token
                    });

                    callback(options);
                },
                error: function(err) {
                    console.log(err);
                    throwError('Could not fetch payment options');
                }
            });
        }

        /**
         * Perform riskAssessment
         */

        Sign2Pay.prototype.riskAssessment = function() {
            var self = this;

            var callback = function(options) {
                options['success'] = function() {
                    // Disable the Sign2Pay payment method
                    $('input[name="payment[method]"][value="sign2pay"]').removeAttr('disabled');
                }

                self.initTransport(options);
            }

            this.fetchPaymentOptions(callback);
        };

        /**
         * Initialize payment
         */

        Sign2Pay.prototype.initializePayment = function() {
            var self = this;

            var unloadCallback = function() {
                return 'Leaving this screen might prevent you from completing this purchase.';
            };

            var closeCallback = function() {};

            var cancelCallback = function() {
                $(window).unbind('beforeunload', unloadCallback);
                window.location = self.baseUrl + "sign2pay/payment/cancel";
            };

            var callback = function(options) {
                options['launch'] = "on_load";
                options['map'] = {};

                options['success']  = function() {
                    var el = $(this.el).get(0);
                    $('.s2p-button-text', el).remove();
                    $('.s2p-button-banks', el)
                        .append('Pay with Sign2Pay')
                        .append('Cancel')
                        .children('.btn-cancel')
                        .on('click', function() {
                            cancelCallback();
                            return false;
                        });
                    $('.loading, .s2p-text', el).remove();
                };

                options['error']  = function() {
                    alert('There was a problem during Sign2Pay initialization. Your ref_id is ' + options['ref_id'] + '.');

                    closeCallback = cancelCallback;

                    var el = $(this.el).get(0);
                    $(".loading", el).hide();
                };

                options['close'] = function(a) {
                    closeCallback();
                };

                self.initTransport(options);
            };

            $(window).on('beforeunload', unloadCallback);
            this.fetchPaymentOptions(callback);
        }

        return Sign2Pay;
    })();

    $(window).load(function() {
        if (!s2pOptions || !s2pOptions['merchantId'] || !s2pOptions['token']) {
            throwError('The Sign2Pay Module is enabled, but you are missing required settings.');
        } else {
            window.sign2payPayment = new Sign2Pay(s2pOptions);
        }
    });

    window.initializeRiskAssessment = function() {
        var interval;
        interval = setInterval(function() {
            if (typeof window.sign2payPayment !== 'object') return;
            clearInterval(interval);

            // Perform risk assessment
            window.sign2payPayment.riskAssessment();

            // Disable the Sign2Pay payment method
            $('input[name="payment[method]"][value="sign2pay"]').attr('disabled', 'disabled');
        });
    };

})(jQuery.noConflict());
<commit_msg>Change checkout type to single in payment script on checkout page<commit_after>'use strict';

(function($) {

    var throwError = function(msg) {
        throw new Error('Sign2Pay: ' + msg);
    }

    var Sign2Pay = (function (settings) {

        /**
         * Sign2Pay constructor
         *
         * @param object settings
         */

        function Sign2Pay(settings) {
            this.merchantId = settings.merchantId || throwError('No merchant id');
            this.token = settings.token || throwError('No token');
            this.baseUrl = settings.baseUrl || throwError('No base url');

            // Remove protocol from base url
            this.baseUrl = this.baseUrl.replace(/^http:/, '');

            if (settings.initialize) this.initializePayment();
        }

        /**
         * @var Default options
         */

        Sign2Pay.prototype.defaultOptions = {
            domain: "sign2pay.com",
            el: "#sign2pay"
        }

        /**
         * Initialize Sign2Pay transport with given options
         *
         * @param object options
         */
        Sign2Pay.prototype.initTransport = function(options) {
            window.sign2PayOptions = options;

            if (!this.scriptAttached) {
                this.scriptAttached = true;
                $('head').append('');
            }
        }

        /**
         * Fetches all payment related options
         *
         * @param function callback
         */

        Sign2Pay.prototype.fetchPaymentOptions = function(callback) {
            var self = this;

            $.ajax(this.baseUrl + 'sign2pay/payment/fetchPaymentOptions', {
                type: 'POST',
                dataType: 'json',
                success: function(options) {
                    var options = $.extend(self.defaultOptions, options, {
                        merchant_id: self.merchantId,
                        token: self.token
                    });

                    callback(options);
                },
                error: function(err) {
                    console.log(err);
                    throwError('Could not fetch payment options');
                }
            });
        }

        /**
         * Perform riskAssessment
         */

        Sign2Pay.prototype.riskAssessment = function() {
            var self = this;

            var callback = function(options) {
                options['success'] = function() {
                    // Disable the Sign2Pay payment method
                    $('input[name="payment[method]"][value="sign2pay"]').removeAttr('disabled');
                };

                options['checkout_type'] = 'single';

                options['map'] = {
                    first_name: '[name="billing[firstname]"]',
                    last_name: '[name="billing[lastname]"]',
                    email: '[name="billing[email]"]',
                    address: '[name="billing[street][]"]',
                    postal_code: '[name="billing[postcode]"]',
                    city: '[name="billing[city]"]',
                    region: '[name="billing[region_id]"]',
                    country: '[name="billing[country_id]"]'
                };

                self.initTransport(options);
            }

            this.fetchPaymentOptions(callback);
        };

        /**
         * Initialize payment
         */

        Sign2Pay.prototype.initializePayment = function() {
            var self = this;

            var unloadCallback = function() {
                return 'Leaving this screen might prevent you from completing this purchase.';
            };

            var closeCallback = function() {};

            var cancelCallback = function() {
                $(window).unbind('beforeunload', unloadCallback);
                window.location = self.baseUrl + "sign2pay/payment/cancel";
            };

            var callback = function(options) {
                options['launch'] = "on_load";
                options['map'] = {};

                options['success']  = function() {
                    var el = $(this.el).get(0);
                    $('.s2p-button-text', el).remove();
                    $('.s2p-button-banks', el)
                        .append('Pay with Sign2Pay')
                        .append('Cancel')
                        .children('.btn-cancel')
                        .on('click', function() {
                            cancelCallback();
                            return false;
                        });
                    $('.loading, .s2p-text', el).remove();
                };

                options['error']  = function() {
                    alert('There was a problem during Sign2Pay initialization. Your ref_id is ' + options['ref_id'] + '.');

                    closeCallback = cancelCallback;

                    var el = $(this.el).get(0);
                    $(".loading", el).hide();
                };

                options['close'] = function(a) {
                    closeCallback();
                };

                self.initTransport(options);
            };

            $(window).on('beforeunload', unloadCallback);
            this.fetchPaymentOptions(callback);
        }

        return Sign2Pay;
    })();

    $(window).load(function() {
        if (!s2pOptions || !s2pOptions['merchantId'] || !s2pOptions['token']) {
            throwError('The Sign2Pay Module is enabled, but you are missing required settings.');
        } else {
            window.sign2payPayment = new Sign2Pay(s2pOptions);
        }
    });

    window.initializeRiskAssessment = function() {
        var interval;
        interval = setInterval(function() {
            if (typeof window.sign2payPayment !== 'object') return;
            clearInterval(interval);

            // Perform risk assessment
            window.sign2payPayment.riskAssessment();

            // Disable the Sign2Pay payment method
            $('input[name="payment[method]"][value="sign2pay"]').attr('disabled', 'disabled');
        });
    };

})(jQuery.noConflict());
<|endoftext|>


<commit_before>describe('MessageView', function() {
  var convo, message;

  before(function() {
    convo = new Whisper.Conversation({id: 'foo'});
    message = convo.messageCollection.add({
      conversationId: convo.id,
      body: 'hello world',
      type: 'outgoing',
      source: '+14158675309',
      received_at: Date.now()
    });

    return storage.put('number_id', '+18088888888.1');
  });

  it('should display the message text', function() {
    var view = new Whisper.MessageView({model: message}).render();
    assert.match(view.$el.text(), /hello world/);
  });

  it('should auto-update the message text', function() {
    var view = new Whisper.MessageView({model: message}).render();
    message.set('body', 'goodbye world');
    assert.match(view.$el.html(), /goodbye world/);
  });

  it('should have a nice timestamp', function() {
    var view = new Whisper.MessageView({model: message});
    message.set({'sent_at': Date.now() - 5000});
    view.render();
    assert.match(view.$el.html(), /now/);

    message.set({'sent_at': Date.now() - 60000});
    view.render();
    assert.match(view.$el.html(), /min/);

    message.set({'sent_at': Date.now() - 3600000});
    view.render();
    assert.match(view.$el.html(), /hour/);
  });
  it('should not imply messages are from the future', function() {
    var view = new Whisper.MessageView({model: message});
    message.set({'sent_at': Date.now() + 60000});
    view.render();
    assert.match(view.$el.html(), /now/);
  });

  it('should go away when the model is destroyed', function() {
    var view = new Whisper.MessageView({model: message});
    var div = $('<div>').append(view.$el);
    message.destroy();
    assert.strictEqual(div.find(view.$el).length, 0);
  });

  it('allows links', function() {
    var url = 'http://example.com';
    message.set('body', url);
    var view = new Whisper.MessageView({model: message});
    view.render();
    var link = view.$el.find('.body a');
    assert.strictEqual(link.length, 1);
    assert.strictEqual(link.text(), url);
    assert.strictEqual(link.attr('href'), url);
  });

  it('disallows xss', function() {
    var xss = '<script>alert("pwnd")</script>';
    message.set('body', xss);
    var view = new Whisper.MessageView({model: message});
    view.render();
    assert.include(view.$el.text(), xss); // should appear as escaped text
    assert.strictEqual(view.$el.find('script').length, 0); // should not appear as html
  });

  it('supports emoji', function() {
    message.set('body', 'I \u2764\uFE0F emoji!');
    var view = new Whisper.MessageView({model: message});
    view.render();
    var img = view.$el.find('.content img');
    assert.strictEqual(img.length, 1);
    assert.strictEqual(img.attr('src'), 'node_modules/emoji-datasource-apple/img/apple/64/2764-fe0f.png');
    assert.strictEqual(img.attr('title'), ':heart:');
    assert.strictEqual(img.attr('class'), 'emoji');
  });
});
<commit_msg>Clear database before message view tests<commit_after>describe('MessageView', function() {
  var convo, message;

  before(async (done) => {
    await clearDatabase();
    convo = new Whisper.Conversation({id: 'foo'});
    message = convo.messageCollection.add({
      conversationId: convo.id,
      body: 'hello world',
      type: 'outgoing',
      source: '+14158675309',
      received_at: Date.now(),
    });

    await storage.put('number_id', '+18088888888.1');
    done();
  });

  it('should display the message text', function() {
    var view = new Whisper.MessageView({model: message}).render();
    assert.match(view.$el.text(), /hello world/);
  });

  it('should auto-update the message text', function() {
    var view = new Whisper.MessageView({model: message}).render();
    message.set('body', 'goodbye world');
    assert.match(view.$el.html(), /goodbye world/);
  });

  it('should have a nice timestamp', function() {
    var view = new Whisper.MessageView({model: message});
    message.set({'sent_at': Date.now() - 5000});
    view.render();
    assert.match(view.$el.html(), /now/);

    message.set({'sent_at': Date.now() - 60000});
    view.render();
    assert.match(view.$el.html(), /min/);

    message.set({'sent_at': Date.now() - 3600000});
    view.render();
    assert.match(view.$el.html(), /hour/);
  });
  it('should not imply messages are from the future', function() {
    var view = new Whisper.MessageView({model: message});
    message.set({'sent_at': Date.now() + 60000});
    view.render();
    assert.match(view.$el.html(), /now/);
  });

  it('should go away when the model is destroyed', function() {
    var view = new Whisper.MessageView({model: message});
    var div = $('<div>').append(view.$el);
    message.destroy();
    assert.strictEqual(div.find(view.$el).length, 0);
  });

  it('allows links', function() {
    var url = 'http://example.com';
    message.set('body', url);
    var view = new Whisper.MessageView({model: message});
    view.render();
    var link = view.$el.find('.body a');
    assert.strictEqual(link.length, 1);
    assert.strictEqual(link.text(), url);
    assert.strictEqual(link.attr('href'), url);
  });

  it('disallows xss', function() {
    var xss = '<script>alert("pwnd")</script>';
    message.set('body', xss);
    var view = new Whisper.MessageView({model: message});
    view.render();
    assert.include(view.$el.text(), xss); // should appear as escaped text
    assert.strictEqual(view.$el.find('script').length, 0); // should not appear as html
  });

  it('supports emoji', function() {
    message.set('body', 'I \u2764\uFE0F emoji!');
    var view = new Whisper.MessageView({model: message});
    view.render();
    var img = view.$el.find('.content img');
    assert.strictEqual(img.length, 1);
    assert.strictEqual(img.attr('src'), 'node_modules/emoji-datasource-apple/img/apple/64/2764-fe0f.png');
    assert.strictEqual(img.attr('title'), ':heart:');
    assert.strictEqual(img.attr('class'), 'emoji');
  });
});
<|endoftext|>


<commit_before>//Constant Variables
var XMax = 400;
var YMax = 400;
var ZMax = 400;
var ZScalingFactor = .5;
var YScalingFactor = .3;

//Global Variables

//Player fort health (int)
var pFortHealth = 10;
//Enemy boss health (int)
var eBossHealth;
// materials (int)
var materials;

//Basic foot soldier
// x = int x axis
// y = int y axis
// z = int z axis
// speed = int movement speed
// health = int health
// def = int defense
// atk = int attack
// rng = int range
function stickMan(x, y, z, speed, health, def, atk, rng){
	this.x = x;
	this.y = y;
	this.z = z;
	this.speed = speed;
	this.health = health;
	this.def = def;
	this.atk = atk;
	this.rng = rng;
}

//Player Army
// pFootSoldiers = Array foot soldiers
// pTowerSoldiers = Array tower soldiers
// pTowerSupport = Array tower support
var pArmy = new Object;
	pArmy.pFootSoldiers = [];
	pArmy.pTowerSoldiers = [];
	pArmy.pTowerSupport = [];

//Enemy Army
// eFootSoldiers = Array foot soldiers
var eArmy = new Object;
	eArmy.eFootSoldiers = [];

// preload images
if (document.images)
{
	var img = new Array();
	img[0] = new Image();
	img[0].src = 'stickman.png';
}

function main_draw()
{
	var main_canvas = document.getElementById("main_screen");
	var context = main_canvas.getContext("2d");
	context.clearRect(0,0,XMax,YMax);

	var stick_image = new Image();
	stick_image.src = "stickman.png";
	context.drawImage(stick_image,200,200);
}

function god_draw()
{
	var god_canvas = document.getElementById("god_screen");
	var context = god_canvas.getContext("2d");
	context.clearRect(0,0,XMax,ZMax);

	var stick_image = new Image();
	stick_image.src = "stickman.png";
	context.drawImage(stick_image,100,100);
}

function draw_all()
{
	main_draw();
	god_draw();
}

//Calls draw function
//Checks game end condition
//Waits for step
function step()
{
	draw_all();
	if(pFortHealth > 0)
	{
		document.getElementById("result").innerHTML = "GAME OVER";
		document.getElementById("button").style.visibility = 'visible';
	}
	else
	{
		wait_for_step();
	}

}

//Timer til next draw
function wait_for_step()
{
	setTimeout('step()', 100);
}

//Main
function game()
{
	document.getElementById("button").style.visibility = 'hidden';
	wait_for_step();
}
<commit_msg>added soldier movement<commit_after>//Constant Variables
var XMax = 400;
var YMax = 400;
var ZMax = 400;
var ZScalingFactor = .5;
var YScalingFactor = .3;

//Global Variables

//Player fort health (int)
var pFortHealth = 10;
//Enemy boss health (int)
var eBossHealth;
// materials (int)
var materials;

//Basic foot soldier
// x = int x axis
// y = int y axis
// z = int z axis
// speed = int movement speed
// health = int health
// def = int defense
// atk = int attack
// rng = int range
function stickMan(x, y, z, speed, health, def, atk, rng){
	this.x = x;
	this.y = y;
	this.z = z;
	this.speed = speed;
	this.health = health;
	this.def = def;
	this.atk = atk;
	this.rng = rng;
}

//Player Army
// pFootSoldiers = Array foot soldiers
// pTowerSoldiers = Array tower soldiers
// pTowerSupport = Array tower support
var pArmy = new Object;
	pArmy.pFootSoldiers = [];
	pArmy.pTowerSoldiers = [];
	pArmy.pTowerSupport = [];

//Enemy Army
// eFootSoldiers = Array foot soldiers
var eArmy = new Object;
	eArmy.eFootSoldiers = [];

// preload images
if (document.images)
{
	var img = new Array();
	img[0] = new Image();
	img[0].src = 'stickman.png';
}

//
function move_soldiers()
{
	for (var i = 0; i < pArmy.pFootSoldiers.length; i++)
	{
		pArmy.pFootSoldiers[i].x += pArmy.pFootSoldiers[i].speed;
	}
}

function main_draw()
{
	var main_canvas = document.getElementById("main_screen");
	var context = main_canvas.getContext("2d");
	context.clearRect(0,0,XMax,YMax);

	for (var i = 0; i < pArmy.pFootSoldiers.length; i++)
	{
		var stick_image = new Image();
		stick_image.src = "stickman.png";
		context.drawImage(stick_image,pArmy.pFootSoldiers[i].x,pArmy.pFootSoldiers[i].y);
	}

}

function god_draw()
{
	var god_canvas = document.getElementById("god_screen");
	var context = god_canvas.getContext("2d");
	context.clearRect(0,0,XMax,ZMax);

	var stick_image = new Image();
	stick_image.src = "stickman.png";
	context.drawImage(stick_image,100,100);
}

function draw_all()
{
	main_draw();
	god_draw();
}

//Calls draw function
//Checks game end condition
//Waits for step
function step()
{
	move_soldiers();
	draw_all();
	if(pFortHealth <= 0)
	{
		document.getElementById("result").innerHTML = "GAME OVER";
		document.getElementById("button").style.visibility = 'visible';
	}
	else
	{
		wait_for_step();
	}

}

//Timer til next draw
function wait_for_step()
{
	setTimeout('step()', 50);
}

//Main
function game()
{
	document.getElementById("button").style.visibility = 'hidden';
	var soldier1 = new stickMan(50, 100, 50, 5, 10, 10, 5, 2);
	var soldier2 = new stickMan(50, 200, 50, 5, 10, 10, 5, 2);
	pArmy.pFootSoldiers.push(soldier1);
	pArmy.pFootSoldiers.push(soldier2);
	wait_for_step();
}
<|endoftext|>


<commit_before>'use strict'

var stringifySafe = require('json-stringify-safe')
var format = require('util').format  // eslint-disable-line no-unused-vars
var os = require('os')
var pid = process.pid
var hostname = os.hostname()

var levels = {
  'fatal': 60,
  'error': 50,
  'warn': 40,
  'info': 30,
  'debug': 20,
  'trace': 10
}

function pino (opts, stream) {
  if (opts && opts._writableState) {
    stream = opts
    opts = null
  }
  stream = stream || process.stdout
  opts = opts || {}

  var stringify = opts.safe !== false ? stringifySafe : JSON.stringify
  var name = opts.name
  var level
  var funcs = {}
  var result = {
    fatal: null,
    error: null,
    warn: null,
    info: null,
    debug: null,
    trace: null
  }
  var serializers = opts.serializers || {}

  for (var key in levels) {
    funcs[key] = genLogFunction(key)
  }

  Object.defineProperty(result, 'level', {
    enumerable: false,
    get: function () {
      return level
    },
    set: function (l) {
      level = levels[l]
      if (!level) {
        throw new Error('unkown level ' + l)
      }

      Object.keys(levels).forEach(function (key) {
        if (level <= levels[key]) {
          result[key] = funcs[key]
        } else {
          result[key] = noop
        }
      })
    }
  })

  result.level = opts.level || 'info'

  return result

  function genLogFunction (key) {
    var level = levels[key]
    return function (a, b, c, d, e, f, g, h, i, j, k) {
      var base = 0
      var obj = null
      var params = null
      var msg
      if (Object(a) === a) {
        obj = a
        params = [b, c, d, e, f, g, h, i, j, k]
        base = 1

        if (obj.method && obj.headers && obj.socket) {
          obj = mapHttpRequest(obj)
        } else if (obj.statusCode) {
          obj = mapHttpResponse(obj)
        }
      } else {
        params = [a, b, c, d, e, f, g, h, i, j, k]
      }
      if ((params.length = arguments.length - base) > 0) {
        msg = format.apply(null, params)
      }

      stream.write(asJson(obj, msg, level))
    }
  }

  function asJson (obj, msg, num) { // eslint-disable-line no-unused-vars
    if (!msg && obj instanceof Error) {
      msg = obj.message
    }
    var data = message(num, msg)
    var value
    if (obj) {
      if (obj instanceof Error) {
        data += ',"type":"Error","stack":' + stringify(obj.stack)
      } else {
        for (var key in obj) {
          value = obj[key]
          if (obj.hasOwnProperty(key) && value !== undefined) {
            value = serializers[key] ? serializers[key](value) : value
            data += ',"' + key + '":' + stringify(value)
          }
        }
      }
    }
    return data + '}\n'
  }

  // returns string json with final brace omitted
  // the final brace is added by asJson
  function message (level, msg) {
    return '{"pid":' + pid + ',' +
      (typeof hostname === 'undefined' ? '' : '"hostname":"' + hostname + '",') +
      (typeof name === 'undefined' ? '' : '"name":"' + name + '",') +
      '"level":' + level + ',' +
      (typeof msg === 'undefined' ? '' : '"msg":"' + (msg && msg.toString()) + '",') +
      '"time":"' + (new Date()).toISOString() + '",' +
      '"v":' + 0
  }
}

function noop () {}

function mapHttpRequest (req) {
  return {
    req: asReqValue(req)
  }
}

function mapHttpResponse (res) {
  return {
    res: asResValue(res)
  }
}

function asReqValue (req) {
  return {
    method: req.method,
    url: req.url,
    headers: req.headers,
    remoteAddress: req.connection.remoteAddress,
    remotePort: req.connection.remotePort
  }
}

function asResValue (res) {
  return {
    statusCode: res.statusCode,
    header: res._header
  }
}

module.exports = pino

module.exports.stdSerializers = {
  req: asReqValue,
  res: asResValue
}
<commit_msg>Removed eslint comments<commit_after>'use strict'

var stringifySafe = require('json-stringify-safe')
var format = require('util').format
var os = require('os')
var pid = process.pid
var hostname = os.hostname()

var levels = {
  'fatal': 60,
  'error': 50,
  'warn': 40,
  'info': 30,
  'debug': 20,
  'trace': 10
}

function pino (opts, stream) {
  if (opts && opts._writableState) {
    stream = opts
    opts = null
  }
  stream = stream || process.stdout
  opts = opts || {}

  var stringify = opts.safe !== false ? stringifySafe : JSON.stringify
  var name = opts.name
  var level
  var funcs = {}
  var result = {
    fatal: null,
    error: null,
    warn: null,
    info: null,
    debug: null,
    trace: null
  }
  var serializers = opts.serializers || {}

  for (var key in levels) {
    funcs[key] = genLogFunction(key)
  }

  Object.defineProperty(result, 'level', {
    enumerable: false,
    get: function () {
      return level
    },
    set: function (l) {
      level = levels[l]
      if (!level) {
        throw new Error('unkown level ' + l)
      }

      Object.keys(levels).forEach(function (key) {
        if (level <= levels[key]) {
          result[key] = funcs[key]
        } else {
          result[key] = noop
        }
      })
    }
  })

  result.level = opts.level || 'info'

  return result

  function genLogFunction (key) {
    var level = levels[key]
    return function (a, b, c, d, e, f, g, h, i, j, k) {
      var base = 0
      var obj = null
      var params = null
      var msg
      if (Object(a) === a) {
        obj = a
        params = [b, c, d, e, f, g, h, i, j, k]
        base = 1

        if (obj.method && obj.headers && obj.socket) {
          obj = mapHttpRequest(obj)
        } else if (obj.statusCode) {
          obj = mapHttpResponse(obj)
        }
      } else {
        params = [a, b, c, d, e, f, g, h, i, j, k]
      }
      if ((params.length = arguments.length - base) > 0) {
        msg = format.apply(null, params)
      }

      stream.write(asJson(obj, msg, level))
    }
  }

  function asJson (obj, msg, num) {
    if (!msg && obj instanceof Error) {
      msg = obj.message
    }
    var data = message(num, msg)
    var value
    if (obj) {
      if (obj instanceof Error) {
        data += ',"type":"Error","stack":' + stringify(obj.stack)
      } else {
        for (var key in obj) {
          value = obj[key]
          if (obj.hasOwnProperty(key) && value !== undefined) {
            value = serializers[key] ? serializers[key](value) : value
            data += ',"' + key + '":' + stringify(value)
          }
        }
      }
    }
    return data + '}\n'
  }

  // returns string json with final brace omitted
  // the final brace is added by asJson
  function message (level, msg) {
    return '{"pid":' + pid + ',' +
      (typeof hostname === 'undefined' ? '' : '"hostname":"' + hostname + '",') +
      (typeof name === 'undefined' ? '' : '"name":"' + name + '",') +
      '"level":' + level + ',' +
      (typeof msg === 'undefined' ? '' : '"msg":"' + (msg && msg.toString()) + '",') +
      '"time":"' + (new Date()).toISOString() + '",' +
      '"v":' + 0
  }
}

function noop () {}

function mapHttpRequest (req) {
  return {
    req: asReqValue(req)
  }
}

function mapHttpResponse (res) {
  return {
    res: asResValue(res)
  }
}

function asReqValue (req) {
  return {
    method: req.method,
    url: req.url,
    headers: req.headers,
    remoteAddress: req.connection.remoteAddress,
    remotePort: req.connection.remotePort
  }
}

function asResValue (res) {
  return {
    statusCode: res.statusCode,
    header: res._header
  }
}

module.exports = pino

module.exports.stdSerializers = {
  req: asReqValue,
  res: asResValue
}
<|endoftext|>


<commit_before>/**
 * Created by crispin on 3/06/16.
 */
var game = new Phaser.Game(800, 800, Phaser.AUTO, 'div');
var goodGuys = [];
var scale = 7;
//takes grid [x, y] returns game [x, y]
var getGridCoords  = function(x, y){
	if (x > map.width || y > map.width || x <= 0 || y <= 0) {
		throw RangeError("x or y is too big or too small" + x + ' ' + y);
	}
	return [bg.x + (map.tileWidth * scale * (x - 1)), bg.y + (map.tileHeight * scale * (y - 1))];
};
var loadState = {
	preload: function () {
		game.time.advancedTiming = true
		game.stage.smoothed = false;
		game.antialias = false;
		game.load.tilemap('arena', 'assets/battlemap.json', null, Phaser.Tilemap.TILED_JSON);
		game.load.image('tileset', 'assets/tileset.png');
		game.load.image('archer', 'assets/archer.png');
			},
	create: function () {
		game.stage.backgroundColor = "#4488AA";
		game.state.start('play');
	}
};

var playState = {
	create: function () {
		map = game.add.tilemap('arena');
		map.addTilesetImage('Toen', 'tileset');
		bg = map.createLayer('Background');
		fg = map.createLayer('Foreground');

		fps = game.add.text(game.world.centerX + (game.world.width / 2.3), game.world.centerY - (game.world.height / 2.3), 00 + " FPS", {
			font: "12px Arial"
		});

		cursors = game.input.keyboard.createCursorKeys();

		person = game.add.sprite(0, 0, 'archer');
		person.gridX = 1;
		person.gridY = 1;
		person.inputEnabled = true;

		bg.scale = {x:scale, y:scale};
		fg.scale = {x:scale, y:scale};

		person.scale = {x: scale, y: scale};

		bg.fixedToCamera = false;

		bg.x = this.world.centerX - (map.widthInPixels * scale / 2);
		bg.y = this.world.centerY - (map.heightInPixels * scale / 2);

		fg.fixedToCamera = false;

		fg.x = this.world.centerX - (map.widthInPixels * scale / 2);
		fg.y = this.world.centerY - (map.heightInPixels * scale / 2);
		[person.x,person.y] = getGridCoords(person.gridX, person.gridY);

	},
	update: function () {
		// fps.setText(game.time.fps + " FPS");
		if (cursors.up.isDown){
			if (!person.gridY - 1 > map.width || !person.gridY - 1 <= 0) {
			person.gridY--; }
			cursors.up.reset();
		}
		if (cursors.down.isDown){
			if (!person.gridY + 1 > map.width || !person.gridY + 1 <= 0) {
			person.gridY++; }
			cursors.down.reset();
		}
		if (cursors.left.isDown){
			if (!person.gridX - 1 > map.width || !person.gridX - 1 <= 0) {
				person.gridX--;
			}
			cursors.left.reset();
		}
		if (cursors.right.isDown) {
			if (!person.gridX + 1 > map.width || !person.gridX + 1 <= 0) {
			person.gridX++; }
			cursors.right.reset();
		}
		[person.x,person.y] = getGridCoords(person.gridX, person.gridY);
	}
};

game.state.add('load', loadState);
game.state.add('play', playState);

game.state.start('load');<commit_msg>You now can't walk off the world.<commit_after>/**
 * Created by crispin on 3/06/16.
 */
var game = new Phaser.Game(800, 800, Phaser.AUTO, 'div');
var goodGuys = [];
var scale = 7;
//takes grid [x, y] returns game [x, y]
var getGridCoords  = function(x, y){
	if (x > map.width || y > map.height || x <= 0 || y <= 0) {
		throw RangeError("x or y is too big or too small: x: " + x + ', y: ' + y);
	}
	return [bg.x + (map.tileWidth * scale * (x - 1)), bg.y + (map.tileHeight * scale * (y - 1))];
};
var loadState = {
	preload: function () {
		game.time.advancedTiming = true
		game.stage.smoothed = false;
		game.antialias = false;
		game.load.tilemap('arena', 'assets/battlemap.json', null, Phaser.Tilemap.TILED_JSON);
		game.load.image('tileset', 'assets/tileset.png');
		game.load.image('archer', 'assets/archer.png');
			},
	create: function () {
		game.stage.backgroundColor = "#4488AA";
		game.state.start('play');
	}
};

var playState = {
	create: function () {
		map = game.add.tilemap('arena');
		map.addTilesetImage('Toen', 'tileset');
		bg = map.createLayer('Background');
		fg = map.createLayer('Foreground');

		fps = game.add.text(game.world.centerX + (game.world.width / 2.3), game.world.centerY - (game.world.height / 2.3), 00 + " FPS", {
			font: "12px Arial"
		});

		cursors = game.input.keyboard.createCursorKeys();
		space = game.input.keyboard.addKey(Phaser.KeyCode.SPACEBAR);

		person = game.add.sprite(0, 0, 'archer');
		person.gridX = 1;
		person.gridY = 1;
		person.inputEnabled = true;

		bg.scale = {x:scale, y:scale};
		fg.scale = {x:scale, y:scale};

		person.scale = {x: scale, y: scale};

		bg.fixedToCamera = false;

		bg.x = this.world.centerX - (map.widthInPixels * scale / 2);
		bg.y = this.world.centerY - (map.heightInPixels * scale / 2);

		fg.fixedToCamera = false;

		fg.x = this.world.centerX - (map.widthInPixels * scale / 2);
		fg.y = this.world.centerY - (map.heightInPixels * scale / 2);
		[person.x,person.y] = getGridCoords(person.gridX, person.gridY);

	},
	update: function () {
		fps.setText(game.time.fps + " FPS");
		if (cursors.up.isDown){
			if (person.gridY - 1 > 0) {
				person.gridY--; }
			cursors.up.reset();
		}
		if (cursors.down.isDown){
			if (person.gridY + 1 <= map.height) {
				person.gridY++; }
			cursors.down.reset();
		}
		if (cursors.left.isDown){
			if (person.gridX - 1 > 0) {
				person.gridX--; }
			cursors.left.reset();
		}
		if (cursors.right.isDown) {
			if (person.gridX + 1 <= map.width) {
				person.gridX++; }
			cursors.right.reset();
		}
		[person.x,person.y] = getGridCoords(person.gridX, person.gridY);
	}
};

game.state.add('load', loadState);
game.state.add('play', playState);

game.state.start('load');<|endoftext|>