<commit_before>
function setupDialDialog() {
    var connection;
    var inCall = false;
    var $dialog = $('#dialog-dial');
    var $input = $dialog.find('.dial-input');
    var $status = $dialog.find('.dial-status');
    var $doHangup = $dialog.find('.do-hangup');
    var $doCall = $dialog.find('.do-call');

    var toggleCallStatus = function(){
        $doCall.toggle(!inCall);
        $doHangup.text(inCall? "Hangup" : "Close");
    }

    $dialog.find('.dial-button').click(function(e) {
        e.preventDefault();
        var value = $(e.currentTarget).val();

        if (connection) {
            connection.sendDigits(value);
        } else {
            $input.val($dialInput.val()+value);
        }
    });

    Twilio.Device.setup($dialog.find('input[name=token]').val());

    $doCall.click(function() {
        params = { "tocall" : $input.val()};
        connection = Twilio.Device.connect(params);
    });
    $doHangup.click(function() {
        Twilio.Device.disconnectAll();
    });

    Twilio.Device.ready(function (device) {
        console.log("Ready");
        $status.text('Ready to start call');
    });

    Twilio.Device.incoming(function (conn) {
        if (confirm('Accept incoming call from ' + conn.parameters.From + '?')) {
            $dialog.addClass('active');
            connection = conn;
            conn.accept();
        }
    });

    Twilio.Device.offline(function (device) {
        console.log("Offline");
        $status.text('Offline');
    });

    Twilio.Device.error(function (error) {
        console.log("Error", error);
        $status.text("Error: "+error.message.message);
    });

    Twilio.Device.connect(function (conn) {
        console.log("Connected");
        $status.text("Successfully established call");
        inCall = true;
        toggleCallStatus();
    });

    Twilio.Device.disconnect(function (conn) {
        console.log("Disconnected");
        if (inCall) $status.text("Call ended");
        inCall = false;
        toggleCallStatus();
    });

    toggleCallStatus();
}

// Click to toggle dialog
function setupDialogs() {
    $('*[data-dialog]').click(function(e) {
        e.preventDefault();
        var dialog = $(e.currentTarget).attr('data-dialog');

        $('#dialog-'+dialog).toggleClass('active');
    });
}

// Setup audio player
function setupAudioPlayers() {
    $('.audio-player').each(function() {
        var $player = $(this);
        var audio = $player.find('audio').get(0);
        var $position = $player.find('.position');
        var loaded = false;

        audio.onplaying = function() {
            $player.addClass('playing');
            $player.removeClass('paused');
        };
        audio.onpause = function() {
            $player.addClass('playing');
            $player.addClass('paused');
        };
        audio.onended = function() {
            $player.removeClass('playing');
            $player.removeClass('paused');
        };
        audio.ontimeupdate = function() {
            var t = audio.currentTime;
            var msg = "";

            msg = Math.floor(t/60)+':'+Math.ceil(t % 60);

            $position.text(msg);
        };

        $player.find('.do-play').click(function(e) {
            e.preventDefault();
            if (!loaded) {
                audio.load();
                loaded = true;
            }
            audio.play();
        });

        $player.find('.do-pause').click(function(e) {
            e.preventDefault();
            audio.pause();
        });

        $player.find('.do-stop').click(function(e) {
            e.preventDefault();
            audio.pause();
            audio.currentTime = 0;
        });
    });
}

// Handle call and sms links in the app
function setupLinks() {
    $('a').click(function(e) {
        var $a = $(e.currentTarget);
        var val = decodeURIComponent($a.attr('href'));

        if (val.indexOf('tel:') === 0) {
            e.preventDefault();
            $('#dialog-dial').addClass('active')
                .find('.dial-input')
                .val(val.slice('tel:'.length));

        } else if (val.indexOf('sms:') === 0) {
            e.preventDefault();
            $('#dialog-sms').addClass('active')
                .find('.dial-input')
                .val(val.slice('tel:'.length));
        }
    })
}

$(document).ready(function() {
    setupDialogs();
    setupAudioPlayers();
    setupDialDialog();
    setupLinks();
});
<commit_msg>Handle esc key to close dialogs<commit_after>
function setupDialDialog() {
    var connection;
    var inCall = false;
    var $dialog = $('#dialog-dial');
    var $input = $dialog.find('.dial-input');
    var $status = $dialog.find('.dial-status');
    var $doHangup = $dialog.find('.do-hangup');
    var $doCall = $dialog.find('.do-call');

    var toggleCallStatus = function(){
        $doCall.toggle(!inCall);
        $doHangup.text(inCall? "Hangup" : "Close");
    }

    $dialog.find('.dial-button').click(function(e) {
        e.preventDefault();
        var value = $(e.currentTarget).val();

        if (connection) {
            connection.sendDigits(value);
        } else {
            $input.val($dialInput.val()+value);
        }
    });

    Twilio.Device.setup($dialog.find('input[name=token]').val());

    $doCall.click(function() {
        params = { "tocall" : $input.val()};
        connection = Twilio.Device.connect(params);
    });
    $doHangup.click(function() {
        Twilio.Device.disconnectAll();
    });

    Twilio.Device.ready(function (device) {
        console.log("Ready");
        $status.text('Ready to start call');
    });

    Twilio.Device.incoming(function (conn) {
        if (confirm('Accept incoming call from ' + conn.parameters.From + '?')) {
            $dialog.addClass('active');
            connection = conn;
            conn.accept();
        }
    });

    Twilio.Device.offline(function (device) {
        console.log("Offline");
        $status.text('Offline');
    });

    Twilio.Device.error(function (error) {
        console.log("Error", error);
        $status.text("Error: "+error.message.message);
    });

    Twilio.Device.connect(function (conn) {
        console.log("Connected");
        $status.text("Successfully established call");
        inCall = true;
        toggleCallStatus();
    });

    Twilio.Device.disconnect(function (conn) {
        console.log("Disconnected");
        if (inCall) $status.text("Call ended");
        inCall = false;
        toggleCallStatus();
    });

    toggleCallStatus();
}

// Click to toggle dialog
function setupDialogs() {
    $('*[data-dialog]').click(function(e) {
        e.preventDefault();
        var dialog = $(e.currentTarget).attr('data-dialog');

        $('#dialog-'+dialog).toggleClass('active');
    });

    $(document).keyup(function(e) {
        if (e.keyCode == 27) $('.dialog-container').removeClass('active');
    });
}

// Setup audio player
function setupAudioPlayers() {
    $('.audio-player').each(function() {
        var $player = $(this);
        var audio = $player.find('audio').get(0);
        var $position = $player.find('.position');
        var loaded = false;

        audio.onplaying = function() {
            $player.addClass('playing');
            $player.removeClass('paused');
        };
        audio.onpause = function() {
            $player.addClass('playing');
            $player.addClass('paused');
        };
        audio.onended = function() {
            $player.removeClass('playing');
            $player.removeClass('paused');
        };
        audio.ontimeupdate = function() {
            var t = audio.currentTime;
            var msg = "";

            msg = Math.floor(t/60)+':'+Math.ceil(t % 60);

            $position.text(msg);
        };

        $player.find('.do-play').click(function(e) {
            e.preventDefault();
            if (!loaded) {
                audio.load();
                loaded = true;
            }
            audio.play();
        });

        $player.find('.do-pause').click(function(e) {
            e.preventDefault();
            audio.pause();
        });

        $player.find('.do-stop').click(function(e) {
            e.preventDefault();
            audio.pause();
            audio.currentTime = 0;
        });
    });
}

// Handle call and sms links in the app
function setupLinks() {
    $('a').click(function(e) {
        var $a = $(e.currentTarget);
        var val = decodeURIComponent($a.attr('href'));

        if (val.indexOf('tel:') === 0) {
            e.preventDefault();
            $('#dialog-dial').addClass('active')
                .find('.dial-input')
                .val(val.slice('tel:'.length));

        } else if (val.indexOf('sms:') === 0) {
            e.preventDefault();
            $('#dialog-sms').addClass('active')
                .find('.dial-input')
                .val(val.slice('tel:'.length));
        }
    })
}

$(document).ready(function() {
    setupDialogs();
    setupAudioPlayers();
    setupDialDialog();
    setupLinks();
});
<|endoftext|>


<commit_before>$(document).ready(function() {

  $('[data-slidepanel]').slidepanel({
      orientation: 'left',
      mode: 'push'
  });
});<commit_msg>the problems are with the highlight script<commit_after>$(document).ready(function() {

  $('[data-slidepanel]').slidepanel({
      orientation: 'left',
      mode: 'push'
  });

  hljs.initHighlightingOnLoad();
});<|endoftext|>


<commit_before>/*
 * messages
 * https://github.com/yola/jquery-messages
 *
 * Copyright (c) 2013 kahnjw
 * Licensed under the MIT license.
 */

;(function($){
    'use strict';
    var pluginName = 'Messages',
        defaults = {
            alert_classes: {
                'info': 'alert-info',
                'loading': 'alert-info loading',
                'error': 'alert-error alert-danger',
                'success': 'alert-success',
                'alert': 'alert'
            }
        };

    $.fn.message = function(options){
        return this.each(function() {
            $.data(this, 'plugin_' + pluginName,
            new Messages(this, options));
        });
    };

    $.message = {};

    $.message.close = function(selector) {
        $(selector).remove();
    };

    $.message.closeAll = function(classes) {
        if(classes !== undefined){
            defaults.alert_classes = classes;
        }
        $.each(defaults.alert_classes, function(key, value){
            $('.' + value).remove();
        });
    };

    function Messages(element, options){
        this.element = element;
        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        if (this.options.clean === true || this.options.clean === false) {
            this.clean = this.options.clean;
        }
        else { this.clean = true; }

        if(this.buildMessage()) {
            this.cleanMessages();
            this.insertMessage();
        }
    }

    Messages.prototype.buildMessage = function(){
        var element_attribute = $(this.element).data(this.options.message_attribute);
        var body_attribute = $(document.body).data(this.options.message_attribute);
        var fallback_attribute = $(document.body).data(this.options.fallback_message_attribute);

        if (this.options.message_attribute && element_attribute) {
            this.message_details = element_attribute;
        }
        else if (this.options.message) {
            this.message_details = this.options.message;
        }
        else if (this.options.message_attribute && body_attribute) {
            this.message_details = body_attribute;
        }
        else if (this.options.fallback_message_attribute && fallback_attribute) {
            this.message_details = fallback_attribute;
        }
        else {
            this.message_details = { message: this.options.default_message };
        }

        if (this.message_details.constructor === String) {
            this.message_details = { message: this.message_details };
        }

        return this.message_details.message !== undefined;
    };

    Messages.prototype.cleanMessages = function(){
        if (this.clean) {
            var this_element = this.element;
            $.each(this.options.alert_classes, function(key, value) {
                $(this_element).find('.' + value).slideUp(200, function() {
                    $(this).remove();
                });
            });
        }
    };

    Messages.prototype.findStyleClass = function(){
        var this_options = this.options;
        var message_class = '';

        $.each(this.options.alert_classes, function(key, value) {
            if (this_options.message_type === key) { message_class = value; }
        });

        return message_class;
    };

    Messages.prototype.insertMessage = function(){
        var message_class = this.findStyleClass();

        var message = $('<div>').attr('class', 'alert ' + message_class);
        if (this.message_details.hasOwnProperty('message')) {
            message.html(this.message_details.message);
        }
        else {
            message.html(this.message_details);
        }

        var element = null;
        if(this.message_details.field_name){
            var element_selector = '[name="' + this.message_details.field_name + '"]';
            element = $(this.element).find(element_selector);
            message.attr('class', 'fieldError alert ' + message_class).hide();
            element.parent().append(message);
            message.slideDown(200);
            return;
        }

        if (this.options.attach_to) {
            element = $(this.element).find(this.options.attach_to);
            message.attr('class', 'fieldError alert ' + message_class).hide();
            element.after(message);
            message.slideDown(200);
            return;
        }

        $(this.element).prepend(message.hide());
        message.slideDown(200);
    };
})(jQuery);
<commit_msg>Make query slide in feature optional<commit_after>/*
 * messages
 * https://github.com/yola/jquery-messages
 *
 * Copyright (c) 2013 kahnjw
 * Licensed under the MIT license.
 */

