<commit_before>// html5media enables <video> and <audio> tags in all major browsers
// External File: http://api.html5media.info/1.1.8/html5media.min.js

// Add user agent as an attribute on the  tag...
// Inspiration: http://css-tricks.com/ie-10-specific-styles/
var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform);

jQuery(function ($) {
    var supportsAudio = !!document.createElement('audio').canPlayType;
    if (supportsAudio) {
        var index = 0,
            playing = false,
            mediaPath = 'https://s3.us-east-2.amazonaws.com/sermons.cityhillchurch.org/Sermons/',
            extension = '',
            tracks = [{
                "date": "Nov 5, 2017",
                "passage": "Hebrews 10:19-25 'The Five Solas: Solus Christus, Christ Alone'",
                "speaker": "Pastor Robin Cho",
                "length": "38:46",
                "file": "Solus+Christus+Hebrews+10_19-25"
            }, {
                "date": "Oct 29, 2017",
                "passage": "Roman 4:1-8 'The Five Solas: Sola Fide, Faith Alone'",
                "speaker": "Pastor Robin Cho",
                "length": "48:04",
                "file": "Romans+4_1-8"
            }, {
                "date": "Oct 22, 2017",
                "passage": "2 Timothy 3:16-17 'The Five Solas: Sola Scriptura, Scripture Alone'",
                "speaker": "Pastor Steven Jon (Guest Preacher)",
                "length": "31:19",
                "file": "New+Recording+4"
            }, {
                "date": "Oct 15, 2017",
                "passage": "Ephesians 2:1-10 'The Five Solas: Sola Gratia, By Grace Alone'",
                "speaker": "Pastor Robin Cho",
                "length": "52:31",
                "file": "Ephesians+21-10"
            }, {
                "date": "Oct 8, 2017",
                "passage": "Mark 4:10-13; 21-25 'The Purpose of Parables'",
                "speaker": "Pastor Robin Cho",
                "length": "51:08",
                "file": "Mark+4_10-13%3B+21-25"
            }, {
                "date": "Oct 1, 2017",
                "passage": "Mark 4:1-20 'The Parable of the Soil'",
                "speaker": "Pastor Robin Cho",
                "length": "48:41",
                "file": "Mark+4_1-20"
            }, {
                "date": "Sept 24, 2017",
                "passage": "Mark 3:31-35 'God's Family'",
                "speaker": "Pastor Robin Cho",
                "length": "39:33",
                "file": "Mark+3_31-35"
            }, {
                "date": "Sept 10, 2017",
                "passage": "Mark 3:20-30 'The Stronger One'",
                "speaker": "Pastor Robin Cho",
                "length": "42:49",
                "file": "Mark+3_20-30"
            }, {
                "date": "Sept 3, 2017",
                "passage": "Ephesians 1:3-14 'Union With Christ'",
                "speaker": "Pastor Stephen Jon (Guest Preacher)",
                "length": "24:33",
                "file": "Ephesians+13-14"
            }, {
                "date": "Aug 27, 2017",
                "passage": "Jeremiah 12:7-17 'Hope For the Nations'",
                "speaker": "Pastor Robin Cho",
                "length": "49:09",
                "file": "Jeremiah+12_7-17"
            }, {
                "date": "Aug 20, 2017",
                "passage": "Jeremiah 12:1-6 'What's Going On?'",
                "speaker": "Pastor Robin Cho",
                "length": "44:30",
                "file": "Jeremiah+12_1-6"
            }, {
                "date": "Aug 13, 2017",
                "passage": "2 Corinthians 1:3-11 'The God of all Comfort'",
                "speaker": "Pastor Robin Cho",
                "length": "47:22",
                "file": "2+Corinthians+1_3-11"
            }, {
                "date": "Aug 6, 2017",
                "passage": "Psalm 119:9-16 'Storing Up'",
                "speaker": "Pastor Robin Cho",
                "length": "51:47",
                "file": "Psalm+119_9-16"
            }, {
                "date": "July 30, 2017",
                "passage": "Mark 3:7-19 'Jesus and His Apostles'",
                "speaker": "Pastor Robin Cho",
                "length": "39:57",
                "file": "Mark+3_7-19"
            }, {
                "date": "July 16, 2017",
                "passage": "Mark 3:1-6 'Healing on the Sabbath'",
                "speaker": "Pastor Robin Cho",
                "length": "41:28",
                "file": "Mark+3_1-6"
            }, {
                "date": "July 9, 2017",
                "passage": "Mark 2:23-28 'Lord of the Sabbath'",
                "speaker": "Pastor Robin Cho",
                "length": "41:45",
                "file": "Mark+2_23-28"
            }, {
                "date": "July 2, 2017",
                "passage": "Mark 2:18-22 'True Religion'",
                "speaker": "Pastor Robin Cho",
                "length": "38:19",
                "file": "Mark+2_18-22"
            }, {
                "date": "June 25, 2017",
                "passage": "Mark 2:15-17 'An Invitation To Sinners'",
                "speaker": "Pastor Robin Cho",
                "length": "38:09",
                "file": "Mark+2_15-17"
            }, {
                "date": "May 28, 2017",
                "passage": "Mark 2:13-14 'His Will To Call You'",
                "speaker": "Pastor Robin Cho",
                "length": "30:35",
                "file": "Mark+2_13-14"
            }, {
                "date": "May 7, 2017",
                "passage": "Colossians 4:2-6 'Downtime'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "41:14",
                "file": "Downtime"
            }, {
                "date": "April 30, 2017",
                "passage": "Matthew 5:43-48 'Why do we love our enemies'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "33:23",
                "file": "Matthew+5_43-48"
            }, {
                "date": "April 23, 2017",
                "passage": "Mark 2:1-12 'The Forgiveness of Sin'",
                "speaker": "Pastor Robin Cho",
                "length": "33:23",
                "file": "Mark+2_1-12"
            }, {
                "date": "April 17, 2017",
                "passage": "Mark 1:40-45 'The Spritual Leper'",
                "speaker": "Pastor Robin Cho",
                "length": "30:24",
                "file": "Mark+1_40-45"
            }, {
                "date": "April 9, 2017",
                "passage": "Mark 1:35-39 'The Priority of Jesus'",
                "speaker": "Pastor Robin Cho",
                "length": "37:12",
                "file": "Mark+1_35-39"
            }, {
                "date": "April 2, 2017",
                "passage": "1 Peter 2:11-12 'As a People out of this World'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "48:09",
                "file": "1+Peter+2_11-12"
            }, {
                "date": "Mar 26, 2017",
                "passage": "Galatians 6:1-10 'Bearing One Another's Burdens'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "40:39",
                "file": "Galatians+6_1-10"
            },  {
                "date": "Mar 19, 2017",
                "passage": "Galatians 5:1-6 'Avoid the Sewage and Enjoy the Spring'",
                "speaker": "Pastor Sam Kang (Guest Preacher)",
                "length": "34:58",
                "file": "Galatians+5_1-6"
            }, {
                "date": "Mar 12, 2017",
                "passage": "Mark 1:29-34 'The Healer'",
                "speaker": "Pastor Robin Cho",
                "length": "37:22",
                "file": "March+1_29-34"
            }, {
                "date": "Mar 5, 2017",
                "passage": "Mark 1:21-28 'The Holy One Of God'",
                "speaker": "Pastor Robin Cho",
                "length": "27:03",
                "file": "The+Holy+One+of+God+-+Mark+1_21-28"
            }, {
                "date": "Feb 26, 2017",
                "passage": "Exodus 7:1-13 'Optimism is Sharing the Gospel to Hardened Hearts'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "44:00",
                "file": "Exodus+7_1-13"
            }, {
                "date": "Feb 19, 2017",
                "passage": "Mark 1:16-20 'Fishers of Men'",
                "speaker": "Pastor Robin Cho",
                "length": "32:27",
                "file": "Mark+1_16-20"
            }, {
                "date": "Feb 12, 2017",
                "passage": "Mark 1:14-15 'What Jesus First Preached'",
                "speaker": "Paster Robin Cho",
                "length": "40:37",
                "file": "Mark+1_14-15"
            }, {
                "date": "Feb 5, 2017",
                "passage": "Daniel 6 'The Lion's Den'",
                "speaker": "Pastor Stephen Jon (Guest Preacher)",
                "length": "49:46",
                "file": "Daniel+6+Stephen+Jon"
            }, {
                "date": "Jan 29, 2017",
                "passage": "Mark 1:12-13 'Wilderness Qualified'",
                "speaker": "Pastor Robin Cho",
                "length": "37:54",
                "file": "Jan+29+Mark+1_12-13"
            }, {
                "date": "Jan 22, 2017",
                "passage": "Mark 1:9-11 'Vicarious Christ'",
                "speaker": "Pastor Robin Cho",
                "length": "34:21",
                "file": "Jan+22+Mark+1_9-11"
            }],
            buildPlaylist = $.each(tracks, function(key, value) {
                var trackNumber = key+1,
                    trackDate = value.date,
                    trackPassage = value.passage,
                    trackSpeaker = value.speaker,
                    trackLength = value.length;
                if (trackNumber.toString().length === 1) {
                    trackNumber = '0' + trackNumber;
                } else {
                    trackNumber = '' + trackNumber;
                }
                $('#plList').append('

' +
                trackNumber + '.

' +
                trackPassage + '
' + trackSpeaker + ' - ' + trackDate +
                '

' + trackLength + '

');
            }),
            trackCount = tracks.length,
            npAction = $('#npAction'),
            npTitle = $('#npTitle'),
            audio = $('#audio1').bind('play', function () {
                playing = true;
                npAction.text('Now Playing...');
            }).bind('pause', function () {
                playing = false;
                npAction.text('Paused...');
            }).bind('ended', function () {
                npAction.text('Paused...');
                if ((index + 1) < trackCount) {
                    index++;
                    loadTrack(index);
                    audio.play();
                } else {
                    audio.pause();
                    index = 0;
                    loadTrack(index);
                }
            }).get(0),
            btnPrev = $('#btnPrev').click(function () {
                if ((index - 1) > -1) {
                    index--;
                    loadTrack(index);
                    if (playing) {
                        audio.play();
                    }
                } else {
                    audio.pause();
                    index = 0;
                    loadTrack(index);
                }
            }),
            btnNext = $('#btnNext').click(function () {
                if ((index + 1) < trackCount) {
                    index++;
                    loadTrack(index);
                    if (playing) {
                        audio.play();
                    }
                } else {
                    audio.pause();
                    index = 0;
                    loadTrack(index);
                }
            }),
            li = $('#plList li').click(function () {
                var id = parseInt($(this).index());
                if (id !== index) {
                    playTrack(id);
                }
            }),
            loadTrack = function (id) {
                $('.plSel').removeClass('plSel');
                $('#plList li:eq(' + id + ')').addClass('plSel');
                npTitle.text(tracks[id].passage);
                index = id;
                audio.src = mediaPath + tracks[id].file + extension;
            },
            playTrack = function (id) {
                loadTrack(id);
                audio.play();
            };
        extension = audio.canPlayType('audio/mpeg') ? '.m4a' : audio.canPlayType('audio/ogg') ? '.ogg' : audio.canPlayType('audio/mp4') ? '.mp4a' : '';
        loadTrack(index);
    }
});
<commit_msg>Update playlist.js<commit_after>// html5media enables <video> and <audio> tags in all major browsers
// External File: http://api.html5media.info/1.1.8/html5media.min.js

// Add user agent as an attribute on the  tag...
// Inspiration: http://css-tricks.com/ie-10-specific-styles/
var b = document.documentElement;
b.setAttribute('data-useragent', navigator.userAgent);
b.setAttribute('data-platform', navigator.platform);

jQuery(function ($) {
    var supportsAudio = !!document.createElement('audio').canPlayType;
    if (supportsAudio) {
        var index = 0,
            playing = false,
            mediaPath = 'https://s3.us-east-2.amazonaws.com/sermons.cityhillchurch.org/Sermons/',
            extension = '',
            tracks = [{
                "date": "Nov 19, 2017",
                "passage": "1 Thessalonians 5:16-18; Psalm 95:1-8 'Thanksgiving On Repeat'",
                "speaker": "Pastor Robin Cho",
                "length": "35:02",
                "file": "1+Thessalonians+5_16-18%3B+Psalm+95_1-8"
            }, {
                "date": "Nov 12, 2017",
                "passage": "John 11:17-40 'The Five Solas: Soli Deo Gloria, Glory To God Alone'",
                "speaker": "Pastor Pastor Sam Kang (Guest Preacher)",
                "length": "56:03",
                "file": "A+Glory+Witnessed"
            }, {
                "date": "Nov 5, 2017",
                "passage": "Hebrews 10:19-25 'The Five Solas: Solus Christus, Christ Alone'",
                "speaker": "Pastor Robin Cho",
                "length": "38:46",
                "file": "Solus+Christus+Hebrews+10_19-25"
            }, {
                "date": "Oct 29, 2017",
                "passage": "Roman 4:1-8 'The Five Solas: Sola Fide, Faith Alone'",
                "speaker": "Pastor Robin Cho",
                "length": "48:04",
                "file": "Romans+4_1-8"
            }, {
                "date": "Oct 22, 2017",
                "passage": "2 Timothy 3:16-17 'The Five Solas: Sola Scriptura, Scripture Alone'",
                "speaker": "Pastor Steven Jon (Guest Preacher)",
                "length": "31:19",
                "file": "New+Recording+4"
            }, {
                "date": "Oct 15, 2017",
                "passage": "Ephesians 2:1-10 'The Five Solas: Sola Gratia, By Grace Alone'",
                "speaker": "Pastor Robin Cho",
                "length": "52:31",
                "file": "Ephesians+21-10"
            }, {
                "date": "Oct 8, 2017",
                "passage": "Mark 4:10-13; 21-25 'The Purpose of Parables'",
                "speaker": "Pastor Robin Cho",
                "length": "51:08",
                "file": "Mark+4_10-13%3B+21-25"
            }, {
                "date": "Oct 1, 2017",
                "passage": "Mark 4:1-20 'The Parable of the Soil'",
                "speaker": "Pastor Robin Cho",
                "length": "48:41",
                "file": "Mark+4_1-20"
            }, {
                "date": "Sept 24, 2017",
                "passage": "Mark 3:31-35 'God's Family'",
                "speaker": "Pastor Robin Cho",
                "length": "39:33",
                "file": "Mark+3_31-35"
            }, {
                "date": "Sept 10, 2017",
                "passage": "Mark 3:20-30 'The Stronger One'",
                "speaker": "Pastor Robin Cho",
                "length": "42:49",
                "file": "Mark+3_20-30"
            }, {
                "date": "Sept 3, 2017",
                "passage": "Ephesians 1:3-14 'Union With Christ'",
                "speaker": "Pastor Stephen Jon (Guest Preacher)",
                "length": "24:33",
                "file": "Ephesians+13-14"
            }, {
                "date": "Aug 27, 2017",
                "passage": "Jeremiah 12:7-17 'Hope For the Nations'",
                "speaker": "Pastor Robin Cho",
                "length": "49:09",
                "file": "Jeremiah+12_7-17"
            }, {
                "date": "Aug 20, 2017",
                "passage": "Jeremiah 12:1-6 'What's Going On?'",
                "speaker": "Pastor Robin Cho",
                "length": "44:30",
                "file": "Jeremiah+12_1-6"
            }, {
                "date": "Aug 13, 2017",
                "passage": "2 Corinthians 1:3-11 'The God of all Comfort'",
                "speaker": "Pastor Robin Cho",
                "length": "47:22",
                "file": "2+Corinthians+1_3-11"
            }, {
                "date": "Aug 6, 2017",
                "passage": "Psalm 119:9-16 'Storing Up'",
                "speaker": "Pastor Robin Cho",
                "length": "51:47",
                "file": "Psalm+119_9-16"
            }, {
                "date": "July 30, 2017",
                "passage": "Mark 3:7-19 'Jesus and His Apostles'",
                "speaker": "Pastor Robin Cho",
                "length": "39:57",
                "file": "Mark+3_7-19"
            }, {
                "date": "July 16, 2017",
                "passage": "Mark 3:1-6 'Healing on the Sabbath'",
                "speaker": "Pastor Robin Cho",
                "length": "41:28",
                "file": "Mark+3_1-6"
            }, {
                "date": "July 9, 2017",
                "passage": "Mark 2:23-28 'Lord of the Sabbath'",
                "speaker": "Pastor Robin Cho",
                "length": "41:45",
                "file": "Mark+2_23-28"
            }, {
                "date": "July 2, 2017",
                "passage": "Mark 2:18-22 'True Religion'",
                "speaker": "Pastor Robin Cho",
                "length": "38:19",
                "file": "Mark+2_18-22"
            }, {
                "date": "June 25, 2017",
                "passage": "Mark 2:15-17 'An Invitation To Sinners'",
                "speaker": "Pastor Robin Cho",
                "length": "38:09",
                "file": "Mark+2_15-17"
            }, {
                "date": "May 28, 2017",
                "passage": "Mark 2:13-14 'His Will To Call You'",
                "speaker": "Pastor Robin Cho",
                "length": "30:35",
                "file": "Mark+2_13-14"
            }, {
                "date": "May 7, 2017",
                "passage": "Colossians 4:2-6 'Downtime'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "41:14",
                "file": "Downtime"
            }, {
                "date": "April 30, 2017",
                "passage": "Matthew 5:43-48 'Why do we love our enemies'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "33:23",
                "file": "Matthew+5_43-48"
            }, {
                "date": "April 23, 2017",
                "passage": "Mark 2:1-12 'The Forgiveness of Sin'",
                "speaker": "Pastor Robin Cho",
                "length": "33:23",
                "file": "Mark+2_1-12"
            }, {
                "date": "April 17, 2017",
                "passage": "Mark 1:40-45 'The Spritual Leper'",
                "speaker": "Pastor Robin Cho",
                "length": "30:24",
                "file": "Mark+1_40-45"
            }, {
                "date": "April 9, 2017",
                "passage": "Mark 1:35-39 'The Priority of Jesus'",
                "speaker": "Pastor Robin Cho",
                "length": "37:12",
                "file": "Mark+1_35-39"
            }, {
                "date": "April 2, 2017",
                "passage": "1 Peter 2:11-12 'As a People out of this World'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "48:09",
                "file": "1+Peter+2_11-12"
            }, {
                "date": "Mar 26, 2017",
                "passage": "Galatians 6:1-10 'Bearing One Another's Burdens'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "40:39",
                "file": "Galatians+6_1-10"
            },  {
                "date": "Mar 19, 2017",
                "passage": "Galatians 5:1-6 'Avoid the Sewage and Enjoy the Spring'",
                "speaker": "Pastor Sam Kang (Guest Preacher)",
                "length": "34:58",
                "file": "Galatians+5_1-6"
            }, {
                "date": "Mar 12, 2017",
                "passage": "Mark 1:29-34 'The Healer'",
                "speaker": "Pastor Robin Cho",
                "length": "37:22",
                "file": "March+1_29-34"
            }, {
                "date": "Mar 5, 2017",
                "passage": "Mark 1:21-28 'The Holy One Of God'",
                "speaker": "Pastor Robin Cho",
                "length": "27:03",
                "file": "The+Holy+One+of+God+-+Mark+1_21-28"
            }, {
                "date": "Feb 26, 2017",
                "passage": "Exodus 7:1-13 'Optimism is Sharing the Gospel to Hardened Hearts'",
                "speaker": "Pastor David Lee (Guest Preacher)",
                "length": "44:00",
                "file": "Exodus+7_1-13"
            }, {
                "date": "Feb 19, 2017",
                "passage": "Mark 1:16-20 'Fishers of Men'",
                "speaker": "Pastor Robin Cho",
                "length": "32:27",
                "file": "Mark+1_16-20"
            }, {
                "date": "Feb 12, 2017",
                "passage": "Mark 1:14-15 'What Jesus First Preached'",
                "speaker": "Paster Robin Cho",
                "length": "40:37",
                "file": "Mark+1_14-15"
            }, {
                "date": "Feb 5, 2017",
                "passage": "Daniel 6 'The Lion's Den'",
                "speaker": "Pastor Stephen Jon (Guest Preacher)",
                "length": "49:46",
                "file": "Daniel+6+Stephen+Jon"
            }, {
                "date": "Jan 29, 2017",
                "passage": "Mark 1:12-13 'Wilderness Qualified'",
                "speaker": "Pastor Robin Cho",
                "length": "37:54",
                "file": "Jan+29+Mark+1_12-13"
            }, {
                "date": "Jan 22, 2017",
                "passage": "Mark 1:9-11 'Vicarious Christ'",
                "speaker": "Pastor Robin Cho",
                "length": "34:21",
                "file": "Jan+22+Mark+1_9-11"
            }],
            buildPlaylist = $.each(tracks, function(key, value) {
                var trackNumber = key+1,
                    trackDate = value.date,
                    trackPassage = value.passage,
                    trackSpeaker = value.speaker,
                    trackLength = value.length;
                if (trackNumber.toString().length === 1) {
                    trackNumber = '0' + trackNumber;
                } else {
                    trackNumber = '' + trackNumber;
                }
                $('#plList').append('

' +
                trackNumber + '.

' +
                trackPassage + '
' + trackSpeaker + ' - ' + trackDate +
                '

' + trackLength + '

');
            }),
            trackCount = tracks.length,
            npAction = $('#npAction'),
            npTitle = $('#npTitle'),
            audio = $('#audio1').bind('play', function () {
                playing = true;
                npAction.text('Now Playing...');
            }).bind('pause', function () {
                playing = false;
                npAction.text('Paused...');
            }).bind('ended', function () {
                npAction.text('Paused...');
                if ((index + 1) < trackCount) {
                    index++;
                    loadTrack(index);
                    audio.play();
                } else {
                    audio.pause();
                    index = 0;
                    loadTrack(index);
                }
            }).get(0),
            btnPrev = $('#btnPrev').click(function () {
                if ((index - 1) > -1) {
                    index--;
                    loadTrack(index);
                    if (playing) {
                        audio.play();
                    }
                } else {
                    audio.pause();
                    index = 0;
                    loadTrack(index);
                }
            }),
            btnNext = $('#btnNext').click(function () {
                if ((index + 1) < trackCount) {
                    index++;
                    loadTrack(index);
                    if (playing) {
                        audio.play();
                    }
                } else {
                    audio.pause();
                    index = 0;
                    loadTrack(index);
                }
            }),
            li = $('#plList li').click(function () {
                var id = parseInt($(this).index());
                if (id !== index) {
                    playTrack(id);
                }
            }),
            loadTrack = function (id) {
                $('.plSel').removeClass('plSel');
                $('#plList li:eq(' + id + ')').addClass('plSel');
                npTitle.text(tracks[id].passage);
                index = id;
                audio.src = mediaPath + tracks[id].file + extension;
            },
            playTrack = function (id) {
                loadTrack(id);
                audio.play();
            };
        extension = audio.canPlayType('audio/mpeg') ? '.m4a' : audio.canPlayType('audio/ogg') ? '.ogg' : audio.canPlayType('audio/mp4') ? '.mp4a' : '';
        loadTrack(index);
    }
});
<|endoftext|>


<commit_before>/*
 * QuickBlox JavaScript SDK
 *
 * Configuration Module
 *
 */

var config = {
  version: '1.3.0',
  creds: {
    appId: '',
    authKey: '',
    authSecret: ''
  },
  endpoints: {
    api: 'api.quickblox.com',
    chat: 'chat.quickblox.com',
    muc: 'muc.chat.quickblox.com',
    turn: 'turnserver.quickblox.com',
    s3Bucket: 'qbprod'
  },
  chatProtocol: {
    //bosh: 'http://chat.quickblox.com:8080',
    bosh: 'https://chat.quickblox.com:8081', // With SSL
    websocket: 'ws://chat.quickblox.com:5290',
    active: 1
  },
  urls: {
    session: 'session',
    login: 'login',
    users: 'users',
    chat: 'chat',
    blobs: 'blobs',
    geodata: 'geodata',
    places: 'places',
    pushtokens: 'push_tokens',
    subscriptions: 'subscriptions',
    events: 'events',
    data: 'data',
    type: '.json'
  },
  ssl: true,
  debug: false
};

// Browserify exports
module.exports = config;
<commit_msg>Added config.set method for changing defaults<commit_after>/*
 * QuickBlox JavaScript SDK
 *
 * Configuration Module
 *
 */

var config = {
  version: '1.3.0',
  creds: {
    appId: '',
    authKey: '',
    authSecret: ''
  },
  endpoints: {
    api: 'api.quickblox.com',
    chat: 'chat.quickblox.com',
    muc: 'muc.chat.quickblox.com',
    turn: 'turnserver.quickblox.com',
    s3Bucket: 'qbprod'
  },
  chatProtocol: {
    //bosh: 'http://chat.quickblox.com:8080',
    bosh: 'https://chat.quickblox.com:8081', // With SSL
    websocket: 'ws://chat.quickblox.com:5290',
    active: 1
  },
  urls: {
    session: 'session',
    login: 'login',
    users: 'users',
    chat: 'chat',
    blobs: 'blobs',
    geodata: 'geodata',
    places: 'places',
    pushtokens: 'push_tokens',
    subscriptions: 'subscriptions',
    events: 'events',
    data: 'data',
    type: '.json'
  },
  ssl: true,
  debug: false
};

config.set = function(options) {
  console.log("Received %s:", typeof options);
  console.log(options)
  Object.keys(options).forEach(function(key) {
    if(key !== 'set' && config.hasOwnProperty(key)) {
      if(typeof options[key] !== 'object') {
        config[key] = options[key]
      } else {
        Object.keys(options[key]).forEach(function(nextkey) {
          if(config.hasOwnProperty(key))
            config[key][nextkey] = options[key][nextkey];
        });
      }
    }
  })
};

// Browserify exports
module.exports = config;
<|endoftext|>


<commit_before>MyHomeworkSpace.QuickAdd = {
	classes: [],
	classIds: [],
	prefixList: [],
	classSynonyms: [
		["science", "sci", "bio", "biology", "chem", "chemistry", "physics"],
		["math", "algebra", "calculus", "calc", "pre-calculus", "precalculus", "precalc", "geometry", "geo"],
		["computer science", "compsci"],
		["language", "french", "latin", "spanish", "mandarin"]
	],
	init: function() {
		var nlp = window.nlp_compromise;
		// these things aren't descriptive enough to be useful dates, so remove them from the lexicon
		nlp.lexicon()["day"] = undefined;
		nlp.lexicon()["week"] = undefined;

		// these things cause nlp_compromise to get very confused
		// "hw pa" doesn't mean a highway in philadelphia
		nlp.lexicon()["hwy"] = undefined;
		nlp.lexicon()["pa"] = undefined;

		// this is a bit of a hack to get nlp_compromise to like the "hw" prefix
		// i know that "hw" isn't a verb
		// nlp_compromise doesn't
		nlp.lexicon()["hw"] = "Infinitive";

		MyHomeworkSpace.QuickAdd.classes = [];
		MyHomeworkSpace.QuickAdd.classIds = [];
		MyHomeworkSpace.QuickAdd.prefixList = [];
		for (var prefixIndex in MyHomeworkSpace.Prefixes.list) {
			var prefix = MyHomeworkSpace.Prefixes.list[prefixIndex];
			for (var wordIndex in prefix.words) {
				MyHomeworkSpace.QuickAdd.prefixList.push(prefix.words[wordIndex].toLowerCase());
			}
		}
		for (var classIndex in MyHomeworkSpace.Classes.list) {
			MyHomeworkSpace.QuickAdd.classes.push(MyHomeworkSpace.Classes.list[classIndex].name.toLowerCase());
			MyHomeworkSpace.QuickAdd.classIds.push(MyHomeworkSpace.Classes.list[classIndex].id);
		}
	},
	isClass: function(array, index) {
		var classMatches = false;
		var termsToSkip = 0;
		var arrIndex = index;
		for (var classIndex in MyHomeworkSpace.QuickAdd.classes) {
			var classItem = MyHomeworkSpace.QuickAdd.classes[classIndex];
			var classWords = classItem.split(" ");
			arrIndex = index;
			for (var i = 0; i < classWords.length; i++) {
				if (array.length <= arrIndex) {
					if (classMatches) {
						break;
					} else {
						continue;
					}
				}
				if (classWords[i].toLowerCase() == array[arrIndex].text.toLowerCase()) {
					classMatches = true;
				} else {
					classMatches = false;
					for (var synonymsIndex in MyHomeworkSpace.QuickAdd.classSynonyms) {
						if (MyHomeworkSpace.QuickAdd.classSynonyms[synonymsIndex].indexOf(classWords[i].toLowerCase()) > -1) {
							if (MyHomeworkSpace.QuickAdd.classSynonyms[synonymsIndex].indexOf(array[arrIndex].text.toLowerCase()) > -1) {
								classMatches = true;
							}
						}
					}
				}
				arrIndex++;
			}
			if (classMatches) {
				break;
			}
		}
		return {
			match: classMatches,
			classIndex: parseInt(classIndex),
			termsToSkip: arrIndex - index
		};
	},
	parseDate: function(text) {
		if (!isNaN(moment(text).day())) {
			return moment(text).format("YYYY-MM-DD");
		}
		var textToParse = text.toLowerCase().split(" ");
		var result = {
			last: false,
			next: false,
			dow: -1
		};
		for (var wordIndex in textToParse) {
			var word = textToParse[wordIndex];
			if (word == "last") {
				result.last = true;
			} else if (word == "next") {
				result.next = true;
			} else if (word.substr(0, 3) == "sun") {
				result.dow = 0;
			} else if (word.substr(0, 3) == "mon") {
				result.dow = 1;
			} else if (word.substr(0, 3) == "tue") {
				result.dow = 2;
			} else if (word.substr(0, 3) == "wed") {
				result.dow = 3;
			} else if (word.substr(0, 3) == "thu") {
				result.dow = 4;
			} else if (word.substr(0, 3) == "fri") {
				result.dow = 5;
			} else if (word.substr(0, 3) == "sat") {
				result.dow = 6;
			} else if (word.substr(0, 3) == "ton") { // tonight
				result.dow = moment().day();
			} else if (word.substr(0, 3) == "tom") { // tomorrow
				result.dow = moment().day() + 1;
				if (result.dow == 7) {
					result.dow = 0;
				}
			}
		}
		if (result.dow == -1) {
			return "";
		}
		var resultDate = moment();
		var thisWeek = resultDate.week();
		while (
			((result.last || result.next) && (resultDate.week() == thisWeek || resultDate.day() != result.dow)) ||
			((!result.last && !result.next) && (resultDate.day() != result.dow))
		) {
			if (result.last) {
				resultDate.subtract(1, "day");
			} else {
				resultDate.add(1, "day");
			}
		}
		return resultDate.format("YYYY-MM-DD");
	},
	parseText: function(text) {
		// examples:
		// [read poem] [for English] for [tomorrow]
		// take [test on molecules] [in Science] on [next Tuesday]
		// [next Friday] write an [essay about the revolution] [in History] class

		var nlp = window.nlp_compromise;
		var response = {
			tag: "",
			name: "",
			class: "",
			classId: 0,
			due: ""
		};
		var sentence = nlp.sentence(text);
		var nameTrack = false;
		var termsToSkip = 0;

		for (var termIndex in sentence.terms) {
			var term = sentence.terms[termIndex];
			if (termsToSkip > 0) {
				termsToSkip--;
			} else if (MyHomeworkSpace.QuickAdd.prefixList.indexOf(term.text.toLowerCase()) > -1) {
				response.tag = term.text;
				nameTrack = true;
			} else if (term.tag == "Date") {
				response.due = term.text;
			} else if (term.pos.Conjunction || term.pos.Preposition) {
				// peek at the next word
				var classResults = MyHomeworkSpace.QuickAdd.isClass(sentence.terms, parseInt(termIndex) + 1);
				if (sentence.terms[parseInt(termIndex) + 1] && classResults.match) {
					// if it's a class, set it and skip it
					response.class = MyHomeworkSpace.Classes.list[classResults.classIndex].name;
					response.classId = MyHomeworkSpace.QuickAdd.classIds[classResults.classIndex];
					termsToSkip = classResults.termsToSkip;
				} else if ((parseInt(termIndex) + 1) != sentence.terms.length && sentence.terms[parseInt(termIndex) + 1].tag == "Date") {
					// the next word is a due date, so skip this word
				} else if (nameTrack) {
					response.name += term.text;
					response.name += " ";
				}
			} else if (term.text.toLowerCase() == "due" || term.text.toLowerCase() == "class") {
				// skip it
			} else if (nameTrack) {
				response.name += term.text;
				response.name += " ";
			}
		}

		response.name = response.name.trim();

		return response;
	}
};
<commit_msg>fix quick add issue with some prefixes + nouns<commit_after>MyHomeworkSpace.QuickAdd = {
	classes: [],
	classIds: [],
	prefixList: [],
	classSynonyms: [
		["science", "sci", "bio", "biology", "chem", "chemistry", "physics"],
		["math", "algebra", "calculus", "calc", "pre-calculus", "precalculus", "precalc", "geometry", "geo"],
		["computer science", "compsci"],
		["language", "french", "latin", "spanish", "mandarin"]
	],
	init: function() {
		var nlp = window.nlp_compromise;
		// these things aren't descriptive enough to be useful dates, so remove them from the lexicon
		nlp.lexicon()["day"] = undefined;
		nlp.lexicon()["week"] = undefined;

		// these things cause nlp_compromise to get very confused
		// "hw pa" doesn't mean a highway in philadelphia
		nlp.lexicon()["hwy"] = undefined;
		nlp.lexicon()["pa"] = undefined;

		// this is a bit of a hack to get nlp_compromise to like prefixes
		// i know that "hw" and "essay" aren't verbs
		// nlp_compromise doesn't
		for (var prefixIndex in MyHomeworkSpace.Prefixes.list) {
			var prefix = MyHomeworkSpace.Prefixes.list[prefixIndex];
			for (var wordIndex in prefix.words) {
				var word = prefix.words[wordIndex];
				nlp.lexicon()[word.toLowerCase()] = "Infinitive";
			}
		}

		MyHomeworkSpace.QuickAdd.classes = [];
		MyHomeworkSpace.QuickAdd.classIds = [];
		MyHomeworkSpace.QuickAdd.prefixList = [];
		for (var prefixIndex in MyHomeworkSpace.Prefixes.list) {
			var prefix = MyHomeworkSpace.Prefixes.list[prefixIndex];
			for (var wordIndex in prefix.words) {
				MyHomeworkSpace.QuickAdd.prefixList.push(prefix.words[wordIndex].toLowerCase());
			}
		}
		for (var classIndex in MyHomeworkSpace.Classes.list) {
			MyHomeworkSpace.QuickAdd.classes.push(MyHomeworkSpace.Classes.list[classIndex].name.toLowerCase());
			MyHomeworkSpace.QuickAdd.classIds.push(MyHomeworkSpace.Classes.list[classIndex].id);
		}
	},
	isClass: function(array, index) {
		var classMatches = false;
		var termsToSkip = 0;
		var arrIndex = index;
		for (var classIndex in MyHomeworkSpace.QuickAdd.classes) {
			var classItem = MyHomeworkSpace.QuickAdd.classes[classIndex];
			var classWords = classItem.split(" ");
			arrIndex = index;
			for (var i = 0; i < classWords.length; i++) {
				if (array.length <= arrIndex) {
					if (classMatches) {
						break;
					} else {
						continue;
					}
				}
				if (classWords[i].toLowerCase() == array[arrIndex].text.toLowerCase()) {
					classMatches = true;
				} else {
					classMatches = false;
					for (var synonymsIndex in MyHomeworkSpace.QuickAdd.classSynonyms) {
						if (MyHomeworkSpace.QuickAdd.classSynonyms[synonymsIndex].indexOf(classWords[i].toLowerCase()) > -1) {
							if (MyHomeworkSpace.QuickAdd.classSynonyms[synonymsIndex].indexOf(array[arrIndex].text.toLowerCase()) > -1) {
								classMatches = true;
							}
						}
					}
				}
				arrIndex++;
			}
			if (classMatches) {
				break;
			}
		}
		return {
			match: classMatches,
			classIndex: parseInt(classIndex),
			termsToSkip: arrIndex - index
		};
	},
	parseDate: function(text) {
		if (!isNaN(moment(text).day())) {
			return moment(text).format("YYYY-MM-DD");
		}
		var textToParse = text.toLowerCase().split(" ");
		var result = {
			last: false,
			next: false,
			dow: -1
		};
		for (var wordIndex in textToParse) {
			var word = textToParse[wordIndex];
			if (word == "last") {
				result.last = true;
			} else if (word == "next") {
				result.next = true;
			} else if (word.substr(0, 3) == "sun") {
				result.dow = 0;
			} else if (word.substr(0, 3) == "mon") {
				result.dow = 1;
			} else if (word.substr(0, 3) == "tue") {
				result.dow = 2;
			} else if (word.substr(0, 3) == "wed") {
				result.dow = 3;
			} else if (word.substr(0, 3) == "thu") {
				result.dow = 4;
			} else if (word.substr(0, 3) == "fri") {
				result.dow = 5;
			} else if (word.substr(0, 3) == "sat") {
				result.dow = 6;
			} else if (word.substr(0, 3) == "ton") { // tonight
				result.dow = moment().day();
			} else if (word.substr(0, 3) == "tom") { // tomorrow
				result.dow = moment().day() + 1;
				if (result.dow == 7) {
					result.dow = 0;
				}
			}
		}
		if (result.dow == -1) {
			return "";
		}
		var resultDate = moment();
		var thisWeek = resultDate.week();
		while (
			((result.last || result.next) && (resultDate.week() == thisWeek || resultDate.day() != result.dow)) ||
			((!result.last && !result.next) && (resultDate.day() != result.dow))
		) {
			if (result.last) {
				resultDate.subtract(1, "day");
			} else {
				resultDate.add(1, "day");
			}
		}
		return resultDate.format("YYYY-MM-DD");
	},
	parseText: function(text) {
		// examples:
		// [read poem] [for English] for [tomorrow]
		// take [test on molecules] [in Science] on [next Tuesday]
		// [next Friday] write an [essay about the revolution] [in History] class

		var nlp = window.nlp_compromise;
		var response = {
			tag: "",
			name: "",
			class: "",
			classId: 0,
			due: ""
		};
		var sentence = nlp.sentence(text);
		var nameTrack = false;
		var termsToSkip = 0;

		for (var termIndex in sentence.terms) {
			var term = sentence.terms[termIndex];
			if (termsToSkip > 0) {
				termsToSkip--;
			} else if (MyHomeworkSpace.QuickAdd.prefixList.indexOf(term.text.toLowerCase()) > -1) {
				response.tag = term.text;
				nameTrack = true;
			} else if (term.tag == "Date") {
				response.due = term.text;
			} else if (term.pos.Conjunction || term.pos.Preposition) {
				// peek at the next word
				var classResults = MyHomeworkSpace.QuickAdd.isClass(sentence.terms, parseInt(termIndex) + 1);
				if (sentence.terms[parseInt(termIndex) + 1] && classResults.match) {
					// if it's a class, set it and skip it
					response.class = MyHomeworkSpace.Classes.list[classResults.classIndex].name;
					response.classId = MyHomeworkSpace.QuickAdd.classIds[classResults.classIndex];
					termsToSkip = classResults.termsToSkip;
				} else if ((parseInt(termIndex) + 1) != sentence.terms.length && sentence.terms[parseInt(termIndex) + 1].tag == "Date") {
					// the next word is a due date, so skip this word
				} else if (nameTrack) {
					response.name += term.text;
					response.name += " ";
				}
			} else if (term.text.toLowerCase() == "due" || term.text.toLowerCase() == "class") {
				// skip it
			} else if (nameTrack) {
				response.name += term.text;
				response.name += " ";
			}
		}

		response.name = response.name.trim();

		return response;
	}
};
<|endoftext|>


<commit_before>GAME.setConsts({
	canvas : document.createElement("canvas"),
	CANVAS_WIDTH : 500,
	CANVAS_HEIGHT : 500,
	TILE_SCALE : 5,
	C_PLAYER : "rgb(0,200,0)",
	C_PL_BULLET : "rgb(0,0,255)",
	C_ENEMY : "rgb(255,0,0)",
	C_EN_BULLET : "rgb(100,100,100)",
	C_FLOOR	: "rgb(255,255,255)",
	C_WALL : "rgb(0,0,0)",
});

GAME.setConsts({
	ctx : GAME.canvas.getContext("2d"),
	VIEW_WIDTH : GAME.CANVAS_WIDTH / GAME.TILE_SCALE - 2,
	VIEW_HEIGHT : GAME.CANVAS_HEIGHT / GAME.TILE_SCALE - 2,
});

GAME.Renderer = (function() {
	var canvas = GAME.canvas,
		height = GAME.CANVAS_HEIGHT,
		width	= GAME.CANVAS_WIDTH,
		scale = GAME.TILE_SCALE,
		ctx		= GAME.ctx,
		WALL_TILE	 = GAME.WALL_TILE,
		C_FLOOR = GAME.C_FLOOR,
		C_WALL = GAME.C_WALL,
		C_PLAYER = GAME.C_PLAYER,
		C_PL_BULLET = GAME.C_PL_BULLET,
		C_ENEMY = GAME.C_ENEMY,
		C_EN_BULLET = GAME.C_EN_BULLET,
		VIEW_WIDTH = GAME.VIEW_WIDTH,
		VIEW_HEIGHT = GAME.VIEW_HEIGHT,
    vgnfade = 0,
    vgnmax = .8;

	canvas.height = height;
	canvas.width = width;

	function draw() {
		drawFloors();
		drawWalls();
		drawBullets();
		drawEntities();
    if (GAME.frozen) {
      drawVingette();
    }
	}

	function drawTile(x, y) {
		//TODO: Check if tile is within window bounds
		ctx.fillRect(x*scale, y*scale, scale, scale);
	}

	function drawFloors() {
		ctx.fillStyle = C_FLOOR;
		ctx.fillRect(0,0,width,height); // Fill everything as floors to start
	}

	function drawWalls() {
		ctx.fillStyle = C_WALL;
		var level = GAME.current_level;
		for (var i = 0, len = level.tilemap.length; i < len; i++){
			for (var j = 0, hei = level.tilemap[i].length; j < hei; j++) {
				if (level.tilemap[i][j] == WALL_TILE) {
					drawTile(i,j);
				}
			}
		}
	}

	function drawBullets() {
		ctx.fillStyle = C_PL_BULLET;
		for (var i = 0, len = GAME.bullets.length; i < len; i++) {
			drawEntity(GAME.bullets[i]);
		}
	}

	function drawEntities() {
		ctx.fillStyle = C_PLAYER;
		drawEntity(GAME.player);

		ctx.fillStyle = C_ENEMY;
		for (var i = 0; i < GAME.entities.length; i++) {
			drawEntity(GAME.entities[i]);
		}
	}

	function drawEntity(e) {
		var points = GAME.Math.rotatePoints(e.shape, e.angle);

		ctx.beginPath();
		ctx.moveTo(e.x + points[0][0] * scale,
		           e.y + points[0][1] * scale);
		for (var i = 1; i < points.length; i++) {
			ctx.lineTo(e.x + points[i][0] * scale,
			           e.y + points[i][1] * scale);
		}
		ctx.closePath();
		ctx.fill();
	}

  function drawVingette() {
    var start = 0;
    vgnfade += (vgnmax - vgnfade) / 10;
    var cstart = "rgba(100,100,100,255)";
    var cend = "rgba(100,0,0,0)";
    var end = Math.min(vgnfade, vgnmax);
    var vingette = ctx.createLinearGradient(0,0,GAME.player.x, GAME.player.y);
    vingette.addColorStop(start, cstart);
    vingette.addColorStop(end, cend);
    ctx.fillStyle = vingette;
    ctx.fillRect(0,0,width,height);

    vingette = ctx.createLinearGradient(GAME.current_level.size.width*scale,GAME.current_level.size.height*scale,GAME.player.x,GAME.player.y);
    vingette.addColorStop(start, cstart);
    vingette.addColorStop(end, cend);
    ctx.fillStyle = vingette;
    ctx.fillRect(0,0,width,height);

    vingette = ctx.createLinearGradient(0,GAME.current_level.size.width*scale,GAME.player.x, GAME.player.y);
    vingette.addColorStop(start, cstart);
    vingette.addColorStop(end, cend);
    ctx.fillStyle = vingette;
    ctx.fillRect(0,0,width,height);

    vingette = ctx.createLinearGradient(GAME.current_level.size.width*scale,0,GAME.player.x, GAME.player.y);
    vingette.addColorStop(start, cstart);
    vingette.addColorStop(end, cend);
    ctx.fillStyle = vingette;
    ctx.fillRect(0,0,width,height);

  }
	return {
		draw : draw,
    drawVingette : drawVingette,
	}
})();
<commit_msg>Darken vignette.<commit_after>GAME.setConsts({
	canvas : document.createElement("canvas"),
	CANVAS_WIDTH : 500,
	CANVAS_HEIGHT : 500,
	TILE_SCALE : 5,
	C_PLAYER : "rgb(0,200,0)",
	C_PL_BULLET : "rgb(0,0,255)",
	C_ENEMY : "rgb(255,0,0)",
	C_EN_BULLET : "rgb(100,100,100)",
	C_FLOOR	: "rgb(255,255,255)",
	C_WALL : "rgb(0,0,0)",
});

GAME.setConsts({
	ctx : GAME.canvas.getContext("2d"),
	VIEW_WIDTH : GAME.CANVAS_WIDTH / GAME.TILE_SCALE - 2,
	VIEW_HEIGHT : GAME.CANVAS_HEIGHT / GAME.TILE_SCALE - 2,
});

GAME.Renderer = (function() {
	var canvas = GAME.canvas,
		height = GAME.CANVAS_HEIGHT,
		width	= GAME.CANVAS_WIDTH,
		scale = GAME.TILE_SCALE,
		ctx		= GAME.ctx,
		WALL_TILE	 = GAME.WALL_TILE,
		C_FLOOR = GAME.C_FLOOR,
		C_WALL = GAME.C_WALL,
		C_PLAYER = GAME.C_PLAYER,
		C_PL_BULLET = GAME.C_PL_BULLET,
		C_ENEMY = GAME.C_ENEMY,
		C_EN_BULLET = GAME.C_EN_BULLET,
		VIEW_WIDTH = GAME.VIEW_WIDTH,
		VIEW_HEIGHT = GAME.VIEW_HEIGHT,
    vgnfade = 0,
    vgnmax = .8;

	canvas.height = height;
	canvas.width = width;

	function draw() {
		drawFloors();
		drawWalls();
		drawBullets();
		drawEntities();
    if (GAME.frozen) {
      drawVingette();
    }
	}

	function drawTile(x, y) {
		//TODO: Check if tile is within window bounds
		ctx.fillRect(x*scale, y*scale, scale, scale);
	}

	function drawFloors() {
		ctx.fillStyle = C_FLOOR;
		ctx.fillRect(0,0,width,height); // Fill everything as floors to start
	}

	function drawWalls() {
		ctx.fillStyle = C_WALL;
		var level = GAME.current_level;
		for (var i = 0, len = level.tilemap.length; i < len; i++){
			for (var j = 0, hei = level.tilemap[i].length; j < hei; j++) {
				if (level.tilemap[i][j] == WALL_TILE) {
					drawTile(i,j);
				}
			}
		}
	}

	function drawBullets() {
		ctx.fillStyle = C_PL_BULLET;
		for (var i = 0, len = GAME.bullets.length; i < len; i++) {
			drawEntity(GAME.bullets[i]);
		}
	}

	function drawEntities() {
		ctx.fillStyle = C_PLAYER;
		drawEntity(GAME.player);

		ctx.fillStyle = C_ENEMY;
		for (var i = 0; i < GAME.entities.length; i++) {
			drawEntity(GAME.entities[i]);
		}
	}

	function drawEntity(e) {
		var points = GAME.Math.rotatePoints(e.shape, e.angle);

		ctx.beginPath();
		ctx.moveTo(e.x + points[0][0] * scale,
		           e.y + points[0][1] * scale);
		for (var i = 1; i < points.length; i++) {
			ctx.lineTo(e.x + points[i][0] * scale,
			           e.y + points[i][1] * scale);
		}
		ctx.closePath();
		ctx.fill();
	}

  function drawVingette() {
    var start = 0;
    vgnfade += (vgnmax - vgnfade) / 10;
    var cstart = "rgba(40,30,30,255)";
    var cend = "rgba(100,0,0,0)";
    var end = Math.min(vgnfade, vgnmax);
    var vingette = ctx.createLinearGradient(0,0,GAME.player.x, GAME.player.y);
    vingette.addColorStop(start, cstart);
    vingette.addColorStop(end, cend);
    ctx.fillStyle = vingette;
    ctx.fillRect(0,0,width,height);

    vingette = ctx.createLinearGradient(GAME.current_level.size.width*scale,GAME.current_level.size.height*scale,GAME.player.x,GAME.player.y);
    vingette.addColorStop(start, cstart);
    vingette.addColorStop(end, cend);
    ctx.fillStyle = vingette;
    ctx.fillRect(0,0,width,height);

    vingette = ctx.createLinearGradient(0,GAME.current_level.size.width*scale,GAME.player.x, GAME.player.y);
    vingette.addColorStop(start, cstart);
    vingette.addColorStop(end, cend);
    ctx.fillStyle = vingette;
    ctx.fillRect(0,0,width,height);

    vingette = ctx.createLinearGradient(GAME.current_level.size.width*scale,0,GAME.player.x, GAME.player.y);
    vingette.addColorStop(start, cstart);
    vingette.addColorStop(end, cend);
    ctx.fillStyle = vingette;
    ctx.fillRect(0,0,width,height);

  }
	return {
		draw : draw,
    drawVingette : drawVingette,
	}
})();
<|endoftext|>


<commit_before>/**
 * @author Axel Virnich
 */

var temp = null;

// requests the phenomena available for the station selected
function getPhenomenaJSON(){
	$.getJSON('http://sensorweb.demo.52north.org/sensorwebclient-webapp-stable/api/v1/phenomena/?station=' + temp.getId(), function(data) {
    	var phenArr = [];
		for(var i = 0; i < data.length; i++){
			phenArr.push(new Phenomenon(data[i].id, data[i].label));
		}
		temp.setPhenomena(phenArr);
		temp.showPopup();
		temp = null;
	});
}

<commit_msg>added ajax request for the stations<commit_after>/**
 * @author Axel Virnich
 */

var temp = null;
var req = null;

// requests the phenomena available for the station selected
function getPhenomenaJSON(){
	$.getJSON('http://sensorweb.demo.52north.org/sensorwebclient-webapp-stable/api/v1/phenomena/?station=' + temp.getId(), function(data) {
    	var phenArr = [];
		for(var i = 0; i < data.length; i++){
			phenArr.push(new Phenomenon(data[i].id, data[i].label));
		}
		temp.setPhenomena(phenArr);
		temp.showPopup();
		temp = null;
	});
}

// returns the XMLHTTPRequest, considering the browser used
function getXMLHttpRequest() {
	var httpReq = null;
	if (window.XMLHttpRequest) {
		httpReq = new XMLHttpRequest();
	} else if ( typeof ActiveXObject != "undefined") {
		httpReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	return httpReq;
}

// requests all stations from the server and adds them to the server
// triggers the loadStations function
// during the loading process a loading animation is used
function getStationsJSON(param) {
	showLoadingAnimation();
	req = getXMLHttpRequest();
	if (req) {
		req.onreadystatechange = function() {
			if(req.readyState == 4){
				// console.log(req.responseText);
				// var json = JSON.parse(req.responseText);
				stations = JSON.parse(req.responseText);
				console.log(stations);
				loadStations();
				hideLoadingAnimation();
			}
		};
		req.open("POST", "php/ajax.php", true);
		req.setRequestHeader("Content-type", "x-www-form-urlencoded");
		req.send(param);
	}
}

<|endoftext|>


<commit_before>/**
 * FCViz
 * Payload script for loan requests page
 */

//We don't need this mutation observer since we are in the requests page
window.fcVizObserver.disconnect();

var prependLinkToCell = function(){$(this).before(
  $(document.createElement("span")).attr("class","see_more").before("[").html("+").after("] ")
)};

$("#watch_form").find("a.mediumText").each(prependLinkToCell);

$(".see_more").on("click", function(){
  $(this).html($(this).html() === "+"? "-" : "+");
  var tr = $(this).closest("tr");
  if (tr.next().attr("class") !== "filler") {
    createPreviewUnder(tr);
  }
  tr.next().next().animate({height: "toggle"}, "slow");
});

function createPreviewUnder(row) {
  //Create a junk element that is hidden from the user
  //so that we can somehow give the illusion of maintaining
  //the table row background colors.
  var filler = $(document.createElement("tr"))
    .attr("class", "filler")
    .attr("id", "filler-"+row.attr("id"));
  filler.attr("style", "display: none;");

  var id = "preview-"+row.attr("id");

  var td = $(document.createElement("td"))
    .attr("colspan", 9)
    .attr("id", id)
    .html("Loading...");

  var href = row.find("a.mediumText").attr("href");

  var total = +row.find("td").eq(3).html().replace("£","").replace(",","");

  $.get(href, window.populatePreview.bind(window, id, total)).fail(function(jqXHR, textStatus, errorThrown) {
    $(td).html("Failed to retrieve "+href+", chart render aborted: "+errorThrown);
  });

  var preview = $(document.createElement("tr"))
    .attr("class", "preview");

  preview.append(td);
  preview.attr("style", "display: none;");
  row.after(filler,preview);
}

window.summaryVizDimensions = {
  height: 65,
  width: 300,
  margin: {top: 2, right: 10, bottom: 10, left: 10}
};

window.populatePreview = function (id, total, data){
  var dataTableStartIndex = data.indexOf("
");

  var previewBidsId = "preview_bids_"+id;
  var previewBids = $(document.createElement("span"))
    .attr("id", previewBidsId)
    .attr("style", "width: 300px")
    .html(data.substring(dataTableStartIndex, data.indexOf("
", dataTableStartIndex)) + "
" );
  previewBids.find("table").attr("style", "display: none");
  $("#"+id).html("").append(previewBids);

  window.renderBidSummaryCharts(total, "#"+id, previewBidsId);
  $("#"+id).find("svg").find("g.tick").attr("style", "display: none;");
  $("#"+id).find("svg").find("g").find("text").attr("style", "display: none;");
}<commit_msg>Add company name, type, age to preview pane<commit_after>/**
 * FCViz
 * Payload script for loan requests page
 */

//We don't need this mutation observer since we are in the requests page
window.fcVizObserver.disconnect();

var prependLinkToCell = function(){$(this).before(
  $(document.createElement("span")).attr("class","see_more").before("[").html("+").after("] ")
)};

$("#watch_form").find("a.mediumText").each(prependLinkToCell);

$(".see_more").on("click", function(){
  $(this).html($(this).html() === "+"? "-" : "+");
  var tr = $(this).closest("tr");
  if (tr.next().attr("class") !== "filler") {
    createPreviewUnder(tr);
  }
  tr.next().next().animate({height: "toggle"}, "slow");
});

function createPreviewUnder(row) {
  //Create a junk element that is hidden from the user
  //so that we can somehow give the illusion of maintaining
  //the table row background colors.
  var filler = $(document.createElement("tr"))
    .attr("class", "filler")
    .attr("id", "filler-"+row.attr("id"));
  filler.attr("style", "display: none;");

  var id = "preview-"+row.attr("id");

  var td = $(document.createElement("td"))
    .attr("colspan", 9)
    .attr("id", id)
    .html("Loading...");

  var href = row.find("a.mediumText").attr("href");

  var total = +row.find("td").eq(3).html().replace("£","").replace(",","");

  $.get(href, window.populatePreview.bind(window, id, total)).fail(function(jqXHR, textStatus, errorThrown) {
    $(td).html("Failed to retrieve "+href+", chart render aborted: "+errorThrown);
  });

  var preview = $(document.createElement("tr"))
    .attr("class", "preview");

  preview.append(td);
  preview.attr("style", "display: none;");
  row.after(filler,preview);
}

window.summaryVizDimensions = {
  height: 65,
  width: 300,
  margin: {top: 2, right: 10, bottom: 10, left: 10}
};

window.populatePreview = function (id, total, data){
  $("#"+id).html("");
  var detailsStartIndex = data.indexOf("
\n
");
  var dl = $(document.createElement("span"))
    .html(data.substring(detailsStartIndex, data.indexOf("
", detailsStartIndex)))
    .find("dl").attr("style", "display: initial;");
  dl.children().attr("style", "font-size: 14px;").slice(2,6).detach();
  var title = [];
  dl.find("dd").each(function(){title.push($(this).html().trim())});
  indicateMoreThan = /more than/.test(title[2])? ">" : "";
  title[2] = indicateMoreThan + (/\d+/.exec(title[2])[0]);
  var previewDetails = $(document.createElement("span"))
    .attr("id", id+"-details")
    .append(title[0]).append(document.createElement("br")).append(title[1] + ", " + title[2] + " years");
  $("#"+id).append(previewDetails);

  var dataTableStartIndex = data.indexOf("
");
  var previewBidsId = id+"-bids";
  var previewBids = $(document.createElement("span"))
    .attr("id", previewBidsId)
    .attr("style", "width: 300px")
    .html(data.substring(dataTableStartIndex, data.indexOf("
", dataTableStartIndex)) + "
" );
  previewBids.find("table").attr("style", "display: none");
  $("#"+id).append(previewBids);

  window.renderBidSummaryCharts(total, "#"+id, previewBidsId);
  $("#"+id).find("svg").find("g.tick").attr("style", "display: none;");
  $("#"+id).find("svg").find("g").find("text").attr("style", "display: none;");
  previewBids.find("table").detach();
}<|endoftext|>


<commit_before>var TimeTrackerServices = angular.module('TimeTrackerServices', []);

TimeTrackerServices.service('PlayerRepository', [
    '$rootScope',
    'Player',
    function ($rootScope, Player)
    {
        var playerList = [];

        this.addPlayer = function(player)
        {
            if (locatePlayer(player) === false) {
                player = new Player(player);
                playerList.push(player);
            }

            $rootScope.$broadcast('playerChanges', playerList);

            return playerList;
        };

        this.getPlayers = function()
        {
            return playerList;
        };

        this.removePlayer = function (player)
        {
            var index = locatePlayer(player);

            if (index !== false) {
                playerList[index].clockOut();

                playerList = playerList.slice(0, index).concat(
                    playerList.slice(index + 1, playerList.length)
                );

                $rootScope.$broadcast('playerChanges', playerList);
            }

            return playerList;
        };

        function locatePlayer(player)
        {
            var i = 0,
                l = playerList.length;

            for (; i < l; i++) {
                if (playerList[i].getName() === player) {
                    return i;
                }
            }

            return false;
        }
    }
]);<commit_msg>Prevents playerChanges event from firing if no new players are added<commit_after>var TimeTrackerServices = angular.module('TimeTrackerServices', []);

TimeTrackerServices.service('PlayerRepository', [
    '$rootScope',
    'Player',
    function ($rootScope, Player)
    {
        var playerList = [];

        this.addPlayer = function(player)
        {
            if (locatePlayer(player) === false) {
                player = new Player(player);
                playerList.push(player);
                $rootScope.$broadcast('playerChanges', playerList);
            }

            return playerList;
        };

        this.getPlayers = function()
        {
            return playerList;
        };

        this.removePlayer = function (player)
        {
            var index = locatePlayer(player);

            if (index !== false) {
                playerList[index].clockOut();

                playerList = playerList.slice(0, index).concat(
                    playerList.slice(index + 1, playerList.length)
                );

                $rootScope.$broadcast('playerChanges', playerList);
            }

            return playerList;
        };

        function locatePlayer(player)
        {
            var i = 0,
                l = playerList.length;

            for (; i < l; i++) {
                if (playerList[i].getName() === player) {
                    return i;
                }
            }

            return false;
        }
    }
]);<|endoftext|>


<commit_before>$('
 \
 \
    \
            \
            Czatrepajr \
 <button id="min-chat-switch" class="min-chat__header__switch">Wyłącz</button> \
 \

 \

 \

 \

 \

 \
        <input type="text" id="chat-input" class="min-chat__fieldset__input" spellcheck="true"> \

 \

 \

').appendTo('body');
<commit_msg>Change syntax to  template strings.<commit_after>$(`

            Czatrepajr
 <button id="min-chat-switch" class="min-chat__header__switch" title="Wyłącz">↓</button>

        <input type="text" id="chat-input" class="min-chat__fieldset__input" spellcheck="true">

`).appendTo('body');
<|endoftext|>


<commit_before>angular.module('bgDirectives', [])
  .directive('bgSplitter', function() {
    return {
      restrict: 'E',
      replace: true,
      transclude: true,
      scope: {
        orientation: '@',
        pos: '@'
      },
      template: '

',
      controller: function ($scope) {
        $scope.panes = [];

        this.addPane = function(pane){
          if ($scope.panes.length > 1)
            throw 'splitters can only have two panes';
          $scope.panes.push(pane);
          return $scope.panes.length;
        };
      },
      link: function(scope, element, attrs) {
        var handler = angular.element('

');
        var pane1 = scope.panes[0];
        var pane2 = scope.panes[1];
        var vertical = scope.orientation == 'vertical';
        var pane1Min = pane1.minSize || 0;
        var pane2Min = pane2.minSize || 0;
        var drag = false;

        pane1.elem.after(handler);

        console.log('split link');
        console.log(scope.pos);
        console.log(element);

        function resize (ev) {
          if (!drag) return;

          var bounds = element[0].getBoundingClientRect();
          var pos = 0;

          if (vertical) {
            var width = bounds.right - bounds.left;
            pos = ev.clientX - bounds.left;

            if (pos < pane1Min) return;
            if (width - pos < pane2Min) return;

            handler.css('left', pos + 'px');
            pane1.elem.css('width', pos + 'px');
            pane2.elem.css('left', pos + 'px');

          } else {
            var height = bounds.bottom - bounds.top;
            pos = ev.clientY - bounds.top;

            if (pos < pane1Min) return;
            if (height - pos < pane2Min) return;

            handler.css('top', pos + 'px');
            pane1.elem.css('height', pos + 'px');
            pane2.elem.css('top', pos + 'px');
          }
        }

        element.bind('mousemove', resize);

        handler.bind('mousedown', function (ev) {
          ev.preventDefault();
          drag = true;
        });

        angular.element(document).bind('mouseup', function (ev) {
          drag = false;
        });

        if (scope.pos)
        {
            // initialize handler position from pos attribute
            var bounds = element[0].getBoundingClientRect();
            var width = bounds.right - bounds.left;
            var height = bounds.bottom - bounds.top;

            var ev = {
                clientX: 0,
                clientY: 0
            };

            if (scope.pos.indexOf('%') != -1)
            {
                // handle percent
                var posStr = scope.pos.substring(0, scope.pos.indexOf('%'));
                var fraction = Number(posStr) / 100;

                if (fraction < 0)
                {
                    fraction = 1 + fraction;
                }

                if (vertical)
                {
                    ev.clientX = width * fraction;
                }
                else
                {
                    ev.clientY = height * fraction;
                }
            }
            else
            {
                // handle pixels
                var pixels = parseInt(scope.pos);
                if (vertical)
                {
                    ev.clientX = pixels < 0 ? width + pixels : pixels;
                }
                else
                {
                    ev.clientY = pixels < 0 ? height + pixels : pixels;
                }
            }

            drag = true;
            resize(ev);
            drag = false;
        }
      }
    };
  })
  .directive('bgPane', function () {
    return {
      restrict: 'E',
      require: '^bgSplitter',
      replace: true,
      transclude: true,
      scope: {
        minSize: '='
      },
      template: '

',
      link: function(scope, element, attrs, bgSplitterCtrl) {
        scope.elem = element;
        scope.index = bgSplitterCtrl.addPane(scope);
      }
    };
  });
<commit_msg>removed debugging info<commit_after>angular.module('bgDirectives', [])
  .directive('bgSplitter', function() {
    return {
      restrict: 'E',
      replace: true,
      transclude: true,
      scope: {
        orientation: '@',
        pos: '@'
      },
      template: '

',
      controller: function ($scope) {
        $scope.panes = [];

        this.addPane = function(pane){
          if ($scope.panes.length > 1)
            throw 'splitters can only have two panes';
          $scope.panes.push(pane);
          return $scope.panes.length;
        };
      },
      link: function(scope, element, attrs) {
        var handler = angular.element('

');
        var pane1 = scope.panes[0];
        var pane2 = scope.panes[1];
        var vertical = scope.orientation == 'vertical';
        var pane1Min = pane1.minSize || 0;
        var pane2Min = pane2.minSize || 0;
        var drag = false;

        pane1.elem.after(handler);

        function resize (ev) {
          if (!drag) return;

          var bounds = element[0].getBoundingClientRect();
          var pos = 0;

          if (vertical) {
            var width = bounds.right - bounds.left;
            pos = ev.clientX - bounds.left;

            if (pos < pane1Min) return;
            if (width - pos < pane2Min) return;

            handler.css('left', pos + 'px');
            pane1.elem.css('width', pos + 'px');
            pane2.elem.css('left', pos + 'px');

          } else {
            var height = bounds.bottom - bounds.top;
            pos = ev.clientY - bounds.top;

            if (pos < pane1Min) return;
            if (height - pos < pane2Min) return;

            handler.css('top', pos + 'px');
            pane1.elem.css('height', pos + 'px');
            pane2.elem.css('top', pos + 'px');
          }
        }

        element.bind('mousemove', resize);

        handler.bind('mousedown', function (ev) {
          ev.preventDefault();
          drag = true;
        });

        angular.element(document).bind('mouseup', function (ev) {
          drag = false;
        });

        if (scope.pos)
        {
            // initialize handler position from pos attribute
            var bounds = element[0].getBoundingClientRect();
            var width = bounds.right - bounds.left;
            var height = bounds.bottom - bounds.top;

            var ev = {
                clientX: 0,
                clientY: 0
            };

            if (scope.pos.indexOf('%') != -1)
            {
                // handle percent
                var posStr = scope.pos.substring(0, scope.pos.indexOf('%'));
                var fraction = Number(posStr) / 100;

                if (fraction < 0)
                {
                    fraction = 1 + fraction;
                }

                if (vertical)
                {
                    ev.clientX = width * fraction;
                }
                else
                {
                    ev.clientY = height * fraction;
                }
            }
            else
            {
                // handle pixels
                var pixels = parseInt(scope.pos);
                if (vertical)
                {
                    ev.clientX = pixels < 0 ? width + pixels : pixels;
                }
                else
                {
                    ev.clientY = pixels < 0 ? height + pixels : pixels;
                }
            }

            drag = true;
            resize(ev);
            drag = false;
        }
      }
    };
  })
  .directive('bgPane', function () {
    return {
      restrict: 'E',
      require: '^bgSplitter',
      replace: true,
      transclude: true,
      scope: {
        minSize: '='
      },
      template: '

',
      link: function(scope, element, attrs, bgSplitterCtrl) {
        scope.elem = element;
        scope.index = bgSplitterCtrl.addPane(scope);
      }
    };
  });
<|endoftext|>


<commit_before>define(['require', 'jquery', 'Terminal', 'Game/Code', 'Phaser',
        'State/Boot', 'State/Preload', 'State/Game', 'Game/Robot',
        'Game/API', 'Game/Settings', 'Game/BlockManager',
        'Levels/Level0', 'Levels/Level1', 'Levels/Level2', 'Levels/Level3', 'Levels/Level99'],
function (require, $, Terminal, Code, Phaser, boot, preload, gm, Robot, API, Settings, BlockManager) {

    var Main = function(phgame) {

        // Start up the game.
        this.game = phgame;
        gm.main = this;
        this.game.state.add('Boot', boot);
        this.game.state.add('Preload', preload);
        this.game.state.add('Game', gm);
        this.game.state.start('Boot');
        this.levelNum = 0;

        this.robot = null;
        this.bg_music = null;

        // The library is accessible by the player
        this.library = new Code(this);

        // Parallax default
        this.parallax = true;

    }

    Main.prototype.mute = function() {

        if (this.bg_music.isPlaying) {
            this.bg_music.pause();
        } else {
            this.bg_music.resume();
        }
    }

    Main.prototype.create = function() {

        // Add sounds
        this.sound_jump = this.game.add.audio('sound_jump');
        this.sound_jetpack = this.game.add.audio('sound_jetpack');

        // Creating a grass block
        this.grassBlock = {
            land : this.game.add.audio('sound_land_dirt'),
            walk : this.game.add.audio('sound_walk_dirt'),
            sprite : this.game.add.sprite('grass_block'),
            blockName : "grass_block",
        }

        this.dirtBlock = {
            land : this.game.add.audio('sound_land_dirt'),
            walk : this.game.add.audio('sound_walk_dirt'),
            sprite : this.game.add.sprite('dirt_block'),
            blockName : "dirt_block",
        }

        // Creating a metal block
        this.metalBlock = {
            land : this.game.add.audio('sound_land_metal'),
            walk : this.game.add.audio('sound_walk_metal'),
            sprite : this.game.add.sprite('metal_block'),
            blockName : "metal_block",
        }

        // Creating a fullMetal block
        this.fullMetalBlock = {
          land : this.game.add.audio('sound_land_metal'),
          walk : this.game.add.audio('sound_walk_metal'),
          sprite : this.game.add.sprite('fullMetalBlock'),
          blockName : "fullMetalBlock",
        }

        this.specialBlock = {
            land : this.game.add.audio('sound_land_concrete'),
            walk : this.game.add.audio('sound_walk_concrete'),
            sprite : this.game.add.sprite('invisible'),
            blockName : "invisible",
        }

        this.woodBlock = {
            land : this.game.add.audio('sound_land_wood'),
            walk : this.game.add.audio('sound_walk_wood'),
            sprite : this.game.add.sprite('wood_block'),
            blockName : "wood_block",
        }

        this.sound_walk_concrete = this.game.add.audio('sound_walk_concrete')
        this.sound_land_concrete = this.game.add.audio('sound_land_concrete')
        this.sound_land_conveyor = this.game.add.audio('sound_land_conveyor')
        this.sound_walk_conveyor = this.game.add.audio('sound_walk_conveyor')

        // Start physics system
        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        // initiate settings
        this.settings = new Settings(this);

        // Initiate terminal
        var term = new Terminal();

        if (this.levelNum == undefined) {
            this.levelNum = 0;
        }
        this.loadLevel(this.levelNum);

        $(window).keypress(function(e){
            console.log(e.which);
            if(e.which == 96){
                var cursor = $('#term .cursor');
                if(cursor.hasClass('blink')){
                    console.log('Selecting game canvas');
                    $('#game').click();
                }else{
                    $('#term .cmd').click();
                }
            }
        });
    }

    Main.prototype.changeLevel = function(level) {
        this.level.destroy();
        this.library.clear();
        this.game.state.restart(true, false, level);
    }

    Main.prototype.loadLevel = function(level) {
        // load the first level
        Level = require('Levels/Level' + level);
        // Create level
        this.level = new Level(this);

        // Follow the robot
        this.game.camera.follow(this.robot.sprite, Phaser.Camera.FOLLOW_PLATFORMER);

        window.help = this.level.help;
    }

    Main.prototype.update = function() {
        // Parallax
        if (typeof this.bg !== "undefined") {
            if (this.parallax) {
                this.bg.position.x = this.game.camera.x/2
                this.bg.position.y = this.game.camera.y/2
            }
        }

        // this.library.update();
        this.api.update();
        this.level.update();
        this.robot.update();
    }

    return Main;
});
<commit_msg>Put reset back.<commit_after>define(['require', 'jquery', 'Terminal', 'Game/Code', 'Phaser',
        'State/Boot', 'State/Preload', 'State/Game', 'Game/Robot',
        'Game/API', 'Game/Settings', 'Game/BlockManager',
        'Levels/Level0', 'Levels/Level1', 'Levels/Level2', 'Levels/Level3', 'Levels/Level99'],
function (require, $, Terminal, Code, Phaser, boot, preload, gm, Robot, API, Settings, BlockManager) {

    var Main = function(phgame) {

        // Start up the game.
        this.game = phgame;
        gm.main = this;
        this.game.state.add('Boot', boot);
        this.game.state.add('Preload', preload);
        this.game.state.add('Game', gm);
        this.game.state.start('Boot');
        this.levelNum = 0;

        this.robot = null;
        this.bg_music = null;

        // The library is accessible by the player
        this.library = new Code(this);

        // Parallax default
        this.parallax = true;

    }

    Main.prototype.mute = function() {

        if (this.bg_music.isPlaying) {
            this.bg_music.pause();
        } else {
            this.bg_music.resume();
        }
    }

    Main.prototype.create = function() {

        // Add sounds
        this.sound_jump = this.game.add.audio('sound_jump');
        this.sound_jetpack = this.game.add.audio('sound_jetpack');

        // Creating a grass block
        this.grassBlock = {
            land : this.game.add.audio('sound_land_dirt'),
            walk : this.game.add.audio('sound_walk_dirt'),
            sprite : this.game.add.sprite('grass_block'),
            blockName : "grass_block",
        }

        this.dirtBlock = {
            land : this.game.add.audio('sound_land_dirt'),
            walk : this.game.add.audio('sound_walk_dirt'),
            sprite : this.game.add.sprite('dirt_block'),
            blockName : "dirt_block",
        }

        // Creating a metal block
        this.metalBlock = {
            land : this.game.add.audio('sound_land_metal'),
            walk : this.game.add.audio('sound_walk_metal'),
            sprite : this.game.add.sprite('metal_block'),
            blockName : "metal_block",
        }

        // Creating a fullMetal block
        this.fullMetalBlock = {
          land : this.game.add.audio('sound_land_metal'),
          walk : this.game.add.audio('sound_walk_metal'),
          sprite : this.game.add.sprite('fullMetalBlock'),
          blockName : "fullMetalBlock",
        }

        this.specialBlock = {
            land : this.game.add.audio('sound_land_concrete'),
            walk : this.game.add.audio('sound_walk_concrete'),
            sprite : this.game.add.sprite('invisible'),
            blockName : "invisible",
        }

        this.woodBlock = {
            land : this.game.add.audio('sound_land_wood'),
            walk : this.game.add.audio('sound_walk_wood'),
            sprite : this.game.add.sprite('wood_block'),
            blockName : "wood_block",
        }

        this.sound_walk_concrete = this.game.add.audio('sound_walk_concrete')
        this.sound_land_concrete = this.game.add.audio('sound_land_concrete')
        this.sound_land_conveyor = this.game.add.audio('sound_land_conveyor')
        this.sound_walk_conveyor = this.game.add.audio('sound_walk_conveyor')

        // Start physics system
        this.game.physics.startSystem(Phaser.Physics.ARCADE);

        // initiate settings
        this.settings = new Settings(this);

        // Initiate terminal
        var term = new Terminal();

        if (this.levelNum == undefined) {
            this.levelNum = 0;
        }
        this.loadLevel(this.levelNum);

        $(window).keypress(function(e){
            console.log(e.which);
            if(e.which == 96){
                var cursor = $('#term .cursor');
                if(cursor.hasClass('blink')){
                    console.log('Selecting game canvas');
                    $('#game').click();
                }else{
                    $('#term .cmd').click();
                }
            }
        });
    }

    Main.prototype.changeLevel = function(level) {
        this.level.destroy();
        this.library.clear();
        this.game.state.restart(true, false, level);
    }

    Main.prototype.loadLevel = function(level) {
        // load the first level
        Level = require('Levels/Level' + level);
        // Create level
        this.level = new Level(this);

        // Follow the robot
        this.game.camera.follow(this.robot.sprite, Phaser.Camera.FOLLOW_PLATFORMER);

        window.help = this.level.help;
        window.reset = this.library.reset;
    }

    Main.prototype.update = function() {
        // Parallax
        if (typeof this.bg !== "undefined") {
            if (this.parallax) {
                this.bg.position.x = this.game.camera.x/2
                this.bg.position.y = this.game.camera.y/2
            }
        }

        // this.library.update();
        this.api.update();
        this.level.update();
        this.robot.update();
    }

    return Main;
});
<|endoftext|>


<commit_before>$(function(){

    $(window).on("hashchange", function(){
      location.reload();
    });

    var ua = navigator.userAgent;
    var ds = milkcocoa.dataStore('fusen');

    var room = "";
    if(location.hash) room = location.hash.slice(1);
    if(room != "") ds = ds.child(room);
    $("#title").val(room);

    function pad (num) { return ("0" + num).substr(-2,2) };
    var today = {
      m: pad( (new Date()).getMonth()+1 ),
      d: pad( (new Date()).getDate() )
    }

    $("#title").attr("placeholder", "例) <your name>_"+today.m+today.d+"_todo")

    // titleの場所で板移動
    $("#title").keypress(function(e){
      if(e.which == 13){
        location.hash = "#"+$(this).val();
      }
    });

    /*
    * 同時接続数を取得するロジック
    */
    var ds_connection = milkcocoa.dataStore("connection_count").child(room);

    // milkcocoaインスタンス生成後、コネクションデータを送信し、その後レンダリングやリスナー設置
    ds_connection.push({}, function(){
      // コネクション数のレンダリングと、コネクション増加時のカウントアップ
      ds_connection.stream().size(999).next(function(err, data) {
        // 堆積したコネクションを削除
        var limit = 1000*45;
        data = data.filter(function(datum){
          var isFresh = (datum.timestamp > data[data.length-1].timestamp - limit);
          if(!isFresh) ds_connection.remove(datum.id);
          return isFresh;
        });

        // 部屋とコネクションを記録
        var _room;
        if(room != "") _room = room;
        else _room = "__root__";

        var ds_room = milkcocoa.dataStore("rooms");
          ds_room.get(_room, function(err, room_data){
            if(err == "not found") room_data = { value : { access: 0 }  };
            room_data.value.access++;
            ds_room.set(_room, {connection: data.length, access: room_data.value.access, updated_at: Date.now()},
              function(err, datum){
                // 成功時
              },
              function(err, datum){
                // セキュリティや制限のエラー
                toast.error("セキュリティおよび負荷の理由で接続に失敗しました");
              }
            );
          });

        // コネクションを表示
        var pushed_count = 0;
        $("title").text("Wowoo("+data.length+")");

        // 他者が接続したらリアルタイム更新
        ds_connection.on("push", function(err, datum){
          pushed_count++;
          $("title").text("Wowoo("+(data.length+pushed_count)+")");
        });

        // 他者が離脱したらリアルタイム更新
        ds_connection.on("remove", function(err, datum){
          pushed_count--;
          $("title").text("Wowoo("+(data.length+pushed_count)+")");
        });
      });

      // ユーザーのアクティブ取得
      var timeout_ids = [];
      ds_connection.stream().size(999).next(function(err, data) {
        var first = data.shift();
        var oldest_count = (first) ? first : {id:""};

        // 常に最新のtimeoutだけが有効になっている
        $(document).on("keypress mousemove click", function(e){
          e.stopPropagation();
          var past_id = timeout_ids.shift();
          clearTimeout(past_id);
          var current_id = setTimeout(function(){
            disconnect_current_connection();
          }, 30000);
          timeout_ids.push(current_id);
        });

        // 画面から離れる際にカウントダウン
        $(window).on("beforeunload", function(e){
          disconnect_current_connection();
        });

        function disconnect_current_connection(){ ds_connection.remove(oldest_count.id); }
      });

    });
    // ここまで

    var curClr = "one";
    var canvas = $("#canvas");
    var fusenBuilder = new FusenBuilder(canvas, ds);

    var device = "pc";
    if(ua.indexOf('iPhone') > 0 || ua.indexOf('iPad') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0) {
        device = "mobile";
    }else{
        device = "pc";
    }

    // select color
    $(".p-colorlist__item").click(function(e){
        curClr = $(this).attr("id");
        $(".p-colorlist__item").each(function(){
            $(this).removeClass("is-active");
        });
        $(this).addClass("is-active");
        e.stopPropagation();
    });

    ds.stream().size(999).sort('desc').next(function(err, datas) {
        for(var i=0;i < datas.length;i++) {
            create_memo(datas[i].id, datas[i].value.x, datas[i].value.y, datas[i].value.text, datas[i].value.color);
        }
    });
    ds.on('push', function(pushed) {
        create_memo(pushed.id, pushed.value.x, pushed.value.y, pushed.value.text, pushed.value.color);
    });
    ds.on('set', function(setted) {
        var fusen = fusenBuilder.getFusen(setted.id);
        fusen.setPos(setted.value.x, setted.value.y);
        fusen.setText(setted.value.text);
    });
    ds.on('remove', function(_removed) {
        var removed = _removed;
        fusenBuilder.getFusen(removed.id).removeSelf();
    });

    function create_memo(id, x, y, _text, color) {
        var text = _text || "";
        var fusen = fusenBuilder.createFusen(id, text, color);
        fusen.setPos(x, y);
    }

    canvas.click(function(e) {
        var $self = $(this);
        e.stopPropagation();

        var offset_x = e.offsetX;
        var offset_y = e.offsetY;
        var page_x = e.pageX;
        var page_y = e.pageY;

        generateBalloon(function(text){
          ds.push({
              x : page_x-53,
              y : page_y-45,
              text : text,
              color : curClr
          }, function(e){
            if(device == "pc") fusen_util.removeBalloon();
          });
        });

        function generateBalloon(cb){
          var text = "";
          if(device == "mobile"){
            text = prompt("メモを入力してください");
            if(!text) {
              toastr.error("Blank text🐶");
              return;
            }
            cb(text);
          } else {
            $(".posting-balloon").remove();
            $self.append('
<input type="text" />
');

            var $input = $(".posting-balloon > input");
            $input.focus();
            $input.off("keypress").on("keypress", function(e){
              if(e.which === 13){
                text = $(this).val();
                if(!text) {
                  toastr.error("Blank text🐶");
                  return;
                }
                cb(text);
              }
            });

            // 吹き出しを消す
            fusen_util.removeBalloonOnESC()
          }
        }
    });

    $("#replay").click(function(e){
      fusenBuilder.replay(function(fusensByOrder){
        setInterval(function(){
          var fusen = fusensByOrder.shift();
          create_memo(fusen.id, fusen.pos.x, fusen.pos.y, fusen.text, fusen.color);
        }, 750);
      });
    });

    window.fusen_util = {
        getDevice : function() {
            return device;
        },
        htmlEscape : function(s) {
            s=s.replace(/&/g,'&');
            s=s.replace(/>/g,'>');
            s=s.replace(/</g,'<');
            return s;
        },
        copy : function (text){
          // clipboard.jsを使う
          // promptを使わない
          /*
          document.addEventListener('copy', function(e) {
            e.preventDefault();
            if (e.clipboardData) {
              e.preventDefault();
              e.clipboardData.setData('text/plain', "Hello");
            }
            if (window.clipboardData) {
              e.returnValue = false;
              window.clipboardData.setData('text/plain', "World");
            }
          }, false);

          */
          $(document).trigger("copy");
        },
        userAgent : function(){
          return window.navigator.userAgent.toLowerCase();
        },
    		linknize : function (escapedText) {
    		  // とりあえず高階関数で実装
    			var http_regexp = /https?:\/\/.+(\ |$)/;
    			var linkedText = escapedText.split(" ").map(function(_t){
    				var found = _t.match(http_regexp);
    				if (found) {
    					var url = found[0];
    					var short_url = url.split(/\/\//)[1];
    					var _t = _t.replace(http_regexp, ""+short_url+"" ) ;
    				}
    				return _t;
    			}).join(" ");

    			linkedText = hashnize(linkedText);
    			return linkedText;

    			function hashnize(linkedText) {
    				// hashをリンク化
    				var hash_regexp = /^#.+/;
    				var hashedText = linkedText.split(" ").map(function(_t){
    					if ( _t.match(hash_regexp) ) {
    						var url = location.href + _t;
    						_t = _t.replace(hash_regexp, ""+_t+"");
    					}
    					return _t;
    				}).join(" ");
    				return hashedText;
    			}
    		},
        removeBalloonOnESC : function (){
          $(document).off("keyup").on("keyup", function(e) {
             if (e.keyCode == 27) fusen_util.removeBalloon();
          });
        },
        removeBalloon : function (){
          $(".posting-balloon").remove();
        },
        zoomIn : function (zoomLev) {
            if (zoomLev > 1) {
                if (typeof (document.body.style.zoom) != "undefined") {
                    $(document.body).css('zoom', zoomLev);
                }else {
                    // Mozilla doesn't support zoom, use -moz-transform to scale and compensate for lost width
                    $('#divWrap').css({
                        "-moz-transform": 'scale(" + zoomLev + ")',
                        width: $(window).width() / zoomLev
                    });
                }
            }
        }
    }

    // スマホならズーム
    if(device == "mobile") fusen_util.zoomIn(2.0);

});
<commit_msg>zoom timing tweaked<commit_after>$(function(){

    $(window).on("hashchange", function(){
      location.reload();
    });

    var ua = navigator.userAgent;
    var ds = milkcocoa.dataStore('fusen');

    var room = "";
    if(location.hash) room = location.hash.slice(1);
    if(room != "") ds = ds.child(room);
    $("#title").val(room);

    function pad (num) { return ("0" + num).substr(-2,2) };
    var today = {
      m: pad( (new Date()).getMonth()+1 ),
      d: pad( (new Date()).getDate() )
    }

    $("#title").attr("placeholder", "例) <your name>_"+today.m+today.d+"_todo")

    // titleの場所で板移動
    $("#title").keypress(function(e){
      if(e.which == 13){
        location.hash = "#"+$(this).val();
      }
    });

    /*
    * 同時接続数を取得するロジック
    */
    var ds_connection = milkcocoa.dataStore("connection_count").child(room);

    // milkcocoaインスタンス生成後、コネクションデータを送信し、その後レンダリングやリスナー設置
    ds_connection.push({}, function(){
      // コネクション数のレンダリングと、コネクション増加時のカウントアップ
      ds_connection.stream().size(999).next(function(err, data) {
        // 堆積したコネクションを削除
        var limit = 1000*45;
        data = data.filter(function(datum){
          var isFresh = (datum.timestamp > data[data.length-1].timestamp - limit);
          if(!isFresh) ds_connection.remove(datum.id);
          return isFresh;
        });

        // 部屋とコネクションを記録
        var _room;
        if(room != "") _room = room;
        else _room = "__root__";

        var ds_room = milkcocoa.dataStore("rooms");
          ds_room.get(_room, function(err, room_data){
            if(err == "not found") room_data = { value : { access: 0 }  };
            room_data.value.access++;
            ds_room.set(_room, {connection: data.length, access: room_data.value.access, updated_at: Date.now()},
              function(err, datum){
                // 成功時
              },
              function(err, datum){
                // セキュリティや制限のエラー
                toast.error("セキュリティおよび負荷の理由で接続に失敗しました");
              }
            );
          });

        // コネクションを表示
        var pushed_count = 0;
        $("title").text("Wowoo("+data.length+")");

        // 他者が接続したらリアルタイム更新
        ds_connection.on("push", function(err, datum){
          pushed_count++;
          $("title").text("Wowoo("+(data.length+pushed_count)+")");
        });

        // 他者が離脱したらリアルタイム更新
        ds_connection.on("remove", function(err, datum){
          pushed_count--;
          $("title").text("Wowoo("+(data.length+pushed_count)+")");
        });
      });

      // ユーザーのアクティブ取得
      var timeout_ids = [];
      ds_connection.stream().size(999).next(function(err, data) {
        var first = data.shift();
        var oldest_count = (first) ? first : {id:""};

        // 常に最新のtimeoutだけが有効になっている
        $(document).on("keypress mousemove click", function(e){
          e.stopPropagation();
          var past_id = timeout_ids.shift();
          clearTimeout(past_id);
          var current_id = setTimeout(function(){
            disconnect_current_connection();
          }, 30000);
          timeout_ids.push(current_id);
        });

        // 画面から離れる際にカウントダウン
        $(window).on("beforeunload", function(e){
          disconnect_current_connection();
        });

        function disconnect_current_connection(){ ds_connection.remove(oldest_count.id); }
      });

    });
    // ここまで

    var curClr = "one";
    var canvas = $("#canvas");
    var fusenBuilder = new FusenBuilder(canvas, ds);

    var device = "pc";
    if(ua.indexOf('iPhone') > 0 || ua.indexOf('iPad') > 0 || ua.indexOf('iPod') > 0 || ua.indexOf('Android') > 0) {
        device = "mobile";
    }else{
        device = "pc";
    }

    // select color
    $(".p-colorlist__item").click(function(e){
        curClr = $(this).attr("id");
        $(".p-colorlist__item").each(function(){
            $(this).removeClass("is-active");
        });
        $(this).addClass("is-active");
        e.stopPropagation();
    });

    ds.stream().size(999).sort('desc').next(function(err, datas) {
        for(var i=0;i < datas.length;i++) {
            create_memo(datas[i].id, datas[i].value.x, datas[i].value.y, datas[i].value.text, datas[i].value.color);
        }

        // 付箋設置後に、スマホならズーム
        if(device == "mobile") fusen_util.zoomIn(2.0);
    });
    ds.on('push', function(pushed) {
        create_memo(pushed.id, pushed.value.x, pushed.value.y, pushed.value.text, pushed.value.color);
    });
    ds.on('set', function(setted) {
        var fusen = fusenBuilder.getFusen(setted.id);
        fusen.setPos(setted.value.x, setted.value.y);
        fusen.setText(setted.value.text);
    });
    ds.on('remove', function(_removed) {
        var removed = _removed;
        fusenBuilder.getFusen(removed.id).removeSelf();
    });

    function create_memo(id, x, y, _text, color) {
        var text = _text || "";
        var fusen = fusenBuilder.createFusen(id, text, color);
        fusen.setPos(x, y);
    }

    canvas.click(function(e) {
        var $self = $(this);
        e.stopPropagation();

        var offset_x = e.offsetX;
        var offset_y = e.offsetY;
        var page_x = e.pageX;
        var page_y = e.pageY;

        generateBalloon(function(text){
          ds.push({
              x : page_x-53,
              y : page_y-45,
              text : text,
              color : curClr
          }, function(e){
            if(device == "pc") fusen_util.removeBalloon();
          });
        });

        function generateBalloon(cb){
          var text = "";
          if(device == "mobile"){
            text = prompt("メモを入力してください");
            if(!text) {
              toastr.error("Blank text🐶");
              return;
            }
            cb(text);
          } else {
            $(".posting-balloon").remove();
            $self.append('
<input type="text" />
');

            var $input = $(".posting-balloon > input");
            $input.focus();
            $input.off("keypress").on("keypress", function(e){
              if(e.which === 13){
                text = $(this).val();
                if(!text) {
                  toastr.error("Blank text🐶");
                  return;
                }
                cb(text);
              }
            });

            // 吹き出しを消す
            fusen_util.removeBalloonOnESC()
          }
        }
    });

    $("#replay").click(function(e){
      fusenBuilder.replay(function(fusensByOrder){
        setInterval(function(){
          var fusen = fusensByOrder.shift();
          create_memo(fusen.id, fusen.pos.x, fusen.pos.y, fusen.text, fusen.color);
        }, 750);
      });
    });

    window.fusen_util = {
        getDevice : function() {
            return device;
        },
        htmlEscape : function(s) {
            s=s.replace(/&/g,'&');
            s=s.replace(/>/g,'>');
            s=s.replace(/</g,'<');
            return s;
        },
        copy : function (text){
          // clipboard.jsを使う
          // promptを使わない
          /*
          document.addEventListener('copy', function(e) {
            e.preventDefault();
            if (e.clipboardData) {
              e.preventDefault();
              e.clipboardData.setData('text/plain', "Hello");
            }
            if (window.clipboardData) {
              e.returnValue = false;
              window.clipboardData.setData('text/plain', "World");
            }
          }, false);

          */
          $(document).trigger("copy");
        },
        userAgent : function(){
          return window.navigator.userAgent.toLowerCase();
        },
    		linknize : function (escapedText) {
    		  // とりあえず高階関数で実装
    			var http_regexp = /https?:\/\/.+(\ |$)/;
    			var linkedText = escapedText.split(" ").map(function(_t){
    				var found = _t.match(http_regexp);
    				if (found) {
    					var url = found[0];
    					var short_url = url.split(/\/\//)[1];
    					var _t = _t.replace(http_regexp, ""+short_url+"" ) ;
    				}
    				return _t;
    			}).join(" ");

    			linkedText = hashnize(linkedText);
    			return linkedText;

    			function hashnize(linkedText) {
    				// hashをリンク化
    				var hash_regexp = /^#.+/;
    				var hashedText = linkedText.split(" ").map(function(_t){
    					if ( _t.match(hash_regexp) ) {
    						var url = location.href + _t;
    						_t = _t.replace(hash_regexp, ""+_t+"");
    					}
    					return _t;
    				}).join(" ");
    				return hashedText;
    			}
    		},
        removeBalloonOnESC : function (){
          $(document).off("keyup").on("keyup", function(e) {
             if (e.keyCode == 27) fusen_util.removeBalloon();
          });
        },
        removeBalloon : function (){
          $(".posting-balloon").remove();
        },
        zoomIn : function (zoomLev) {
            if (zoomLev > 1) {
                if (typeof (document.body.style.zoom) != "undefined") {
                    $(document.body).css('zoom', zoomLev);
                }else {
                    // Mozilla doesn't support zoom, use -moz-transform to scale and compensate for lost width
                    $('#divWrap').css({
                        "-moz-transform": 'scale(" + zoomLev + ")',
                        width: $(window).width() / zoomLev
                    });
                }
            }
        }
    }

});
<|endoftext|>