;(function($){
    'use strict';
    var pluginName = 'Messages',
        defaults = {
            alert_classes: {
                'info': 'alert-info',
                'loading': 'alert-info loading',
                'error': 'alert-error alert-danger',
                'success': 'alert-success',
                'alert': 'alert'
            }
        };

    $.fn.message = function(options){
        return this.each(function() {
            $.data(this, 'plugin_' + pluginName,
            new Messages(this, options));
        });
    };

    $.message = {};

    $.message.close = function(selector) {
        $(selector).remove();
    };

    $.message.closeAll = function(classes) {
        if(classes !== undefined){
            defaults.alert_classes = classes;
        }
        $.each(defaults.alert_classes, function(key, value){
            $('.' + value).remove();
        });
    };

    function Messages(element, options){
        this.element = element;
        this.options = $.extend({}, defaults, options);

        this._defaults = defaults;
        this._name = pluginName;

        if (this.options.clean === true || this.options.clean === false) {
            this.clean = this.options.clean;
        }
        else { this.clean = true; }

        if (this.options.slideIn === true || this.options.slideIn === false) {
            this.slideIn = this.options.slideIn;
        }
        else { this.slideIn = false; }

        if(this.buildMessage()) {
            this.cleanMessages();
            this.insertMessage();
        }
    }

    Messages.prototype.buildMessage = function(){
        var element_attribute = $(this.element).data(this.options.message_attribute);
        var body_attribute = $(document.body).data(this.options.message_attribute);
        var fallback_attribute = $(document.body).data(this.options.fallback_message_attribute);

        if (this.options.message_attribute && element_attribute) {
            this.message_details = element_attribute;
        }
        else if (this.options.message) {
            this.message_details = this.options.message;
        }
        else if (this.options.message_attribute && body_attribute) {
            this.message_details = body_attribute;
        }
        else if (this.options.fallback_message_attribute && fallback_attribute) {
            this.message_details = fallback_attribute;
        }
        else {
            this.message_details = { message: this.options.default_message };
        }

        if (this.message_details.constructor === String) {
            this.message_details = { message: this.message_details };
        }

        return this.message_details.message !== undefined;
    };

    Messages.prototype.cleanMessages = function(){
        if (this.clean) {
            var this_element = this.element;
            $.each(this.options.alert_classes, function(key, value) {
                $(this_element).find('.' + value).slideUp(200, function() {
                    $(this).remove();
                });
            });
        }
    };

    Messages.prototype.findStyleClass = function(){
        var this_options = this.options;
        var message_class = '';

        $.each(this.options.alert_classes, function(key, value) {
            if (this_options.message_type === key) { message_class = value; }
        });

        return message_class;
    };

    Messages.prototype.insertMessage = function(){
        var message_class = this.findStyleClass();

        var message = $('<div>').attr('class', 'alert ' + message_class);
        if (this.message_details.hasOwnProperty('message')) {
            message.html(this.message_details.message);
        }
        else {
            message.html(this.message_details);
        }

        var element = null;
        if(this.message_details.field_name){
            var element_selector = '[name="' + this.message_details.field_name + '"]';
            element = $(this.element).find(element_selector);
            message.attr('class', 'fieldError alert ' + message_class).hide();
            element.parent().append(message);

            if(this.slideIn) { message.slideDown(200); }
            else { message.show(); }

            return;
        }

        if (this.options.attach_to) {
            element = $(this.element).find(this.options.attach_to);
            message.attr('class', 'fieldError alert ' + message_class).hide();
            element.after(message);

            if(this.slideIn) { message.slideDown(200); }
            else { message.show(); }

            return;
        }

        $(this.element).prepend(message.hide());

        if(this.slideIn) { message.slideDown(200); }
        else { message.show(); }
    };
})(jQuery);
<|endoftext|>


<commit_before>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

//var geometry = new THREE.BoxGeometry( 9, 9, 9 );
////var material = new THREE.MeshPhongMaterial( { color: 0xff55ff } );
//var material = new THREE.MeshLambertMaterial({color: 0xff55ff, transparent: true, opacity: 0.3});
//var cube = new THREE.Mesh( geometry, material );
//scene.add( cube );
//
//var geometry2 = new THREE.BoxGeometry( 1, 1, 1 );
//var material2 = new THREE.MeshPhongMaterial( { color: 0xff99ff } );
//var cube2 = new THREE.Mesh( geometry2, material2 );
//scene.add( cube2 );
//cube2.position.x=2;
//
//var geometry3 = new THREE.BoxGeometry( 1, 1, 1 );
//var material3 = new THREE.MeshPhongMaterial( { color: 0xffffff } );
//var cube3 = new THREE.Mesh( geometry3, material3 );
//scene.add( cube3 );
//cube3.position.x=-2;

console.log(1);
console.log(2);
var x=0.0;

for(var i=1; i<10; i++){
    var name="cube"+i;
    x=x+1;
    console.log(name) ;
    var geometry = new THREE.BoxGeometry( 1,1,1 );
    var material = new THREE.MeshLambertMaterial({color: 0xff55ff, transparent: true, opacity: 0.3});
    var cube = new THREE.Mesh( geometry, material );
    cube.position.x=x;
    cube.name=name;
    scene.add( cube );
}

camera.position.z = 15;

addLights();

function addLights() {
    var dirLight = new THREE.DirectionalLight(0xffffff, 1);
    dirLight.position.set(100, 100, 50);
    scene.add(dirLight);
    var ambLight = new THREE.AmbientLight(0x404040);
    scene.add(ambLight);
};

var render = function () {
    requestAnimationFrame( render );

    for(var j=0; j<10; j++)  {
        var cube = scene.getObjectByName("cube"+j, true );
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;
    }
    //cube2.rotation.x += 0.01;
    //cube2.rotation.y += 0.01;
    //cube3.rotation.x += 0.01;
    //cube3.rotation.y += 0.01;

    renderer.render(scene, camera);
};

render();

<commit_msg>something awesome cause I'm awesome<commit_after>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

//var geometry = new THREE.BoxGeometry( 9, 9, 9 );
////var material = new THREE.MeshPhongMaterial( { color: 0xff55ff } );
//var material = new THREE.MeshLambertMaterial({color: 0xff55ff, transparent: true, opacity: 0.3});
//var cube = new THREE.Mesh( geometry, material );
//scene.add( cube );
//
//var geometry2 = new THREE.BoxGeometry( 1, 1, 1 );
//var material2 = new THREE.MeshPhongMaterial( { color: 0xff99ff } );
//var cube2 = new THREE.Mesh( geometry2, material2 );
//scene.add( cube2 );
//cube2.position.x=2;
//
//var geometry3 = new THREE.BoxGeometry( 1, 1, 1 );
//var material3 = new THREE.MeshPhongMaterial( { color: 0xffffff } );
//var cube3 = new THREE.Mesh( geometry3, material3 );
//scene.add( cube3 );
//cube3.position.x=-2;

console.log(1);
console.log(2);
var x=0.0;

for(var i=1; i<10; i++){
    var name="cube"+i;
    x=x+2;
    console.log(name) ;
    var geometry = new THREE.BoxGeometry( 1,1,1 );
    var material = new THREE.MeshLambertMaterial({color: 0xff55ff, transparent:false, opacity: 0.3});
    var cube = new THREE.Mesh( geometry, material );
    cube.position.x=x;
    cube.name=name;
    scene.add( cube );
}

camera.position.z = 15;

addLights();

function addLights() {
    var dirLight = new THREE.DirectionalLight(0xffffff, 1);
    dirLight.position.set(100, 100, 50);
    scene.add(dirLight);
    var ambLight = new THREE.AmbientLight(0x404040);
    scene.add(ambLight);
};

var render = function () {
    requestAnimationFrame( render );

    for(var j=1; j<10; j++)  {
        var cube = scene.getObjectByName("cube"+j, true );
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;
    }
    //cube2.rotation.x += 0.01;
    //cube2.rotation.y += 0.01;
    //cube3.rotation.x += 0.01;
    //cube3.rotation.y += 0.01;

    renderer.render(scene, camera);
};

render();

<|endoftext|>


<commit_before>// CONFIG (Move to different file)
var endpoint = {
  points: 'points'
};

var markerImage = 'http://www.meadowsfield.com/wp-content/uploads/2013/09/map-icon-64.png';

var appUrl = window.location.href + 'api/';

// END CONFIG

var request = function (options) {
  var xhr = new XMLHttpRequest();
  xhr.open(options.method, options.url);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.addEventListener('load', function(event){
    options.callback(JSON.parse(event.target.responseText));
  });
  xhr.send(JSON.stringify(options.data || {}));
};
///////////////////////////////////////////////////
//
// Socket stuff
var socket = io.connect(window.location.href);
function updateMarker (location) {
  var coords = location.coordinates;
  var marker = Markers.find(location.id);
  if(!marker) {
    marker = Markers.create(coords, locadtion.id);
    return marker;
  }
  marker.setPosition(new google.maps.LatLng(coords[0], coords[1]));
}
socket.on('updateLocation', updateMarker);

socket.on('locations', function (locations) {
  locations.forEach(updateMarker);
});
// Socket stuff end

function initialize() {
  var mapCanvas = document.getElementById('map_canvas');
  mapCanvas.style.height = window.innerHeight + 'px';
  var mapOptions = {
    center: new google.maps.LatLng(44.5403, -78.5463),
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.HYBRID
  };
  var map = new google.maps.Map(mapCanvas, mapOptions);
  window.map = map;
}

var Markers = (function () {

  var markers = {};

  var create = function (coords, id) {
    id = id || Math.random().toString(26).slice(3);
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(coords[0], coords[1]),
      icon: markerImage,
      map: map
    });
    markers[id] = marker;
    marker.id = id;
    return marker;
  };

  var find = function (id) {
    return markers[id] || null;
  };

  return {
    create: create,
    find: find
  };

}());

function convertPoints(points){
  return points.map(function(point){
    return {position: new google.maps.LatLng(point.loc.coordinates[0], point.loc.coordinates[1]),
      icon: markerImage,
      map: map
    };
  });
}

function addMarker(feature) {
  var marker = new google.maps.Marker({
    position: feature.position,
    icon: feature.icon,
    map: map
  });
}

function submitLocation(data) {
  socket.emit('location', data);
}
function success (position) {
  var data = {
    coordinates: [position.coords.latitude, position.coords.longitude]
  };
  var marker = Markers.create(data.coordinates);
  data.id = marker.id;
  submitLocation(data);
}

function error () {
  alert('BASE HAS BEEN FUCKED');
}

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    var coords = position.coords;
    var location = new google.maps.LatLng(coords.latitude, coords.longitude);
    map.setCenter(location);
  }, error);

  var geoOptions = { timeout: 30 * 1000, enableHighAccuracy: false };
  navigator.geolocation.watchPosition(success, error, geoOptions);
} else {
  console.log('Permission denied');
}

initialize();
<commit_msg>hotfix<commit_after>// CONFIG (Move to different file)
var endpoint = {
  points: 'points'
};

var markerImage = 'http://www.meadowsfield.com/wp-content/uploads/2013/09/map-icon-64.png';

var appUrl = window.location.href + 'api/';

// END CONFIG

var request = function (options) {
  var xhr = new XMLHttpRequest();
  xhr.open(options.method, options.url);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.addEventListener('load', function(event){
    options.callback(JSON.parse(event.target.responseText));
  });
  xhr.send(JSON.stringify(options.data || {}));
};
///////////////////////////////////////////////////
//
// Socket stuff
var socket = io.connect(window.location.href);
function updateMarker (location) {
  var coords = location.coordinates;
  var marker = Markers.find(location.id);
  if(!marker) {
    marker = Markers.create(coords, location.id);
    return marker;
  }
  marker.setPosition(new google.maps.LatLng(coords[0], coords[1]));
}
socket.on('updateLocation', updateMarker);

socket.on('locations', function (locations) {
  locations.forEach(updateMarker);
});
// Socket stuff end

function initialize() {
  var mapCanvas = document.getElementById('map_canvas');
  mapCanvas.style.height = window.innerHeight + 'px';
  var mapOptions = {
    center: new google.maps.LatLng(44.5403, -78.5463),
    zoom: 10,
    mapTypeId: google.maps.MapTypeId.HYBRID
  };
  var map = new google.maps.Map(mapCanvas, mapOptions);
  window.map = map;
}

var Markers = (function () {

  var markers = {};

  var create = function (coords, id) {
    id = id || Math.random().toString(26).slice(3);
    var marker = new google.maps.Marker({
      position: new google.maps.LatLng(coords[0], coords[1]),
      icon: markerImage,
      map: map
    });
    markers[id] = marker;
    marker.id = id;
    return marker;
  };

  var find = function (id) {
    return markers[id] || null;
  };

  return {
    create: create,
    find: find
  };

}());

function convertPoints(points){
  return points.map(function(point){
    return {position: new google.maps.LatLng(point.loc.coordinates[0], point.loc.coordinates[1]),
      icon: markerImage,
      map: map
    };
  });
}

function addMarker(feature) {
  var marker = new google.maps.Marker({
    position: feature.position,
    icon: feature.icon,
    map: map
  });
}

function submitLocation(data) {
  socket.emit('location', data);
}
function success (position) {
  var data = {
    coordinates: [position.coords.latitude, position.coords.longitude]
  };
  var marker = Markers.create(data.coordinates);
  data.id = marker.id;
  submitLocation(data);
}

function error () {
  alert('BASE HAS BEEN FUCKED');
}

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(function(position) {
    var coords = position.coords;
    var location = new google.maps.LatLng(coords.latitude, coords.longitude);
    map.setCenter(location);
  }, error);

  var geoOptions = { timeout: 30 * 1000, enableHighAccuracy: false };
  navigator.geolocation.watchPosition(success, error, geoOptions);
} else {
  console.log('Permission denied');
}

initialize();
<|endoftext|>


<commit_before>/**
 * @requires package.js
 *
 */

/**
 * @class
 * Rectangle frame, create a frame to layer edition with handlers
 *
 * @extends L.Layer
 *
 * @param {L.Path} path
 * @param {Object} [options]
 * @param {String} options.pane Where in leaflet pane
 */
L.larva.frame.Rect = L.Layer.extend(
/** @lends L.larva.frame.Rect.prototype */
{

	statics: {
		TOP_LEFT: 'tl',
		TOP_MIDDLE: 'tm',
		TOP_RIGHT: 'tr',
		MIDDLE_LEFT: 'ml',
		MIDDLE_MIDDLE: 'mm',
		MIDDLE_RIGHT: 'mr',
		BOTTOM_LEFT: 'bl',
		BOTTOM_MIDDLE: 'bm',
		BOTTOM_RIGHT: 'br'
	},

	options: {
		pane: 'llarva-frame'
	},

	initialize: function (path) {
		this._path = path;
	},

	beforeAdd: function (map) {
		if (!map.getPane(this.options.pane)) {
			map.createPane(this.options.pane);
		}
	},
	/**
	 * Returns Computed CSS Style of an handler
	 * @param  {String} id
	 * @return {CSSStyleDeclaration}
	 */
	getComputedStyle: function(id) {
		if (id) {
			if (this._handles[id]) {
				return getComputedStyle(this._handles[id]);
			}
		} else {
			return getComputedStyle(this._el);
		}
	},

	getEvents: function () {
		return {
			zoom: this._onMapZoom
		};
	},
	/**
	 * @return {DOMRect}
	 */
	getFrameClientRect: function () {
		return this._el.getBoundingClientRect();
	},
	/**
	 * @param  {String} id
	 * @return {HTMLElement}
	 */
	getHandle: function (id) {
		return this._handles[id];
	},
	/**
	 * @param  {String} id
	 * @return {L.Point}
	 */
	getPosition: function(id) {
		if (id) {
			return L.DomUtil.getPosition(this._handles[id]);
		} else {
			return L.DomUtil.getPosition(this._el);
		}
	},
	/**
	 */
	hideHandle: function() {
		for (var i = 0; i < arguments.length; i++) {
			if (this._handles[arguments[i]]) {
				this._handles[arguments[i]].style.display = 'none';
			}
		}
	},

	onAdd: function () {
		var el = this._el = L.DomUtil.create('div', 'llarva-pathframe', this.getPane());
		L.DomEvent.on(el, L.Draggable.START.join(' '), this._onStart, this);

		this._handles = {};

		['tl','tm','tr','ml','mm','mr','bl','bm','br'].forEach(function (id) {

			this._handles[id] = L.DomUtil.create('div', 'llarva-' + id, el);
			this._handles[id]._id = id;
			L.DomEvent.on(this._handles[id], L.Draggable.START.join(' '), this._onStart, this);

		}, this);

		this._draggables = {};
		this._updateFrame(false);
		this._updateHandles();
	},

	onRemove: function() {
		var id, eventTypes = L.Draggable.START.join(' ');

		for (id in this._draggables) {
			this._draggables[id].disable();
		}

		// L.DomEvent.off(this._el, 'mousedown click', L.DomEvent.stop);
		L.DomEvent.off(this._el, eventTypes, this._onStart, this);

		for (id in this._handles) {
			L.DomEvent.off(this._handles[id], eventTypes, this._onStart, this);
		}

		L.DomUtil.remove(this._el);
		L.DomUtil.empty(this._el);

		delete this._el;
	},
	/**
	 * @param {Object} styles
	 * @param {HTMLElement} element
	 */
	setElementStyle: function (styles, element) {
		if (!element) {
			L.extend(this._el.style, styles);
		} else {
			element = this._handles[element];

			if (element) {
				L.extend(element.style, styles);
			}
		}
	},
	/**
	 * @param {L.larva.frame.RECT_STYLE} style
	 */
	setStyle: function (style) {
		var id, el, oldStyle = this._style;

		for (id in this._handles) {
			el = this._handles[id];
			el.style.display = 'block';

			if (this._draggables[id]) {
				this._draggables[id].disable();
				delete this._draggables[id];
			}

			if (style[id]) {
				if (style[id].hide) {
					el.style.display = 'none';
				}

				if (style[id].draggable) {
					this._draggables[id] = new L.Draggable(el);
					this._draggables[id].enable();
					L.DomEvent.off(el, 'mousedown click', L.DomEvent.stop);
				}
			}
		}

		if (oldStyle) {
			L.DomUtil.removeClass(this._el, oldStyle.className);
		}

		L.DomUtil.addClass(this._el, style.className);

		this._style = style;

		this._updateHandles();

		for (id in this._draggables) {
			this._updateDraggable(id);
		}
	},
	/**
	 * @param {L.LatLngBounds} [bounds]
	 * @param {...String} [maintainHandles]
	 */
	updateBounds: function (bounds) {
		this._updateFrame(false, Array.prototype.slice.call(arguments, 1), bounds);
	},

	_onEnd: function (evt) {
		L.DomEvent.stop(evt);

		for (var id in L.Draggable.MOVE) {
			L.DomEvent
				.off(document, L.Draggable.MOVE[id], this._onMove, this)
				.off(document, L.Draggable.END[id], this._onEnd, this);
		}

		L.DomUtil.removeClass(document.body, 'leaflet-dragging');

		this.fire('drag:end', {
			sourceEvent: evt
		});
	},

	_onMapZoom: function () {
		this._updateFrame(true);
	},

	_onMove: function (evt) {
		L.DomEvent.stop(evt);

		this.fire('drag:move', {
			sourceEvent: evt
		});
	},

	_onStart: function (evt) {
		L.DomEvent.stop(evt);

		this.fire('drag:start', {
			sourceEvent: evt,
			handle: evt.target._id
		});

		L.DomEvent
			.on(document, L.Draggable.MOVE[evt.type], this._onMove, this)
			.on(document, L.Draggable.END[evt.type], this._onEnd, this);

		L.DomUtil.addClass(document.body, 'leaflet-dragging');
	},

	_setHandlePosition: function (handle, bWidth) {
		var id = handle._id, style = {};

		switch (id[0]) {
			case 't':
				style.top = (L.larva.getHeight(handle) / -2 - bWidth.top) + 'px';
				break;

			case 'm':
				style.top = '50%';
				style.marginTop = (L.larva.getHeight(handle) / -2) + 'px';
				break;

			case 'b':
				style.bottom = (L.larva.getHeight(handle) / -2 - bWidth.bottom) + 'px';
				break;
		}

		switch (id[1]) {
			case 'l':
				style.left = (L.larva.getWidth(handle) / -2 - bWidth.left) + 'px';
				break;

			case 'm':
				style.marginLeft = (L.larva.getWidth(handle) / -2) + 'px';
				style.left = '50%';
				break;

			case 'r':
				style.right = (L.larva.getWidth(handle) / -2 - bWidth.right) + 'px';
				break;
		}

		L.extend(handle.style, style);
	},

	_updateDraggable: function (id) {
		var el = this._handles[id];
		var left = el.offsetLeft,
		top = el.offsetTop;

		if (el.style.marginLeft) {
			left -= parseInt(el.style.marginLeft);
		}

		if (el.style.marginTop) {
			top -= parseInt(el.style.marginTop);
		}

		L.extend(el.style, {
			left: '0px', top: '0px'
		});

		L.DomUtil.setPosition(el, L.point(left, top));
	},

	_updateFrame: function (zoomChanged, maintainHandles, userBounds) {
		var id,
		    currentPosition = L.DomUtil.getPosition(this._el),
		    handle,
		    handlePosition;

		var bounds = userBounds || this._path.getBounds();

		var southEastPoint = this._map.latLngToLayerPoint(bounds.getSouthEast()),
		northWestPoint = this._map.latLngToLayerPoint(bounds.getNorthWest());

		var computedStyle = getComputedStyle(this._el);

		if (maintainHandles && currentPosition && maintainHandles.length) {
			for (var i=0; i<maintainHandles.length; i++) {
				handle = this._handles[maintainHandles[i]];
				if (handle && (handlePosition = L.DomUtil.getPosition(handle))) {
					handlePosition = handlePosition.add(currentPosition);
					L.DomUtil.setPosition(handle, handlePosition.subtract(northWestPoint));
				}
			}
		}

		L.DomUtil.setPosition(this._el, northWestPoint);

		var x = parseInt(computedStyle.borderLeftWidth) + parseInt(computedStyle.borderRightWidth),
		y = parseInt(computedStyle.borderTopWidth) + parseInt(computedStyle.borderBottomWidth);

		var oldWidth, oldHeight;
		if (zoomChanged) {
			oldWidth = L.larva.getWidth(this._el);
			oldHeight = L.larva.getHeight(this._el);
		}

		this._el.style.width = (southEastPoint.x - northWestPoint.x - x) + 'px';
		this._el.style.height = (southEastPoint.y - northWestPoint.y - y) + 'px';

		if (zoomChanged) {

			for (id in this._handles) {
				handle = this._handles[id];
				handlePosition = L.DomUtil.getPosition(handle);

				if (handlePosition) {
					L.DomUtil.setPosition(handle, handlePosition.scaleBy(L.point(
						L.larva.getWidth(this._el) / oldWidth,
						L.larva.getHeight(this._el) / oldHeight
					)));
				}
			}
		}

		this.southEastPoint = southEastPoint;
		this.northWestPoint = northWestPoint;
	},

	_updateHandles: function () {
		var id, computedStyle;

		computedStyle = getComputedStyle(this._el);

		var borderWidth = {
			bottom: 'borderBottomWidth',
			left: 'borderLeftWidth',
			right: 'borderRightWidth',
			top: 'borderTopWidth'
		};

		for (id in borderWidth) {
			borderWidth[id] = parseInt(computedStyle[borderWidth[id]]) / 2;
		}

		for (id in this._handles) {
			this._setHandlePosition(this._handles[id], borderWidth);
		}
	}
});

L.larva.frame.rect = function (path) {
	if (path && path._rectFrame) {
		return path._rectFrame;
	}

	return (path._rectFrame = new L.larva.frame.Rect(path));
};<commit_msg>Rename Rect variables<commit_after>/**
 * @requires package.js
 *
 */

/**
 * @class
 * Rectangle frame, create a frame to layer edition with handlers
 *
 * @extends L.Layer
 *
 * @param {L.Path} path
 * @param {Object} [options]
 * @param {String} options.pane Where in leaflet pane
 */
L.larva.frame.Rect = L.Layer.extend(
/** @lends L.larva.frame.Rect.prototype */
{

	statics: {
		TOP_LEFT: 'tl',
		TOP_MIDDLE: 'tm',
		TOP_RIGHT: 'tr',
		MIDDLE_LEFT: 'ml',
		MIDDLE_MIDDLE: 'mm',
		MIDDLE_RIGHT: 'mr',
		BOTTOM_LEFT: 'bl',
		BOTTOM_MIDDLE: 'bm',
		BOTTOM_RIGHT: 'br'
	},

	options: {
		pane: 'llarva-frame'
	},

	initialize: function (path) {
		this._path = path;
	},

	beforeAdd: function (map) {
		if (!map.getPane(this.options.pane)) {
			map.createPane(this.options.pane);
		}
	},
	/**
	 * Returns Computed CSS Style of an handler
	 * @param  {String} id
	 * @return {CSSStyleDeclaration}
	 */
	getComputedStyle: function(id) {
		if (id) {
			if (this._handles[id]) {
				return getComputedStyle(this._handles[id]);
			}
		} else {
			return getComputedStyle(this._el);
		}
	},

	getEvents: function () {
		return {
			zoom: this._onMapZoom
		};
	},
	/**
	 * @return {DOMRect}
	 */
	getFrameClientRect: function () {
		return this._el.getBoundingClientRect();
	},
	/**
	 * @param  {String} id
	 * @return {HTMLElement}
	 */
	getHandle: function (id) {
		return this._handles[id];
	},
	/**
	 * @param  {String} id
	 * @return {L.Point}
	 */
	getPosition: function(id) {
		if (id) {
			return L.DomUtil.getPosition(this._handles[id]);
		} else {
			return L.DomUtil.getPosition(this._el);
		}
	},
	/**
	 */
	hideHandle: function() {
		for (var i = 0; i < arguments.length; i++) {
			if (this._handles[arguments[i]]) {
				this._handles[arguments[i]].style.display = 'none';
			}
		}
	},

	onAdd: function () {
		var el = this._el = L.DomUtil.create('div', 'llarva-pathframe', this.getPane());
		L.DomEvent.on(el, L.Draggable.START.join(' '), this._onStart, this);

		this._handles = {};

		['tl','tm','tr','ml','mm','mr','bl','bm','br'].forEach(function (id) {

			this._handles[id] = L.DomUtil.create('div', 'llarva-' + id, el);
			this._handles[id]._id = id;
			L.DomEvent.on(this._handles[id], L.Draggable.START.join(' '), this._onStart, this);

		}, this);

		this._draggables = {};
		this._updateFrame(false);
		this._updateHandles();
	},

	onRemove: function() {
		var id, eventTypes = L.Draggable.START.join(' ');

		for (id in this._draggables) {
			this._draggables[id].disable();
		}

		// L.DomEvent.off(this._el, 'mousedown click', L.DomEvent.stop);
		L.DomEvent.off(this._el, eventTypes, this._onStart, this);

		for (id in this._handles) {
			L.DomEvent.off(this._handles[id], eventTypes, this._onStart, this);
		}

		L.DomUtil.remove(this._el);
		L.DomUtil.empty(this._el);

		delete this._el;
	},
	/**
	 * @param {Object} styles
	 * @param {HTMLElement} element
	 */
	setElementStyle: function (styles, element) {
		if (!element) {
			L.extend(this._el.style, styles);
		} else {
			element = this._handles[element];

			if (element) {
				L.extend(element.style, styles);
			}
		}
	},
	/**
	 * @param {L.larva.frame.RECT_STYLE} style
	 */
	setStyle: function (style) {
		var id, el, oldStyle = this._style;

		for (id in this._handles) {
			el = this._handles[id];
			el.style.display = 'block';

			if (this._draggables[id]) {
				this._draggables[id].disable();
				delete this._draggables[id];
			}

			if (style[id]) {
				if (style[id].hide) {
					el.style.display = 'none';
				}

				if (style[id].draggable) {
					this._draggables[id] = new L.Draggable(el);
					this._draggables[id].enable();
					L.DomEvent.off(el, 'mousedown click', L.DomEvent.stop);
				}
			}
		}

		if (oldStyle) {
			L.DomUtil.removeClass(this._el, oldStyle.className);
		}

		L.DomUtil.addClass(this._el, style.className);

		this._style = style;

		this._updateHandles();

		for (id in this._draggables) {
			this._updateDraggable(id);
		}
	},
	/**
	 * @param {L.LatLngBounds} [bounds]
	 * @param {...String} [maintainHandles]
	 */
	updateBounds: function (bounds) {
		this._updateFrame(false, Array.prototype.slice.call(arguments, 1), bounds);
	},

	_onEnd: function (evt) {
		L.DomEvent.stop(evt);

		for (var id in L.Draggable.MOVE) {
			L.DomEvent
				.off(document, L.Draggable.MOVE[id], this._onMove, this)
				.off(document, L.Draggable.END[id], this._onEnd, this);
		}

		L.DomUtil.removeClass(document.body, 'leaflet-dragging');

		this.fire('drag:end', {
			sourceEvent: evt
		});
	},

	_onMapZoom: function () {
		this._updateFrame(true);
	},

	_onMove: function (evt) {
		L.DomEvent.stop(evt);

		this.fire('drag:move', {
			sourceEvent: evt
		});
	},

	_onStart: function (evt) {
		L.DomEvent.stop(evt);

		this.fire('drag:start', {
			sourceEvent: evt,
			handle: evt.target._id
		});

		L.DomEvent
			.on(document, L.Draggable.MOVE[evt.type], this._onMove, this)
			.on(document, L.Draggable.END[evt.type], this._onEnd, this);

		L.DomUtil.addClass(document.body, 'leaflet-dragging');
	},

	_setHandlePosition: function (handle, borders) {
		var id = handle._id, style = {};

		switch (id[0]) {
			case 't':
				style.top = (L.larva.getHeight(handle) / -2 - borders.top) + 'px';
				break;

			case 'm':
				style.top = '50%';
				style.marginTop = (L.larva.getHeight(handle) / -2) + 'px';
				break;

			case 'b':
				style.bottom = (L.larva.getHeight(handle) / -2 - borders.bottom) + 'px';
				break;
		}

		switch (id[1]) {
			case 'l':
				style.left = (L.larva.getWidth(handle) / -2 - borders.left) + 'px';
				break;

			case 'm':
				style.marginLeft = (L.larva.getWidth(handle) / -2) + 'px';
				style.left = '50%';
				break;

			case 'r':
				style.right = (L.larva.getWidth(handle) / -2 - borders.right) + 'px';
				break;
		}

		L.extend(handle.style, style);
	},

	_updateDraggable: function (id) {
		var el = this._handles[id];
		var left = el.offsetLeft,
		top = el.offsetTop;

		if (el.style.marginLeft) {
			left -= parseInt(el.style.marginLeft);
		}

		if (el.style.marginTop) {
			top -= parseInt(el.style.marginTop);
		}

		L.extend(el.style, {
			left: '0px', top: '0px'
		});

		L.DomUtil.setPosition(el, L.point(left, top));
	},

	_updateFrame: function (zoomChanged, maintainHandles, userBounds) {
		var id,
		    currentPosition = L.DomUtil.getPosition(this._el),
		    handle,
		    handlePosition;

		var bounds = userBounds || this._path.getBounds();

		var southEastPoint = this._map.latLngToLayerPoint(bounds.getSouthEast()),
		northWestPoint = this._map.latLngToLayerPoint(bounds.getNorthWest());

		var computedStyle = getComputedStyle(this._el);

		if (maintainHandles && currentPosition && maintainHandles.length) {
			for (var i=0; i<maintainHandles.length; i++) {
				handle = this._handles[maintainHandles[i]];
				if (handle && (handlePosition = L.DomUtil.getPosition(handle))) {
					handlePosition = handlePosition.add(currentPosition);
					L.DomUtil.setPosition(handle, handlePosition.subtract(northWestPoint));
				}
			}
		}

		L.DomUtil.setPosition(this._el, northWestPoint);

		var x = parseInt(computedStyle.borderLeftWidth) + parseInt(computedStyle.borderRightWidth),
		y = parseInt(computedStyle.borderTopWidth) + parseInt(computedStyle.borderBottomWidth);

		var oldWidth, oldHeight;
		if (zoomChanged) {
			oldWidth = L.larva.getWidth(this._el);
			oldHeight = L.larva.getHeight(this._el);
		}

		this._el.style.width = (southEastPoint.x - northWestPoint.x - x) + 'px';
		this._el.style.height = (southEastPoint.y - northWestPoint.y - y) + 'px';

		if (zoomChanged) {

			for (id in this._handles) {
				handle = this._handles[id];
				handlePosition = L.DomUtil.getPosition(handle);

				if (handlePosition) {
					L.DomUtil.setPosition(handle, handlePosition.scaleBy(L.point(
						L.larva.getWidth(this._el) / oldWidth,
						L.larva.getHeight(this._el) / oldHeight
					)));
				}
			}
		}

		this.southEastPoint = southEastPoint;
		this.northWestPoint = northWestPoint;
	},

	_updateHandles: function () {
		var id, computedStyle;

		computedStyle = getComputedStyle(this._el);

		var borders = {
			bottom: 'borderBottomWidth',
			left: 'borderLeftWidth',
			right: 'borderRightWidth',
			top: 'borderTopWidth'
		};

		for (id in borders) {
			borders[id] = parseInt(computedStyle[borders[id]]) / 2;
		}

		for (id in this._handles) {
			this._setHandlePosition(this._handles[id], borders);
		}
	}
});

L.larva.frame.rect = function (path) {
	if (path && path._rectFrame) {
		return path._rectFrame;
	}

	return (path._rectFrame = new L.larva.frame.Rect(path));
};<|endoftext|>


<commit_before>var $searchInput;
var $categoryViewer;

var shortcutBarView = Backbone.View.extend({
  initialize: function() {
    this.render();
  },
  render: function() {
    var shortcutBarTemplate = $('#shortcutBarTemplate').html();
    var template = Handlebars.compile(shortcutBarTemplate);
    var context = {};
    var html = template(context);
    this.$el.html(html);
  }
});

var categoryView = Backbone.View.extend({
  initialize: function() {
    this.render();
    $categoryViewer = $('.category-viewer');
    $categoryViewer.hide();
  },
  render: function() {
    var categoryViewTemplate = $('#categoryViewTemplate').html();
    var template = Handlebars.compile(categoryViewTemplate);
    var context = {};
    var html = template(context);
    this.$el.html(html);
  },
});

$(document).ready(function() {

  $searchInput = $("input.search");
  $searchInput.focus(); //do first!

  var category_viewer_template = new categoryView({el: $('.category-viewer-placeholder') });
  var shortcut_bar_template = new shortcutBarView({el: $('.shortcut-bar-wrapper') });

  $("input.search").on('blur', function() {
    $categoryViewer.fadeIn('fast');
  });

});
<commit_msg>add animations and organize code<commit_after>var Gateway = {

  init: function() {
    Gateway.renderViews();
    Gateway.getElements();
    Gateway.$categoryPlaceholder.css({ height: '0' });

    Gateway.search.$input.on('blur', function() {
      Gateway.showCategories();
    });

  },

  getElements: function() {
    Gateway.$container = $('div.gateway')
    Gateway.$categoryPlaceholder = $('.category-viewer-placeholder');

    Gateway.search.getElements();
  },

  renderViews: function() {
    Gateway.category_view = new categoryView({el: $('.category-viewer-placeholder') });
    Gateway.shortcut_bar_view = new shortcutBarView({el: $('.shortcut-bar-wrapper') });
  },

  showCategories: function() {
    Gateway.$categoryPlaceholder.animate({
      height: '50vh'
    }, 400, function() {
      Gateway.category_view.$categoryViewer.fadeIn('fast');
    });
  },

  search: {

    getElements: function(){
      this.$outer = $('div.search');
      this.$input = $('input.search');
      this.$left = $('div#search-left');
    },

    send: function() {
      //send search to DuckDuckGo on 'return' keydown
    }

  }

}

var $shortcutBar;
//var $categoryViewer;

var shortcutBarView = Backbone.View.extend({
  initialize: function() {
    this.render();
    $shortcutBar = $('.shortcut-bar');
    $shortcutBar
      .hide()
      .delay(400)
      .fadeIn(600);
  },
  render: function() {
    var shortcutBarTemplate = $('#shortcutBarTemplate').html();
    var template = Handlebars.compile(shortcutBarTemplate);
    var context = {};
    var html = template(context);
    this.$el.html(html);
  }
});

var categoryView = Backbone.View.extend({
  initialize: function() {
    this.render();
    this.$categoryViewer = $('.category-viewer');
    this.$categoryViewer.hide();
  },
  render: function() {
    var categoryViewTemplate = $('#categoryViewTemplate').html();
    var template = Handlebars.compile(categoryViewTemplate);
    var context = {};
    var html = template(context);
    this.$el.html(html);
  },
});

$(document).ready(function() {

  $('input.search').focus(); //do first!

  Gateway.init();

  //$("input.search").on('blur', function() {
    //$categoryViewer.fadeIn('fast');
  //});

});
<|endoftext|>


<commit_before>$(document).ready(function () {
    //load appropriate map and also prepopulate from and to fields
    var param = _getParameters();
    switch (param.type) {
        case "search":
            $.ajax({
                url: "/navigate/searchmap",
                data: {
                    search: param.search
                },
                success: function (data) {
                    console.log(param.search);
                    $("#map-wrapper").html(data);
                    return $("#map-directions-end").val(param.search);
                }
            });
            break;
        case "directions":
            $.ajax({
                url: "/navigate/navmap",
                data: {
                    from: param.from,
                    to: param.to
                },
                success: function (data) {
                    $("#map-directions-start").val(param.from);
                    $("#map-directions-end").val(param.to);
                    return $("#map-wrapper").html(data);
                }
            });
    }

    //preload some feed items
    $.getJSON('/report/getall', function (data) {
        $.each(data, function (key, val) {
            var time = _processDate(new Date(val.time));
            var type = val.type;
            var comment = val.comment;
            createFeedItem(time,type,comment);
        });
    });

/**
 * retrieve the get parameters and their values in a querystring
 * @returns urlParams   url parameters in object format
 * @private
 */
function _getParameters() {
    var decode, match, pl, query, search, urlParams;
    pl = /\+/g;
    search = /([^&=]+)=?([^&]*)/g;
    decode = function (s) {
        return decodeURIComponent(s.replace(pl, " "));
    };
    query = window.location.search.substring(1);
    urlParams = {};
    while ((match = search.exec(query))) {
        urlParams[decode(match[1])] = decode(match[2]);
    }
    return urlParams;
};

/**
 * process a js Date object
 * @param date
 * @private
 */
function _processDate(date) {
    var longdate = date.toDateString();
    var time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return longdate + " @ " + time;
}

var isWindowSize = ($(window).width() >= 768);

    //connect to socket.io
    try {
    var socket = io.connect('/');
    socket.on('livereport', function (data) {
        console.log(data);
        data=data.report; //@todo for some reason there is a nested report
        $("#live-feed").prepend('

'+data.time + data.type + data.comment+'
')
    });
    } catch(err) {

    }

    /**
     * dragging mobile sidebar
     */
    $('#feed-btn,#dir-btn').mousedown(function(e){
        if($(window).width() < 768) {
            $(document).mousemove(function(e){

                if (e.which!=0 &&
                    $("#map-content").hasClass("normal") &&
                    e.pageY < $(window).height() &&
                    e.pageY > 0 &&
                    e.pageX < $(window).width() &&
                    e.pageX > 0
                    ) {
                    $("#map-content").height(e.pageY);
                }
                else {
                    $("#map-content").removeClass("normal");

                    changeMobileSidebar(true);
                    $(document).unbind("mousemove");
                    return;
                }

           });
        }
    });

    /**
     * switch to the feed tab on click
     */
    $("#feed-btn").click(function() {
        $("#directions").fadeOut();
        $("#feed").fadeIn();

        $("#sidebar .btn").removeClass("on");
        $(this).addClass("on");
        changeMobileSidebar($("#map-content").hasClass("normal"));
    });

    /**
     * switch to the feed button on click
     */
    $("#feed-btn").click(function() {
        $("#directions").fadeOut();
        $("#feed").fadeIn();

        $("#sidebar .btn").removeClass("on");
        $(this).addClass("on");
        changeMobileSidebar($("#map-content").hasClass("normal"));
    });

    /**
     *
     */
    $("#dir-btn").click(function() {
        $("#feed").fadeOut();
        $("#directions").fadeIn();

        $("#sidebar .btn").removeClass("on");
        $(this).addClass("on");
        changeMobileSidebar($("#map-content").hasClass("normal"));
    });

    /**
     * toggle the open/closed state of the sidebar
     */
    $("#shrink-arrow").click(function() {
        /*$(this).innerHTML='';*/
        var type=$(this).data('type');
        if(type=='close') {
           _closeWindowSidebar();
        } else if (type=='open') {
            _openWindowSidebar();
        }
    });

    /**
     * show the feed tab in the sidebar on click
     */
    $("#feed-btn").click(function() {
        $("#directions").hide();
        $("#feed").fadeIn();
    });

    /**
     * change scrollbar location on window resize
     * switch to the mobile scrollbar formatting if necessary
     */
    $(window).resize(function() {

        if ($(window).width() < 768 && isWindowSize) {
            isWindowSize = false;
            var barType = $("#shrink-arrow").data('type');
            if (barType=="close"){
                _openMobileSidebar(0);
                $("#map-content,.navbar").click(function() {
                    _closeMobileSidebar();
                });
            }
            else {
                _closeMobileSidebar();
            }
        } else if ($(window).width() >= 768 && !isWindowSize) {
            isWindowSize = true;
            var mobileBarClosed = $("#map-content").hasClass("normal");
            if (mobileBarClosed) {
                _closeWindowSidebar();
                _closeMobileSidebar();
            }

            else {
                _openWindowSidebar();
                $("#map-content").css({'height':'', "background-color": "transparent"}).removeClass("collapsed").addClass("normal");
                $(".navbar").css("background-color", "");
            }
        }
        setTimeout(function(){
            google.maps.event.trigger(map, 'resize');
        },500);

    });

});

/**
 * switch to the mobile sidebar
 * @param bool normal       whether in normal state
 */
function changeMobileSidebar(normal) {
    if(normal && $(window).width() < 768) {
        _openMobileSidebar(500);
        //click anywhere to exit list
        // TODO: assign in initialization, have check state
        $("#map-content,.navbar").click(function() {
            _closeMobileSidebar();
        });
    }
}

/**
 * close the mobile sidebar
 */
function _closeMobileSidebar() {
    time=500;
    $("#sidebar .btn").removeClass("on");
    $("#map-content").css({"background-color": "transparent"}).removeClass("collapsed").addClass("normal");
    //$("#map-content").css({'height':'', "background-color": "transparent"}).removeClass("collapsed").addClass("normal");
    $("#map-content").animate({
        height: '100%',
    }, time, function(){});
    $(".navbar").css("background-color", "");
    setTimeout(function(){
        google.maps.event.trigger(map, 'resize');
    },500);
}

/**
 * open the mobile sidebar
 * @param int t     animation time of height change
 */
function _openMobileSidebar(t) {
    $("#map-content").css({'min-height':'60px', "background-color": "rgba(0,0,0,0.4)"}).removeClass("normal").addClass("collapsed");
    $("#map-content").animate({
        height: '20%',
    }, t, function(){});
    $(".navbar").css("background-color", "#223044");
}

/**
 * close the main desktop sidebar
 */
function _closeWindowSidebar() {
    $("#shrink-arrow").data('type', 'open').html('');
    $("#map-content").css('width','100%');
    setTimeout(function(){
        google.maps.event.trigger(map, 'resize');
    },500);
}

/**
 * open the main desktop sidebar
 */
function _openWindowSidebar() {
    $("#shrink-arrow").data('type', 'close').html('');
    $("#map-content").css('width','');
}

/**
 * get directions by request
 * @param start     start location
 * @param end       end location
 */

function getDirections(start, end) {
    $.getJSON('/navigate/nav?start=344234568&end=2345009892', function(data) {
        var coors = [];
        for (var i=0; i<data.path.length; i++) {
            coors.push(new google.maps.LatLng(data.path[i].lat, data.path[i].lon));
        }
        var path = new google.maps.Polyline({
            path: coors,
            strokeColor: "#FF0000",
            strokeOpacity: 1.0,
            strokeWeight: 2
        });
        path.setMap(map);
    });
}

/**
 * set a timeout on direction retrieval
 */
$(function(){
    setTimeout(function(){
        getDirections();
    },2000);
});
<commit_msg>[fix] missing createFeedItem function [fix] merge error in dynamic updates [fix] made createFeedItem private<commit_after>$(document).ready(function () {
    //load appropriate map and also prepopulate from and to fields
    var param = _getParameters();
    switch (param.type) {
        case "search":
            $.ajax({
                url: "/navigate/searchmap",
                data: {
                    search: param.search
                },
                success: function (data) {
                    console.log(param.search);
                    $("#map-wrapper").html(data);
                    return $("#map-directions-end").val(param.search);
                }
            });
            break;
        case "directions":
            $.ajax({
                url: "/navigate/navmap",
                data: {
                    from: param.from,
                    to: param.to
                },
                success: function (data) {
                    $("#map-directions-start").val(param.from);
                    $("#map-directions-end").val(param.to);
                    return $("#map-wrapper").html(data);
                }
            });
    }

    //preload some feed items
    $.getJSON('/report/getall', function (data) {
        $.each(data, function (key, val) {
            var time = _processDate(new Date(val.time));
            var type = val.type;
            var comment = val.comment;
            _createFeedItem(time,type,comment);
        });
    });

/**
 * retrieve the get parameters and their values in a querystring
 * @returns urlParams   url parameters in object format
 * @private
 */
function _getParameters() {
    var decode, match, pl, query, search, urlParams;
    pl = /\+/g;
    search = /([^&=]+)=?([^&]*)/g;
    decode = function (s) {
        return decodeURIComponent(s.replace(pl, " "));
    };
    query = window.location.search.substring(1);
    urlParams = {};
    while ((match = search.exec(query))) {
        urlParams[decode(match[1])] = decode(match[2]);
    }
    return urlParams;
};

/**
 * process a js Date object
 * @param date
 * @private
 */
function _processDate(date) {
    var longdate = date.toDateString();
    var time = date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return longdate + " @ " + time;
}

var isWindowSize = ($(window).width() >= 768);

    //connect to socket.io
    try {
    var socket = io.connect('/');
    socket.on('livereport', function (data) {
        console.log(data);
        data=data.report; //@todo for some reason there is a nested report
        _createFeedItem(_processDate(data.time),data.type,data.comment);
    });
    } catch(err) {

    }

    /**
     * dragging mobile sidebar
     */
    $('#feed-btn,#dir-btn').mousedown(function(e){
        if($(window).width() < 768) {
            $(document).mousemove(function(e){

                if (e.which!=0 &&
                    $("#map-content").hasClass("normal") &&
                    e.pageY < $(window).height() &&
                    e.pageY > 0 &&
                    e.pageX < $(window).width() &&
                    e.pageX > 0
                    ) {
                    $("#map-content").height(e.pageY);
                }
                else {
                    $("#map-content").removeClass("normal");

                    changeMobileSidebar(true);
                    $(document).unbind("mousemove");
                    return;
                }

           });
        }
    });

    /**
     * switch to the feed tab on click
     */
    $("#feed-btn").click(function() {
        $("#directions").fadeOut();
        $("#feed").fadeIn();

        $("#sidebar .btn").removeClass("on");
        $(this).addClass("on");
        changeMobileSidebar($("#map-content").hasClass("normal"));
    });

    /**
     * switch to the feed button on click
     */
    $("#feed-btn").click(function() {
        $("#directions").fadeOut();
        $("#feed").fadeIn();

        $("#sidebar .btn").removeClass("on");
        $(this).addClass("on");
        changeMobileSidebar($("#map-content").hasClass("normal"));
    });

    /**
     *
     */
    $("#dir-btn").click(function() {
        $("#feed").fadeOut();
        $("#directions").fadeIn();

        $("#sidebar .btn").removeClass("on");
        $(this).addClass("on");
        changeMobileSidebar($("#map-content").hasClass("normal"));
    });

    /**
     * toggle the open/closed state of the sidebar
     */
    $("#shrink-arrow").click(function() {
        /*$(this).innerHTML='';*/
        var type=$(this).data('type');
        if(type=='close') {
           _closeWindowSidebar();
        } else if (type=='open') {
            _openWindowSidebar();
        }
    });

    /**
     * show the feed tab in the sidebar on click
     */
    $("#feed-btn").click(function() {
        $("#directions").hide();
        $("#feed").fadeIn();
    });

    /**
     * change scrollbar location on window resize
     * switch to the mobile scrollbar formatting if necessary
     */
    $(window).resize(function() {

        if ($(window).width() < 768 && isWindowSize) {
            isWindowSize = false;
            var barType = $("#shrink-arrow").data('type');
            if (barType=="close"){
                _openMobileSidebar(0);
                $("#map-content,.navbar").click(function() {
                    _closeMobileSidebar();
                });
            }
            else {
                _closeMobileSidebar();
            }
        } else if ($(window).width() >= 768 && !isWindowSize) {
            isWindowSize = true;
            var mobileBarClosed = $("#map-content").hasClass("normal");
            if (mobileBarClosed) {
                _closeWindowSidebar();
                _closeMobileSidebar();
            }

            else {
                _openWindowSidebar();
                $("#map-content").css({'height':'', "background-color": "transparent"}).removeClass("collapsed").addClass("normal");
                $(".navbar").css("background-color", "");
            }
        }
        setTimeout(function(){
            google.maps.event.trigger(map, 'resize');
        },500);

    });

});

/**
 * create new feed item
 * @param time
 * @param type
 * @param comment
 */
function _createFeedItem(time,type,comment) {
    var html=$('

' + '
' + type + '

' + comment + '

—' + time + '

');
    $("#live-feed").prepend(html);
    html.removeClass('feed-item-hidden',300);
}

/**
 * switch to the mobile sidebar
 * @param bool normal       whether in normal state
 */
function changeMobileSidebar(normal) {
    if(normal && $(window).width() < 768) {
        _openMobileSidebar(500);
        //click anywhere to exit list
        // TODO: assign in initialization, have check state
        $("#map-content,.navbar").click(function() {
            _closeMobileSidebar();
        });
    }
}

/**
 * close the mobile sidebar
 */
function _closeMobileSidebar() {
    time=500;
    $("#sidebar .btn").removeClass("on");
    $("#map-content").css({"background-color": "transparent"}).removeClass("collapsed").addClass("normal");
    //$("#map-content").css({'height':'', "background-color": "transparent"}).removeClass("collapsed").addClass("normal");
    $("#map-content").animate({
        height: '100%',
    }, time, function(){});
    $(".navbar").css("background-color", "");
    setTimeout(function(){
        google.maps.event.trigger(map, 'resize');
    },500);
}

/**
 * open the mobile sidebar
 * @param int t     animation time of height change
 */
function _openMobileSidebar(t) {
    $("#map-content").css({'min-height':'60px', "background-color": "rgba(0,0,0,0.4)"}).removeClass("normal").addClass("collapsed");
    $("#map-content").animate({
        height: '20%',
    }, t, function(){});
    $(".navbar").css("background-color", "#223044");
}

/**
 * close the main desktop sidebar
 */
function _closeWindowSidebar() {
    $("#shrink-arrow").data('type', 'open').html('');
    $("#map-content").css('width','100%');
    setTimeout(function(){
        google.maps.event.trigger(map, 'resize');
    },500);
}

/**
 * open the main desktop sidebar
 */
function _openWindowSidebar() {
    $("#shrink-arrow").data('type', 'close').html('');
    $("#map-content").css('width','');
}

/**
 * get directions by request
 * @param start     start location
 * @param end       end location
 */

function getDirections(start, end) {
    $.getJSON('/navigate/nav?start=344234568&end=2345009892', function(data) {
        var coors = [];
        for (var i=0; i<data.path.length; i++) {
            coors.push(new google.maps.LatLng(data.path[i].lat, data.path[i].lon));
        }
        var path = new google.maps.Polyline({
            path: coors,
            strokeColor: "#FF0000",
            strokeOpacity: 1.0,
            strokeWeight: 2
        });
        path.setMap(map);
    });
}

/**
 * set a timeout on direction retrieval
 */
$(function(){
    setTimeout(function(){
        getDirections();
    },2000);
});
<|endoftext|>


<commit_before>var player;

var playState = {

    create: function () {
      var monsterLeft = game.add.tileSprite(0, 0, 128, 600, 'monster-left');
      var monsterRight = game.add.tileSprite(513, 0, 128, 600, 'monster-right');
      var monsterPink64 = game.add.image(150, 250, 'mob-pink-64');
      var monsterBlue64 = game.add.image(435, 250, 'mob-blue-64');
      player = game.add.image(325, 280, 'player');

      player.anchor.setTo(0.5, 0.5);
      player.scale.setTo(1, 1);
      player.animations.add('run');
      player.animations.play('run', 10, true);
    },

    update: function (){

      if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
          player.x -= 4;
          player.angle += 1;
      } else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
          player.x += 4;
          player.angle += 1;
      }

      if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
          player.y -= 4;
          player.angle += 1;
      } else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
          player.y += 4;
          player.angle += 1;
      }
    },

    render: function () {
      game.debug.spriteInfo(player, 20, 32);
    }

};
<commit_msg>workingOnSpin<commit_after>var player;

var playState = {

    create: function () {
      var monsterLeft = game.add.tileSprite(0, 0, 128, 600, 'monster-left');
      var monsterRight = game.add.tileSprite(513, 0, 128, 600, 'monster-right');
      var monsterPink64 = game.add.image(150, 250, 'mob-pink-64');
      var monsterBlue64 = game.add.image(435, 250, 'mob-blue-64');
      player = game.add.image(325, 280, 'player');

      player.anchor.setTo(0.5, 0.5);
      player.scale.setTo(1, 1);
      player.animations.add('run');
      player.animations.play('run', 10, true);
    },

    update: function (){

      if (game.input.keyboard.isDown(Phaser.Keyboard.LEFT)) {
          player.x -= 4;
          player.rotation = 3;
      } else if (game.input.keyboard.isDown(Phaser.Keyboard.RIGHT)) {
          player.x += 4;
          player.rotation = -.5;
      }

      if (game.input.keyboard.isDown(Phaser.Keyboard.UP)) {
          player.y -= 4;
          player.rotation = -1.5;
      } else if (game.input.keyboard.isDown(Phaser.Keyboard.DOWN)) {
          player.y += 4;
          player.rotation = 1;
      }
    },

    render: function () {
      game.debug.spriteInfo(player, 20, 32);
    }

};
<|endoftext|>


<commit_before>/**
 * Content Script
 * @author: Karthik VJ
 */

"use strict";

// ---- polyfills ---
var console = console || {};
console.log = console.log || function() {};
console.logCopy = console.log.bind(console);

// --------------
if (ENABLE_CONSOLE == false)
{
    console.log = function() {};
}

class RpcService
{
    constructor()
    {
        this.sendMessageToBackground = chrome.extension.sendMessage || chrome.runtime.sendMessage || function(){};
        iziToast.settings({
            timeout: 2000,
            resetOnHover: false,
            pauseOnHover: false,
            messageLineHeight: 30
        });
    }

    playVideoOnXBMC(vId)
    {
        console.log("sending message to background");
        this.sendMessageToBackground({message: "playVideo", videoId: vId}, function(response) {});
    }

    queueVideoToXBMC(vId)
    {
        this.sendMessageToBackground({message: "queueVideo", videoId: vId}, function(response) {
            console.log("inject script >> video sent! " + response);
            if (response == ResultData.OK)
            {
                iziToast.success({
                    message: "Added to Queue!"
                });
            }
            else
            {
                iziToast.error({
                    message: "Error! Can't Add to Queue!"
                });
            }
        });
    }

    playListOnXBMC(listId, videoId)
    {
        this.sendMessageToBackground({message: "playList", listId: listId, videoId: videoId}, function(response) {
            console.log("list sent! " + response);
        });
    }

}

class DivGenerator
{
    constructor()
    {
        this.playListId = null;
        this.videoId = null;
        this.isSideBar = false;
    }

    setSideBar(flag)
    {
        this.isSideBar = flag;
        return this;
    }

    setPlayList(pId)
    {
        this.playListId = pId;
        return this;
    }

    setVideo(vId)
    {
        this.videoId = vId;
        return this;
    }

    build()
    {
        let domEl = document.createElement("div");
        domEl.className = "xbmc_control";

        if(this.isSideBar)
        {
            if(this.playListId)
            {
                let playListSpan = document.createElement("span");
                playListSpan.setAttribute("rel", this.playListId);
                playListSpan.setAttribute("class", "xbmc_playlist xbmc_link");
                playListSpan.setAttribute("title", "Play All - Kassi Share");
                playListSpan.setAttribute("onclick", "return false;");
                playListSpan.appendChild(document.createTextNode("Play All"));

                domEl.appendChild(playListSpan);
                domEl.appendChild(document.createTextNode(" | "));
            }

            if(this.videoId)
            {
                let playSpan = document.createElement("span");
                playSpan.setAttribute("rel", this.videoId);
                playSpan.setAttribute("style", "padding-left: 180px;");
                playSpan.setAttribute("class", "xbmc_playNow xbmc_link");
                playSpan.setAttribute("title", "Play Now - Kassi Share");
                playSpan.setAttribute("onclick", "return false;");
                playSpan.appendChild(document.createTextNode("Play Now"));

                let queueSpan = document.createElement("span");
                queueSpan.setAttribute("rel", this.videoId);
                queueSpan.setAttribute("class", "xbmc_queue xbmc_link");
                queueSpan.setAttribute("title", "Add to Queue - Kassi Share");
                queueSpan.setAttribute("onclick", "return false;");
                queueSpan.appendChild(document.createTextNode("[+] Add to Queue"));

                domEl.appendChild(playSpan);
                domEl.appendChild(document.createTextNode(" | "));
                domEl.appendChild(queueSpan);
            }
        }
        else
        {
            if(this.playListId)
            {
                let listAnchor = document.createElement("a");
                listAnchor.setAttribute("href", "#");
                listAnchor.setAttribute("rel", this.playListId);
                listAnchor.setAttribute("title", "Play All - Kassi Share");
                listAnchor.setAttribute("onclick", "return false;");
                listAnchor.className = "xbmc_playlist";
                let listText = document.createTextNode("Play All");
                listAnchor.appendChild(listText);

                domEl.appendChild(listAnchor);
                domEl.appendChild(document.createTextNode(" | "));
            }

            if(this.videoId)
            {
                let playAnchor = document.createElement("a");
                playAnchor.setAttribute("href", "#");
                playAnchor.setAttribute("rel", this.videoId);
                playAnchor.setAttribute("title", "Play Now - Kassi Share");
                playAnchor.setAttribute("onclick", "return false;");
                playAnchor.className = "xbmc_playNow";
                playAnchor.appendChild(document.createTextNode("Play Now"));

                let queueAnchor = document.createElement("a");
                queueAnchor.setAttribute("href", "#");
                queueAnchor.setAttribute("rel", this.videoId);
                queueAnchor.setAttribute("title", "Add to Queue - Kassi Share");
                queueAnchor.setAttribute("onclick", "return false;");
                queueAnchor.className = "xbmc_queue";
                queueAnchor.appendChild(document.createTextNode("[+] Add to Queue"));

                domEl.appendChild(playAnchor);
                domEl.appendChild(document.createTextNode(" | "));
                domEl.appendChild(queueAnchor);
            }
        }

        return domEl;
    }
}

class Utils
{
    static findPropertyFromString(str, key)
    {
        let property = key + "=";
        var index = str.indexOf('?');
        str = str.substring(index + 1);

        var list = str.split('&');

        for (var i = 0; i < list.length; i++)
        {
            if (list[i].search(property) == 0)
            {
                return list[i].replace(property, "");
            }
        }
        return null;
    }
}

class Main
{
    constructor()
    {
        this.timerId = -1;
        this.rpc = new RpcService();

        let contentDiv = document.getElementById("content");
        contentDiv.addEventListener("DOMNodeInserted", (event) => {
            this.injectLinksWithDelay();
        });

        if (window.location.pathname == "/watch")
        {
            this.addLinkToWatchPage();
        }

        this.injectLinks();
    }

    addListeners(el)
    {
        var thisObject = this;
        // click event listeners
        el.querySelectorAll(".xbmc_playlist").forEach(function(innerEl)
        {
            innerEl.addEventListener("click", (event) => {
                let listId = innerEl.getAttribute("rel");

                if (listId)
                {
                    var listData = listId.split(" ");
                    console.log("playlist, " + listData);
                    thisObject.rpc.playListOnXBMC(listData[0], listData[1]);
                    event.preventDefault();
                }
            });

        });

        el.querySelectorAll(".xbmc_playNow").forEach(function(innerEl)
        {
            innerEl.addEventListener("click", (event) => {
                let rel = innerEl.getAttribute("rel");
                console.log("play single video, " + rel);
                thisObject.rpc.playVideoOnXBMC(rel);
                event.preventDefault();
            });

        });

        el.querySelectorAll(".xbmc_queue").forEach(function(innerEl)
        {
            innerEl.addEventListener("click", (event) => {
                let rel = innerEl.getAttribute("rel");
                console.log("queue single video, " + rel);
                thisObject.rpc.queueVideoToXBMC(rel);
                event.preventDefault();
            });

        });
    }

    injectLinks()
    {
        let thisObject = this;
        console.log("injectLinks ", this);
        // (home / subscription on home page), search page, video manager, user page, user browse video, Popular on YouTube, Popular on youtube right side, video list (on video page), play list page
        let classes = ".feed-item-content, .yt-lockup2-content, .vm-video-info-container, .yt-tile-visible, .channels-content-item, .lohp-category-shelf-item, .lohp-large-shelf-container, .lohp-medium-shelf-content, .lohp-vertical-shelf-item-content, .video-list-item, .playlist-video-item, .yt-lockup-content, .recent-activity-snippet, .playlist-actions, .pl-video-title";
        let divList = document.querySelectorAll(classes) || [];
        divList.forEach(function(el)
        {

            let alreadyAdded = false;
            el.querySelectorAll(".xbmc_control").forEach(function(innerEl)
            {
                alreadyAdded = true;
                return false;
            });

            if (alreadyAdded)
            {
                console.log("Already added - injectLinks");
                return; // continue
            }

            // (home / subscription on home page), search page, video manager, (user page / user browse video / Popular on YouTube)
            let df = el.querySelectorAll(".feed-video-title, .yt-uix-tile-link, .vm-video-title-content, .yt-uix-sessionlink, a");
            let len = df.length;
            console.log(typeof df, df);

            for (let i = 0; i < len; i++)
            {
                let innerEl = df[i];

                let videoPathString = innerEl.getAttribute("href");
                let listId;
                let videoId;
                let isSideBar = false;

                if (videoPathString)
                {
                    console.log("videoPathString, " + videoPathString);

                    // just a single video
                    videoId = Utils.findPropertyFromString(videoPathString, "v");
                    if (!videoId)
                    {
                        videoId = Utils.findPropertyFromString(videoPathString, "video_id");
                    }

                    if (!videoId)
                    {
                        videoId = Utils.findPropertyFromString(videoPathString, "video_ids");
                        if(videoId)
                        {
                            videoId = decodeURIComponent(videoId);
                            var vIndexText = Utils.findPropertyFromString(videoPathString, "index");
                            var vIndex = vIndexText ? parseInt(vIndexText) : 0;
                            if (vIndex < videoId.length)
                            {
                                try {
                                    videoId = videoId.split(",")[vIndex];
                                }
                                catch(err) {
                                    videoId = null;
                                }
                            }
                        }

                    }

                    if (videoId)
                    {
                        console.log("videoId, " + videoId);
                        if (el.classList.contains("video-list-item") || el.classList.contains("playlist-video-item"))
                        {
                            isSideBar = true;
                        }
                    }

                    // find play list id
                    listId = Utils.findPropertyFromString(videoPathString, "list");

                    //////

                    if (listId && videoId)
                    {
                        listId = listId + " " + videoId;
                    }

                    if (listId || videoId)
                    {
                        var divGen = new DivGenerator();
                        var div = divGen
                            .setVideo(videoId)
                            .setPlayList(listId)
                            .setSideBar(isSideBar)
                            .build();

                        thisObject.addListeners(div);
                        el.insertBefore(div, el.firstChild);
                    }

                    listId = null;
                    videoId = null;
                }

            }
        });

    }

    injectLinksWithDelay()
    {
        clearTimeout(this.timerId);
        this.timerId = setTimeout(() => {

            this.injectLinks();
            if (window.location.pathname == "/watch")
            {
                console.log("video ID change.. inject watch link!");
                this.addLinkToWatchPage();
            }
        }, 1000)
    }

    addLinkToWatchPage()
    {
        console.log("addLinkToWatchPage, window.location, " + window.location);
        let thisObject = this;
        let alreadyAdded = false;
        let headLineDiv = document.getElementById("watch7-headline");

        headLineDiv.querySelectorAll(".xbmc_control").forEach(function(el)
        {
            alreadyAdded = true;
            return false;
        });

        if (alreadyAdded)
        {
            console.log("Already added - addLinkToWatchPage");
            return;
        }

        let loc = window.location.toString();
        var videoId = Utils.findPropertyFromString(loc, "v");
        let listId = Utils.findPropertyFromString(loc, "list");

        if (listId && videoId)
        {
            listId = listId + " " + videoId;
        }

        if (listId || videoId)
        {
            var divGen = new DivGenerator();
            var div = divGen
                .setVideo(videoId)
                .setPlayList(listId)
                .build();

            thisObject.addListeners(div);
            headLineDiv.insertBefore(div, headLineDiv.firstChild);
        }

    }

}

new Main();<commit_msg>null check<commit_after>/**
 * Content Script
 * @author: Karthik VJ
 */

"use strict";

// ---- polyfills ---
var console = console || {};
console.log = console.log || function() {};
console.logCopy = console.log.bind(console);

// --------------
if (ENABLE_CONSOLE == false)
{
    console.log = function() {};
}

class RpcService
{
    constructor()
    {
        this.sendMessageToBackground = chrome.extension.sendMessage || chrome.runtime.sendMessage || function(){};
        iziToast.settings({
            timeout: 2000,
            resetOnHover: false,
            pauseOnHover: false,
            messageLineHeight: 30
        });
    }

    playVideoOnXBMC(vId)
    {
        console.log("sending message to background");
        this.sendMessageToBackground({message: "playVideo", videoId: vId}, function(response) {});
    }

    queueVideoToXBMC(vId)
    {
        this.sendMessageToBackground({message: "queueVideo", videoId: vId}, function(response) {
            console.log("inject script >> video sent! " + response);
            if (response == ResultData.OK)
            {
                iziToast.success({
                    message: "Added to Queue!"
                });
            }
            else
            {
                iziToast.error({
                    message: "Error! Can't Add to Queue!"
                });
            }
        });
    }

    playListOnXBMC(listId, videoId)
    {
        this.sendMessageToBackground({message: "playList", listId: listId, videoId: videoId}, function(response) {
            console.log("list sent! " + response);
        });
    }

}

class DivGenerator
{
    constructor()
    {
        this.playListId = null;
        this.videoId = null;
        this.isSideBar = false;
    }

    setSideBar(flag)
    {
        this.isSideBar = flag;
        return this;
    }

    setPlayList(pId)
    {
        this.playListId = pId;
        return this;
    }

    setVideo(vId)
    {
        this.videoId = vId;
        return this;
    }

    build()
    {
        let domEl = document.createElement("div");
        domEl.className = "xbmc_control";

        if(this.isSideBar)
        {
            if(this.playListId)
            {
                let playListSpan = document.createElement("span");
                playListSpan.setAttribute("rel", this.playListId);
                playListSpan.setAttribute("class", "xbmc_playlist xbmc_link");
                playListSpan.setAttribute("title", "Play All - Kassi Share");
                playListSpan.setAttribute("onclick", "return false;");
                playListSpan.appendChild(document.createTextNode("Play All"));

                domEl.appendChild(playListSpan);
                domEl.appendChild(document.createTextNode(" | "));
            }

            if(this.videoId)
            {
                let playSpan = document.createElement("span");
                playSpan.setAttribute("rel", this.videoId);
                playSpan.setAttribute("style", "padding-left: 180px;");
                playSpan.setAttribute("class", "xbmc_playNow xbmc_link");
                playSpan.setAttribute("title", "Play Now - Kassi Share");
                playSpan.setAttribute("onclick", "return false;");
                playSpan.appendChild(document.createTextNode("Play Now"));

                let queueSpan = document.createElement("span");
                queueSpan.setAttribute("rel", this.videoId);
                queueSpan.setAttribute("class", "xbmc_queue xbmc_link");
                queueSpan.setAttribute("title", "Add to Queue - Kassi Share");
                queueSpan.setAttribute("onclick", "return false;");
                queueSpan.appendChild(document.createTextNode("[+] Add to Queue"));

                domEl.appendChild(playSpan);
                domEl.appendChild(document.createTextNode(" | "));
                domEl.appendChild(queueSpan);
            }
        }
        else
        {
            if(this.playListId)
            {
                let listAnchor = document.createElement("a");
                listAnchor.setAttribute("href", "#");
                listAnchor.setAttribute("rel", this.playListId);
                listAnchor.setAttribute("title", "Play All - Kassi Share");
                listAnchor.setAttribute("onclick", "return false;");
                listAnchor.className = "xbmc_playlist";
                let listText = document.createTextNode("Play All");
                listAnchor.appendChild(listText);

                domEl.appendChild(listAnchor);
                domEl.appendChild(document.createTextNode(" | "));
            }

            if(this.videoId)
            {
                let playAnchor = document.createElement("a");
                playAnchor.setAttribute("href", "#");
                playAnchor.setAttribute("rel", this.videoId);
                playAnchor.setAttribute("title", "Play Now - Kassi Share");
                playAnchor.setAttribute("onclick", "return false;");
                playAnchor.className = "xbmc_playNow";
                playAnchor.appendChild(document.createTextNode("Play Now"));

                let queueAnchor = document.createElement("a");
                queueAnchor.setAttribute("href", "#");
                queueAnchor.setAttribute("rel", this.videoId);
                queueAnchor.setAttribute("title", "Add to Queue - Kassi Share");
                queueAnchor.setAttribute("onclick", "return false;");
                queueAnchor.className = "xbmc_queue";
                queueAnchor.appendChild(document.createTextNode("[+] Add to Queue"));

                domEl.appendChild(playAnchor);
                domEl.appendChild(document.createTextNode(" | "));
                domEl.appendChild(queueAnchor);
            }
        }

        return domEl;
    }
}

class Utils
{
    static findPropertyFromString(str, key)
    {
        let property = key + "=";
        var index = str.indexOf('?');
        str = str.substring(index + 1);

        var list = str.split('&');

        for (var i = 0; i < list.length; i++)
        {
            if (list[i].search(property) == 0)
            {
                return list[i].replace(property, "");
            }
        }
        return null;
    }
}

class Main
{
    constructor()
    {
        this.timerId = -1;
        this.rpc = new RpcService();

        let contentDiv = document.getElementById("content");
        if(contentDiv)
        {
            contentDiv.addEventListener("DOMNodeInserted", (event) => {
                this.injectLinksWithDelay();
            });
        }

        if (window.location.pathname == "/watch")
        {
            this.addLinkToWatchPage();
        }

        this.injectLinks();
    }

    addListeners(el)
    {
        var thisObject = this;
        // click event listeners
        el.querySelectorAll(".xbmc_playlist").forEach(function(innerEl)
        {
            innerEl.addEventListener("click", (event) => {
                let listId = innerEl.getAttribute("rel");

                if (listId)
                {
                    var listData = listId.split(" ");
                    console.log("playlist, " + listData);
                    thisObject.rpc.playListOnXBMC(listData[0], listData[1]);
                    event.preventDefault();
                }
            });

        });

        el.querySelectorAll(".xbmc_playNow").forEach(function(innerEl)
        {
            innerEl.addEventListener("click", (event) => {
                let rel = innerEl.getAttribute("rel");
                console.log("play single video, " + rel);
                thisObject.rpc.playVideoOnXBMC(rel);
                event.preventDefault();
            });

        });

        el.querySelectorAll(".xbmc_queue").forEach(function(innerEl)
        {
            innerEl.addEventListener("click", (event) => {
                let rel = innerEl.getAttribute("rel");
                console.log("queue single video, " + rel);
                thisObject.rpc.queueVideoToXBMC(rel);
                event.preventDefault();
            });

        });
    }

    injectLinks()
    {
        let thisObject = this;
        console.log("injectLinks ", this);
        // (home / subscription on home page), search page, video manager, user page, user browse video, Popular on YouTube, Popular on youtube right side, video list (on video page), play list page
        let classes = ".feed-item-content, .yt-lockup2-content, .vm-video-info-container, .yt-tile-visible, .channels-content-item, .lohp-category-shelf-item, .lohp-large-shelf-container, .lohp-medium-shelf-content, .lohp-vertical-shelf-item-content, .video-list-item, .playlist-video-item, .yt-lockup-content, .recent-activity-snippet, .playlist-actions, .pl-video-title";
        let divList = document.querySelectorAll(classes) || [];
        divList.forEach(function(el)
        {

            let alreadyAdded = false;
            el.querySelectorAll(".xbmc_control").forEach(function(innerEl)
            {
                alreadyAdded = true;
                return false;
            });

            if (alreadyAdded)
            {
                console.log("Already added - injectLinks");
                return; // continue
            }

            // (home / subscription on home page), search page, video manager, (user page / user browse video / Popular on YouTube)
            let df = el.querySelectorAll(".feed-video-title, .yt-uix-tile-link, .vm-video-title-content, .yt-uix-sessionlink, a");
            let len = df.length;
            console.log(typeof df, df);

            for (let i = 0; i < len; i++)
            {
                let innerEl = df[i];

                let videoPathString = innerEl.getAttribute("href");
                let listId;
                let videoId;
                let isSideBar = false;

                if (videoPathString)
                {
                    console.log("videoPathString, " + videoPathString);

                    // just a single video
                    videoId = Utils.findPropertyFromString(videoPathString, "v");
                    if (!videoId)
                    {
                        videoId = Utils.findPropertyFromString(videoPathString, "video_id");
                    }

                    if (!videoId)
                    {
                        videoId = Utils.findPropertyFromString(videoPathString, "video_ids");
                        if(videoId)
                        {
                            videoId = decodeURIComponent(videoId);
                            var vIndexText = Utils.findPropertyFromString(videoPathString, "index");
                            var vIndex = vIndexText ? parseInt(vIndexText) : 0;
                            if (vIndex < videoId.length)
                            {
                                try {
                                    videoId = videoId.split(",")[vIndex];
                                }
                                catch(err) {
                                    videoId = null;
                                }
                            }
                        }

                    }

                    if (videoId)
                    {
                        console.log("videoId, " + videoId);
                        if (el.classList.contains("video-list-item") || el.classList.contains("playlist-video-item"))
                        {
                            isSideBar = true;
                        }
                    }

                    // find play list id
                    listId = Utils.findPropertyFromString(videoPathString, "list");

                    //////

                    if (listId && videoId)
                    {
                        listId = listId + " " + videoId;
                    }

                    if (listId || videoId)
                    {
                        var divGen = new DivGenerator();
                        var div = divGen
                            .setVideo(videoId)
                            .setPlayList(listId)
                            .setSideBar(isSideBar)
                            .build();

                        thisObject.addListeners(div);
                        el.insertBefore(div, el.firstChild);
                        break;
                    }

                    listId = null;
                    videoId = null;
                }

            }
        });

    }

    injectLinksWithDelay()
    {
        clearTimeout(this.timerId);
        this.timerId = setTimeout(() => {

            this.injectLinks();
            if (window.location.pathname == "/watch")
            {
                console.log("video ID change.. inject watch link!");
                this.addLinkToWatchPage();
            }
        }, 1000)
    }

    addLinkToWatchPage()
    {
        console.log("addLinkToWatchPage, window.location, " + window.location);
        let thisObject = this;
        let alreadyAdded = false;
        let headLineDiv = document.getElementById("watch7-headline");

        headLineDiv.querySelectorAll(".xbmc_control").forEach(function(el)
        {
            alreadyAdded = true;
            return false;
        });

        if (alreadyAdded)
        {
            console.log("Already added - addLinkToWatchPage");
            return;
        }

        let loc = window.location.toString();
        var videoId = Utils.findPropertyFromString(loc, "v");
        let listId = Utils.findPropertyFromString(loc, "list");

        if (listId && videoId)
        {
            listId = listId + " " + videoId;
        }

        if (listId || videoId)
        {
            var divGen = new DivGenerator();
            var div = divGen
                .setVideo(videoId)
                .setPlayList(listId)
                .build();

            thisObject.addListeners(div);
            headLineDiv.insertBefore(div, headLineDiv.firstChild);
        }

    }

}

new Main();<|endoftext|>