<commit_before>"use strict"; // E C M A S C R I P T

//hardcoded streamlist
//2d array with name of stream and stream properties
var streamList = {
    "ESL_SC2": {},
    "nightblue3": {},
    "doublelift": {},
    "imaqtpie": {},
    "arumba07": {}
};

//onload
$(document).ready(function() {
    updateLists();

    $('#addStreamer').click(function() {
        var streamer = $('.form-control').val();
        $('#addStreamer').prop("disabled", true);
        checkExist(streamer);
    });
});

//gets dem channels J S O N
function getChannels(channel) {
    //api links used
    var channelApiLink = "https://wind-bow.gomix.me/twitch-api/channels/" + channel;
    var streamApiLink = "https://wind-bow.gomix.me/twitch-api/streams/" + channel;

    // return variables
    var returnObject = {};

    $.getJSON(streamApiLink).done(updateStream).fail(errStream); //JSON request

    // if JSON request goes through
    function updateStream(data) {
        var streamText = JSON.stringify(data["stream"]);

        //check if channel exists and is online.
        if (streamText === "null") { //if channel is offline or DNE
            $.getJSON(channelApiLink).done(updateChannel).fail(errChannel); //JSON request

            function updateChannel(channeldat) {
                var channelText = JSON.stringify(channeldat["status"]);
                if ($.isNumeric(channelText)) { //if DNE
                    returnObject = {
                        "streamName": null,
                        "message": null,
                        "game": null,
                        "imageLink": null,
                        "online": false
                    };
                } else { //if offline
                    returnObject = {
                        "streamName": JSON.stringify(channeldat["display_name"]).replace(/"/g, ""),
                        "message": JSON.stringify(channeldat["status"]).replace(/"/g, ""),
                        "game": JSON.stringify(channeldat["game"]).replace(/"/g, ""),
                        "imageLink": JSON.stringify(channeldat["logo"]).replace(/"/g, ""),
                        "online": false
                    }
                }
                console.log(returnObject);
                addToStreamList(channel, returnObject);
                populatePanels(channel);
            }

            function errChannel(jqxhr, textStatus, err) {
                console.log("Channel Request Failed: " + textStatus + ", " + err);
            }

        } else { //if channel is online
            returnObject = {
                "streamName": JSON.stringify(data["stream"]["channel"]["display_name"]).replace(/"/g, ""),
                "message": JSON.stringify(data["stream"]["channel"]["status"]).replace(/"/g, ""),
                "game": JSON.stringify(data["stream"]["game"]).replace(/"/g, ""),
                "imageLink": JSON.stringify(data["stream"]["channel"]["logo"]).replace(/"/g, ""),
                "online": true
            }
            console.log(returnObject);
            addToStreamList(channel, returnObject);
            populatePanels(channel);
        }
    }

    //if JSON request does not go through
    function errStream(jqxhr, textStatus, err) {
        console.log("Stream Request Failed: " + textStatus + ", " + err);
    }

}

//adds streaminfo to streamlist
function addToStreamList(channel, returnObject) {
    streamList[channel] = returnObject;
}

//pull stream data for each thing in streamlist
function updateLists() {
    for (var prop in streamList) {
        getChannels(prop);
    }
}

function populatePanels(prop) {
    let streamName = streamList[prop]["streamName"];
    let message = streamList[prop]["message"];
    let game = streamList[prop]["game"];
    let imageLink = streamList[prop]["imageLink"];
    let online = streamList[prop]["online"];

    //insert in housing panels
    if (online) {
        $('
', {
            class: "panel-body emptyme",
            id: prop + "pn1"
        }).insertAfter('#pan-head-online');

        $('
', {
            class: "row wrapper",
            id: prop + "row1"
        }).appendTo("#" + prop + "pn1");

        $('', {
            class: "imageLink col-md-2",
            id: prop + "imageLink",
            href: "https://www.twitch.tv/" + streamName,
            target: "_blank"
        }).appendTo('#' + prop + "row1");

        $('', {
            class: "profileImage center-block",
            src: imageLink,
            alt: prop + "Profile Image"
        }).appendTo('#' + prop + "imageLink");

        $('
', {
            class: "streamName col-md-1 center-block",
            id: streamName,
            html: "
" + streamName + "
"
        }).insertAfter('#' + prop + "imageLink");

        $('
', {
            class: "message col-md-6 col-md-offset-3 center-block",
            id: prop + "message",
            html: "
" + message + "
"
        }).insertAfter('#' + streamName);

        $('
', {
            class: "game center-text col-md-2 col-md-offset-2 center-block",
            id: prop + "game",
            html: "
" + game + "
"
        }).insertAfter('#' + prop + "message");

        $('', {
            href: "#",
            //onclick: removeItem(this),
            class: prop + " btn btn-danger btn-click col-md-2 btn-circle center-block text-center",
            id: prop + "remove",
            html: '',
            "data-toggle": "modal",
            "data-target": "#myModal",
            "data-id": prop
        }).insertAfter('#' + prop + "game");
    } else {
        $('
', {
            class: "panel-body emptyme",
            id: prop + "pn1"
        }).insertAfter('#pan-head-offline');

        $('
', {
            class: "row wrapper",
            id: prop + "row1"
        }).appendTo("#" + prop + "pn1");

        $('', {
            class: "imageLink col-md-2",
            id: prop + "imageLink",
            href: "https://www.twitch.tv/" + streamName,
            target: "_blank"
        }).appendTo('#' + prop + "row1");

        $('', {
            class: "profileImage center-block",
            src: imageLink,
            alt: prop + "Profile Image"
        }).appendTo('#' + prop + "imageLink");

        $('
', {
            class: "streamName col-md-1 center-block",
            id: streamName,
            html: "
" + streamName + "
"
        }).insertAfter('#' + prop + "imageLink");

        $('
', {
            class: "message col-md-6 col-md-offset-3 center-block",
            id: prop + "message",
            html: "
" + message + "
"
        }).insertAfter('#' + streamName);

        $('
', {
            class: "game center-text col-md-2 col-md-offset-2 center-block",
            id: prop + "game",
            html: "
" + game + "
"
        }).insertAfter('#' + prop + "message");

        $('', {
            href: "#",
            //onclick: removeItem(this),
            class: prop + " btn btn-danger btn-click col-md-2 btn-circle center-block text-center",
            id: prop + "remove",
            html: '',
            "data-toggle": "modal",
            "data-target": "#myModal",
            "data-id": prop
        }).insertAfter('#' + prop + "game");
    }
    RefreshEventListener();
}

function RefreshEventListener() {
    $('.wrapper').on('click', '.btn-click', function() {
        var property = $(this).attr("data-id");

        refreshModalListener(property);
    });
}

function refreshModalListener(property) {
    $('#myModal').on('click', '#modalDelete', function() {
        $('#' + property + 'pn1').remove();
    });
}

function checkExist(channel) {
    var apiLink = "https://wind-bow.gomix.me/twitch-api/channels/" + channel;

    $.getJSON(apiLink).done(update).fail(err); //JSON request

    function update(json) {
        var text = JSON.stringify(json["status"]);

        if ($.isNumeric(text)) { //if null
            alert("DNE!");
        } else if (streamList.hasOwnProperty(channel)) {
            alert("already in list!");
        } else {
            alert("Added " + channel)
            streamList[channel] = {};
            clearLists();
            updateLists();
        }
    }

    function err(jqxhr, textStatus, err) {
        console.log("Stream Request Failed: " + textStatus + ", " + err);
    }

    $('.form-control').val("");
    $('#addStreamer').prop("disabled", false);
}

function clearLists() {
    $('.emptyme').empty();
    $('.emptyme').remove();
}<commit_msg>Starting local storage functions<commit_after>"use strict"; // E C M A S C R I P T

//hardcoded streamlist
//2d array with name of stream and stream properties
var streamList = {
    "ESL_SC2": {},
    "nightblue3": {},
    "doublelift": {},
    "imaqtpie": {},
    "arumba07": {}
};

//onload
$(document).ready(function() {
    updateLists();

    $('#addStreamer').click(function() {
        var streamer = $('.form-control').val();
        $('#addStreamer').prop("disabled", true);
        checkExist(streamer);
    });
});

//gets dem channels J S O N
function getChannels(channel) {
    //api links used
    var channelApiLink = "https://wind-bow.gomix.me/twitch-api/channels/" + channel;
    var streamApiLink = "https://wind-bow.gomix.me/twitch-api/streams/" + channel;

    // return variables
    var returnObject = {};

    $.getJSON(streamApiLink).done(updateStream).fail(errStream); //JSON request

    // if JSON request goes through
    function updateStream(data) {
        var streamText = JSON.stringify(data["stream"]);

        //check if channel exists and is online.
        if (streamText === "null") { //if channel is offline or DNE
            $.getJSON(channelApiLink).done(updateChannel).fail(errChannel); //JSON request

            function updateChannel(channeldat) {
                var channelText = JSON.stringify(channeldat["status"]);
                if ($.isNumeric(channelText)) { //if DNE
                    returnObject = {
                        "streamName": null,
                        "message": null,
                        "game": null,
                        "imageLink": null,
                        "online": false
                    };
                } else { //if offline
                    returnObject = {
                        "streamName": JSON.stringify(channeldat["display_name"]).replace(/"/g, ""),
                        "message": JSON.stringify(channeldat["status"]).replace(/"/g, ""),
                        "game": JSON.stringify(channeldat["game"]).replace(/"/g, ""),
                        "imageLink": JSON.stringify(channeldat["logo"]).replace(/"/g, ""),
                        "online": false
                    }
                }
                console.log(returnObject);
                addToStreamList(channel, returnObject);
                populatePanels(channel);
            }

            function errChannel(jqxhr, textStatus, err) {
                console.log("Channel Request Failed: " + textStatus + ", " + err);
            }

        } else { //if channel is online
            returnObject = {
                "streamName": JSON.stringify(data["stream"]["channel"]["display_name"]).replace(/"/g, ""),
                "message": JSON.stringify(data["stream"]["channel"]["status"]).replace(/"/g, ""),
                "game": JSON.stringify(data["stream"]["game"]).replace(/"/g, ""),
                "imageLink": JSON.stringify(data["stream"]["channel"]["logo"]).replace(/"/g, ""),
                "online": true
            }
            console.log(returnObject);
            addToStreamList(channel, returnObject);
            populatePanels(channel);
        }
    }

    //if JSON request does not go through
    function errStream(jqxhr, textStatus, err) {
        console.log("Stream Request Failed: " + textStatus + ", " + err);
    }

}

//adds streaminfo to streamlist
function addToStreamList(channel, returnObject) {
    streamList[channel] = returnObject;
}

//pull stream data for each thing in streamlist
function updateLists() {
    for (var prop in streamList) {
        getChannels(prop);
    }
}

function populatePanels(prop) {
    let streamName = streamList[prop]["streamName"];
    let message = streamList[prop]["message"];
    let game = streamList[prop]["game"];
    let imageLink = streamList[prop]["imageLink"];
    let online = streamList[prop]["online"];

    //insert in housing panels
    if (online) {
        $('
', {
            class: "panel-body emptyme",
            id: prop + "pn1"
        }).insertAfter('#pan-head-online');

        $('
', {
            class: "row wrapper",
            id: prop + "row1"
        }).appendTo("#" + prop + "pn1");

        $('', {
            class: "imageLink col-md-2",
            id: prop + "imageLink",
            href: "https://www.twitch.tv/" + streamName,
            target: "_blank"
        }).appendTo('#' + prop + "row1");

        $('', {
            class: "profileImage center-block",
            src: imageLink,
            alt: prop + "Profile Image"
        }).appendTo('#' + prop + "imageLink");

        $('
', {
            class: "streamName col-md-1 center-block",
            id: streamName,
            html: "
" + streamName + "
"
        }).insertAfter('#' + prop + "imageLink");

        $('
', {
            class: "message col-md-6 col-md-offset-3 center-block",
            id: prop + "message",
            html: "
" + message + "
"
        }).insertAfter('#' + streamName);

        $('
', {
            class: "game center-text col-md-2 col-md-offset-2 center-block",
            id: prop + "game",
            html: "
" + game + "
"
        }).insertAfter('#' + prop + "message");

        $('', {
            href: "#",
            //onclick: removeItem(this),
            class: prop + " btn btn-danger btn-click col-md-2 btn-circle center-block text-center",
            id: prop + "remove",
            html: '',
            "data-toggle": "modal",
            "data-target": "#myModal",
            "data-id": prop
        }).insertAfter('#' + prop + "game");
    } else {
        $('
', {
            class: "panel-body emptyme",
            id: prop + "pn1"
        }).insertAfter('#pan-head-offline');

        $('
', {
            class: "row wrapper",
            id: prop + "row1"
        }).appendTo("#" + prop + "pn1");

        $('', {
            class: "imageLink col-md-2",
            id: prop + "imageLink",
            href: "https://www.twitch.tv/" + streamName,
            target: "_blank"
        }).appendTo('#' + prop + "row1");

        $('', {
            class: "profileImage center-block",
            src: imageLink,
            alt: prop + "Profile Image"
        }).appendTo('#' + prop + "imageLink");

        $('
', {
            class: "streamName col-md-1 center-block",
            id: streamName,
            html: "
" + streamName + "
"
        }).insertAfter('#' + prop + "imageLink");

        $('
', {
            class: "message col-md-6 col-md-offset-3 center-block",
            id: prop + "message",
            html: "
" + message + "
"
        }).insertAfter('#' + streamName);

        $('
', {
            class: "game center-text col-md-2 col-md-offset-2 center-block",
            id: prop + "game",
            html: "
" + game + "
"
        }).insertAfter('#' + prop + "message");

        $('', {
            href: "#",
            //onclick: removeItem(this),
            class: prop + " btn btn-danger btn-click col-md-2 btn-circle center-block text-center",
            id: prop + "remove",
            html: '',
            "data-toggle": "modal",
            "data-target": "#myModal",
            "data-id": prop
        }).insertAfter('#' + prop + "game");
    }
    RefreshEventListener();
}

function RefreshEventListener() {
    $('.wrapper').on('click', '.btn-click', function() {
        var property = $(this).attr("data-id");

        refreshModalListener(property);
    });
}

function refreshModalListener(property) {
    $('#myModal').on('click', '#modalDelete', function() {
        $('#' + property + 'pn1').remove();
    });
}

function checkExist(channel) {
    var apiLink = "https://wind-bow.gomix.me/twitch-api/channels/" + channel;

    $.getJSON(apiLink).done(update).fail(err); //JSON request

    function update(json) {
        var text = JSON.stringify(json["status"]);

        if ($.isNumeric(text)) { //if null
            alert("DNE!");
        } else if (streamList.hasOwnProperty(channel)) {
            alert("already in list!");
        } else {
            alert("Added " + channel)
            streamList[channel] = {};
            clearLists();
            updateLists();
        }
    }

    function err(jqxhr, textStatus, err) {
        console.log("Stream Request Failed: " + textStatus + ", " + err);
    }

    $('.form-control').val("");
    $('#addStreamer').prop("disabled", false);
}

function clearLists() {
    $('.emptyme').empty();
    $('.emptyme').remove();
}

function updateStory() {

}<|endoftext|>


<commit_before>'use strict';

// Declare app level module which depends on filters, and services
angular.module('realEstate', [
  'ngRoute',
  'realEstate.controllers'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/', {templateUrl: 'partials/home.html'});
  $routeProvider.otherwise({redirectTo: '/'});
}]);<commit_msg>ng route change routes.<commit_after>'use strict';

// Declare app level module which depends on filters, and services
angular.module('realEstate', [
  'ngRoute',
  'realEstate.controllers'
]).
config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/', {templateUrl: 'partials/home.html'});
  $routeProvider.when('/login', {templateUrl: 'partials/login.html'});
  $routeProvider.when('/register', {templateUrl: 'partials/register.html'});
  $routeProvider.when('/register/:edit', {templateUrl: 'partials/edit-profile.html'});
  $routeProvider.when('/property', {templateUrl: 'partials/view-property.html'});
  $routeProvider.when('/project', {templateUrl: 'partials/view-project.html'});
  $routeProvider.when('/addproperty', {templateUrl: 'partials/add-property.html'});
  $routeProvider.when('/addproject', {templateUrl: 'partials/add-project.html'});
  $routeProvider.otherwise({redirectTo: '/'});
}]);<|endoftext|>


<commit_before>/******************************************
* APPLICATION NAMESPACE
*/

var app = {

	// Global variables app //
	uniq_id_counter: 0,

	urlOE_authentication: '/sessions',
	urlOE_versionServer: '/web/webclient/version_info',
	urlOE_sessionDestroy: '/web/session/destroy',
	urlOE_sessionInformation: '/web/session/get_session_info',
	urlOE_menuUser: '/web/menu/load',
	urlOE_retrieveListe: '/web/dataset/search_read',
	urlOE_readObject: '/web/dataset/get',
	urlOE_createObject: '/web/dataset/create',
	urlOE_updateObject: '/web/dataset/save',
	urlOE_deleteObject: '/web/dataset/call',
	urlOE_object: '/web/dataset/call',

	// Classes //
	Collections     : {},
	Models          : {},
	Views           : {},

	// Instances //
	properties      : {},
	routes          : {},
	configuration   : {},
	lang            : {},
	collections     : {},
	models          : {},
	views           : {},
	templates       : {},

	/** Application initialization
	*/
	init: function (lang) {

		// Retrieve App properties, configuration and language //
		$.when(app.loadStaticFile('properties.json'), app.loadStaticFile('config/configuration.json'), app.loadStaticFile('config/routes.json'), app.loadI18nScripts(lang))
			.done(function (properties_data, configuration_data, routes_data, lang_data) {

				// Set the app properties configuration and language //
				app.properties    = properties_data[0];
				app.config 		  = configuration_data[0];
				app.routes        = routes_data[0];
				app.lang          = lang_data[0];

				// Instantiation Collections users  et user //
				app.collections.users           = new app.Collections.Users();
				app.collections.users.fetch();
				app.models.user                 = new app.Models.User();
				//app.models.team               = new app.Models.Team();
				app.models.task                 = new app.Models.Task();
				app.models.intervention         = new app.Models.Intervention();
				app.models.request              = new app.Models.Request();
				app.models.place                = new app.Models.Place();
				app.models.service              = new app.Models.ClaimerService();
				app.models.categoryTask         = new app.Models.CategoryTask();
				app.models.categoryIntervention = new app.Models.CategoryIntervention();
				app.models.claimerContact       = new app.Models.ClaimerContact();
				app.models.claimerType          = new app.Models.ClaimerType();

				// Router initialization //
				app.router = new app.Router();
				// Listen url changes //
				Backbone.history.start({pushState: false});
			})
			.fail(function(){
				console.error('Unable to init the app');
			});

	},

	current_user_token: function () {
		return localStorage.getItem('currentUserAuthToken');
	},

	/** Load internationalization scripts
	*/
	loadI18nScripts: function (lang) {

		var langFiles = ['moment-lang.js', 'bootstrap-datepicker-lang.js', 'select2-lang.js'];

		return $.getJSON('i18n/'+lang+'/app-lang.json')
			.success(function(data) {

				_.each(langFiles, function(file){
					var script = document.createElement('script');
					script.type = 'text/javascript';
					script.src = 'i18n/' + lang + '/' + file;
					$('#app').append(script);
				});

				// I18N Moment JS //
				moment.lang(lang);

			})
			.fail(function(){
				alert('Impossible de charger les fichiers de langues');
			});
	},

	loadStaticFile: function (url) {
		return $.getJSON(url)
			.success(function (data) {
			})
			.fail(function () {
				alert('Impossible de charger le fichier') + url;
			});
	},

	/** Load application configuration
	*/
	loadConfiguration: function(url){

		return $.getJSON(url)
			.success(function(data){
			})
			.fail(function(){
				alert('Impossible de charger le fichier de configuration');
			});
	},

	/******************************************
	* GENERIC FUNCTION FOR JSON/AJAX
	*/

	/** Formats an AJAX response to wrap JSON.
	*/
	rpc_jsonp: function(url, payload, options) {

		"use strict";

		// Extracted from payload to set on the url //
		var data = {
			session_id: '',
			id: payload.id
		};

		var ajax = _.extend({
			type: 'GET',
			dataType: 'jsonp',
			jsonp: 'jsonp',
			cache: false,
			data: data,
			url: url
		}, options);

		var payload_str = JSON.stringify(payload);
		console.debug(payload);

		var payload_url = $.param({r: payload_str});

		if (payload_url.length > 2000) {
			throw new Error('Payload is too big.');
		}
		// Direct jsonp request
		ajax.data.r = payload_str;
		return $.ajax(ajax);

	},

	/** Formats a standard JSON 2.0 call
	*/
	json: function (url, params, options) {

		"use strict";

		var deferred = $.Deferred();

		app.uniq_id_counter += 1;
		var payload = {
			'jsonrpc' : '2.0',
			'method'  : 'call',
			'params'  : params,
			'id'      : ("r" + app.uniq_id_counter)
		};

		app.rpc_jsonp(url, payload, options).then(function (data, textStatus, jqXHR) {
			if (data.error) {
				deferred.reject(data.error);
			}
			deferred.resolve(data.result, textStatus, jqXHR);
		});

		return deferred;
	},

	/** Retrieve an object from OpenERP
	*/
	getOE : function (model, fields, ids, session_id, options) {
		return this.json(app.config.openerp.url + this.urlOE_readObject, {
			'model'     : model,
			'fields'    : fields,
			'ids'       : ids
		}, options)},

	/** Retrieve a list from OpenERP
	*/
	readOE : function (model, session_id, options, fields) {

		var params = {
			'model'     : model,
			'session_id': session_id
		}

		// Limit - Offset //
		if(!_.isUndefined(options.limitOffset)){
		 	params.limit = options.limitOffset.limit;
		 	params.offset = options.limitOffset.offset;
		}

		// args - domain //
		if(!_.isUndefined(options.search)){
			params.domain = options.search;
		}

		// Sort by / Order //
		if(!_.isUndefined(options.sortBy)){
			params.sort = options.sortBy;
		}

		// Fields //
		if(_.isUndefined(fields)){
			params.fields = [];
		}else{
			params.fields = fields;
		}

		return this.json(app.config.openerp.url + this.urlOE_retrieveListe, params, options)
	},

	/** Delete object from OpenERP
	*/
	deleteOE : function (args,model,session_id,options) {
		this.json(app.config.openerp.url + this.urlOE_deleteObject, {
			'method'    : 'unlink',
			'args'      : args,
			'model'     : model,
			'session_id': session_id
		}, options);
	},

	/** Save object in OpenERP
	*/
	saveOE : function (id, data, model, session_id, options) {
		if(id)
			this.json(app.config.openerp.url + this.urlOE_updateObject, {
				'data'      : data,
				'model'     : model,
				'id'        : id,
				'session_id': session_id
		   },options);
		else
			this.json(app.config.openerp.url + this.urlOE_createObject, {
					'data'      : data,
					'model'     : model,
					'session_id': session_id
		   }, options);
	},

	/** call object method from OpenERP
	*/
	callObjectMethodOE : function (args, model, method, session_id, options) {
		return this.json(app.config.openerp.url + this.urlOE_object, {
			'method'    : method,
			'args'      : args,
			'model'     : model,
			'session_id': session_id
	   }, options);
	},

	/** Page Loader
	*/
	loader: function(action){

		var deferred = $.Deferred();

		switch(action){
			case 'display':
				$('#loader, #modal-block').fadeIn(250, deferred.resolve);
			break;

			case 'hide':
				$('#loader, #modal-block').fadeOut(450, deferred.resolve);
			break;
		}

		return deferred.promise();
	},

	/** Transform Decimal number to hour:minute
	*/
	decimalNumberToTime: function(decimalNumber){

		// Check if the number is decimal //
		if(_.str.include(decimalNumber, '.')){
			var minutes = _.lpad(((_.rpad(_(decimalNumber).strRight('.'), 2, '0') / 100) * 60), 2, '0');
			var hour = _(decimalNumber).strLeft('.');

			if(hour == 0){
				var date = _(minutes).toNumber()+app.lang.minuteShort;
			}
			else{
				var date = hour+'h'+_(minutes).toNumber();
			}
		}
		else{
			var date = decimalNumber+'h';
		}

		return date;
	},

	/** Calcul the page and the offset
	*/
	calculPageOffset: function(page){

		var paginate = {};

		if(_.isUndefined(page)){
			paginate.page = 1;
			paginate.offset = 0;
		}
		else{
			paginate.page = parseInt(page, 10);
			paginate.offset = (paginate.page - 1) * app.config.itemsPerPage;
		}

		return paginate;
	},

	/** Calcul the sort By column and the order
	*/
	calculPageSort: function(sort){

		var sorter = {};

		sorter.by = _(sort).strLeft('-');
		sorter.order = _(sort).strRight('-');

		return sorter;
	},

	objectifyFilters: function (filterArray) {
		return $.extend({},filterArray);
	},

	/** Calcul the Filter By
	*/
	calculPageFilter: function(filter){

		var filt = {};

		filt.by = _(filter).strLeft('-');
		filt.value = _(filter).strRight('-');

		return filt;
	},

	/** Calcul the search argument of the page
	*/
	calculSearch: function(searchQuery, searchableFields){

		//['|', ["name", "ilike", searchQuery], ["surface", "=", _(searchQuery).toNumber()]];
		//['&', ["state", "ilike", 'valid'], '|', ["name", "ilike", 'demande'], ["id", "=", _('demande').toNumber()]];

		var search = [];

		var searchableFieldsFilter = _.filter(searchableFields, function (field, index) {
			if (field.type != 'numeric') {
				return field;
			} else if (field.type == 'numeric' && _.isNumber(_(searchQuery.search).toNumber())) {
				return field;
			}
		});

		// Remplace the type By the search type for OpenERP //
		_.each(searchableFieldsFilter, function(item, index){
			switch(item.type){
				case 'numeric':
					item.type = '=';
					break;
				case 'text':
					item.type = 'ilike';
					break;
			}
		})

		// Check if there is a filter //
		if(!_.isUndefined(searchQuery.filter)){
			if(!_.isUndefined(searchQuery.search)){ search.push('&'); }
			search.push([searchQuery.filter.by, 'ilike', searchQuery.filter.value]);
		}

		// Check if there is a Search //
		if(!_.isUndefined(searchQuery.search)){
			// Search on several fields //
			if(_.size(searchableFieldsFilter) > 1){
				search.push('|');
				_.each(searchableFieldsFilter, function(item, index){
					if(item.type == '=' && _.isNumber(_(searchQuery.search).toNumber())){
						var term = _(searchQuery.search).toNumber();
					} else {
						var term = searchQuery.search;

					}
					search.push({field: item.key, operator: item.type, value: term});
				});
			}
			else{
				console.log(searchableFieldsFilter)
				search.push({field: searchableFieldsFilter[0].key, operator: searchableFieldsFilter[0].type, value: searchQuery.search});
			}
		}

		return app.objectifyFilters(search);
	},

	/** Notification Message
	*/
	notify: function(notifyModel, type, title, message) {

		"use strict";

		switch(notifyModel){
			case 'large' :
				var addClass = 'stack-bar-top big-icon';
				var width = '50%';
				var delay = 4500;
				var hide = true;
			break;

			default:
				var addClass = '';
				var width = '320px';
				var delay = 4500;
				var hide = true;
			break;

		}

		$.pnotify({
			title: title,
			text: message,
			addclass: addClass,
			width: width,
			type: type,
			hide: hide,
			animate_speed: 'normal',
			opacity: .9,
			icon: true,
			animation: 'slide',
			closer: true,
			closer_hover: false,
			delay: delay
		});
	}

};

// No conflict between Underscore && Underscore String //
_.mixin(_.str.exports());

/******************************************
* AFTER THE LOADING OF THE PAGE
*/
$(document).ready(function () {
	app.init('fr');
	$.ajaxSetup({
		contentType: "application/json",
		headers: {Authorization: 'Token token=' + app.current_user_token()},
		statusCode: {
			401: function () {
				// Redirect the to the login page.
				app.Router.navigate(app.routes.login.url, {trigger: true, replace: true});
			}
		}
	});
});

<commit_msg>fixes filters and minor refactoring<commit_after>/******************************************
* APPLICATION NAMESPACE
*/

var app = {

	// Global variables app //
	uniq_id_counter: 0,

	urlOE_authentication: '/sessions',
	urlOE_versionServer: '/web/webclient/version_info',
	urlOE_sessionDestroy: '/web/session/destroy',
	urlOE_sessionInformation: '/web/session/get_session_info',
	urlOE_menuUser: '/web/menu/load',
	urlOE_retrieveListe: '/web/dataset/search_read',
	urlOE_readObject: '/web/dataset/get',
	urlOE_createObject: '/web/dataset/create',
	urlOE_updateObject: '/web/dataset/save',
	urlOE_deleteObject: '/web/dataset/call',
	urlOE_object: '/web/dataset/call',

	// Classes //
	Collections     : {},
	Models          : {},
	Views           : {},

	// Instances //
	properties      : {},
	routes          : {},
	configuration   : {},
	lang            : {},
	collections     : {},
	models          : {},
	views           : {},
	templates       : {},

	/** Application initialization
	*/
	init: function (lang) {

		// Retrieve App properties, configuration and language //
		$.when(app.loadStaticFile('properties.json'), app.loadStaticFile('config/configuration.json'), app.loadStaticFile('config/routes.json'), app.loadI18nScripts(lang))
			.done(function (properties_data, configuration_data, routes_data, lang_data) {

				// Set the app properties configuration and language //
				app.properties    = properties_data[0];
				app.config 		  = configuration_data[0];
				app.routes        = routes_data[0];
				app.lang          = lang_data[0];

				// Instantiation Collections users  et user //
				app.collections.users           = new app.Collections.Users();
				app.collections.users.fetch();
				app.models.user                 = new app.Models.User();
				//app.models.team               = new app.Models.Team();
				app.models.task                 = new app.Models.Task();
				app.models.intervention         = new app.Models.Intervention();
				app.models.request              = new app.Models.Request();
				app.models.place                = new app.Models.Place();
				app.models.service              = new app.Models.ClaimerService();
				app.models.categoryTask         = new app.Models.CategoryTask();
				app.models.categoryIntervention = new app.Models.CategoryIntervention();
				app.models.claimerContact       = new app.Models.ClaimerContact();
				app.models.claimerType          = new app.Models.ClaimerType();

				// Router initialization //
				app.router = new app.Router();
				// Listen url changes //
				Backbone.history.start({pushState: false});
			})
			.fail(function(){
				console.error('Unable to init the app');
			});

	},

	current_user_token: function () {
		return localStorage.getItem('currentUserAuthToken');
	},

	/** Load internationalization scripts
	*/
	loadI18nScripts: function (lang) {

		var langFiles = ['moment-lang.js', 'bootstrap-datepicker-lang.js', 'select2-lang.js'];

		return $.getJSON('i18n/'+lang+'/app-lang.json')
			.success(function(data) {

				_.each(langFiles, function(file){
					var script = document.createElement('script');
					script.type = 'text/javascript';
					script.src = 'i18n/' + lang + '/' + file;
					$('#app').append(script);
				});

				// I18N Moment JS //
				moment.lang(lang);

			})
			.fail(function(){
				alert('Impossible de charger les fichiers de langues');
			});
	},

	loadStaticFile: function (url) {
		return $.getJSON(url)
			.success(function (data) {
			})
			.fail(function () {
				alert('Impossible de charger le fichier') + url;
			});
	},

	/** Load application configuration
	*/
	loadConfiguration: function(url){

		return $.getJSON(url)
			.success(function(data){
			})
			.fail(function(){
				alert('Impossible de charger le fichier de configuration');
			});
	},

	/******************************************
	* GENERIC FUNCTION FOR JSON/AJAX
	*/

	/** Formats an AJAX response to wrap JSON.
	*/
	rpc_jsonp: function(url, payload, options) {

		"use strict";

		// Extracted from payload to set on the url //
		var data = {
			session_id: '',
			id: payload.id
		};

		var ajax = _.extend({
			type: 'GET',
			dataType: 'jsonp',
			jsonp: 'jsonp',
			cache: false,
			data: data,
			url: url
		}, options);

		var payload_str = JSON.stringify(payload);
		console.debug(payload);

		var payload_url = $.param({r: payload_str});

		if (payload_url.length > 2000) {
			throw new Error('Payload is too big.');
		}
		// Direct jsonp request
		ajax.data.r = payload_str;
		return $.ajax(ajax);

	},

	/** Formats a standard JSON 2.0 call
	*/
	json: function (url, params, options) {

		"use strict";

		var deferred = $.Deferred();

		app.uniq_id_counter += 1;
		var payload = {
			'jsonrpc' : '2.0',
			'method'  : 'call',
			'params'  : params,
			'id'      : ("r" + app.uniq_id_counter)
		};

		app.rpc_jsonp(url, payload, options).then(function (data, textStatus, jqXHR) {
			if (data.error) {
				deferred.reject(data.error);
			}
			deferred.resolve(data.result, textStatus, jqXHR);
		});

		return deferred;
	},

	/** Retrieve an object from OpenERP
	*/
	getOE : function (model, fields, ids, session_id, options) {
		return this.json(app.config.openerp.url + this.urlOE_readObject, {
			'model'     : model,
			'fields'    : fields,
			'ids'       : ids
		}, options)},

	/** Retrieve a list from OpenERP
	*/
	readOE : function (model, session_id, options, fields) {

		var params = {
			'model'     : model,
			'session_id': session_id
		}

		// Limit - Offset //
		if(!_.isUndefined(options.limitOffset)){
		 	params.limit = options.limitOffset.limit;
		 	params.offset = options.limitOffset.offset;
		}

		// args - domain //
		if(!_.isUndefined(options.search)){
			params.domain = options.search;
		}

		// Sort by / Order //
		if(!_.isUndefined(options.sortBy)){
			params.sort = options.sortBy;
		}

		// Fields //
		if(_.isUndefined(fields)){
			params.fields = [];
		}else{
			params.fields = fields;
		}

		return this.json(app.config.openerp.url + this.urlOE_retrieveListe, params, options)
	},

	/** Delete object from OpenERP
	*/
	deleteOE : function (args,model,session_id,options) {
		this.json(app.config.openerp.url + this.urlOE_deleteObject, {
			'method'    : 'unlink',
			'args'      : args,
			'model'     : model,
			'session_id': session_id
		}, options);
	},

	/** Save object in OpenERP
	*/
	saveOE : function (id, data, model, session_id, options) {
		if(id)
			this.json(app.config.openerp.url + this.urlOE_updateObject, {
				'data'      : data,
				'model'     : model,
				'id'        : id,
				'session_id': session_id
		   },options);
		else
			this.json(app.config.openerp.url + this.urlOE_createObject, {
					'data'      : data,
					'model'     : model,
					'session_id': session_id
		   }, options);
	},

	/** call object method from OpenERP
	*/
	callObjectMethodOE : function (args, model, method, session_id, options) {
		return this.json(app.config.openerp.url + this.urlOE_object, {
			'method'    : method,
			'args'      : args,
			'model'     : model,
			'session_id': session_id
	   }, options);
	},

	/** Page Loader
	*/
	loader: function(action){

		var deferred = $.Deferred();

		switch(action){
			case 'display':
				$('#loader, #modal-block').fadeIn(250, deferred.resolve);
			break;

			case 'hide':
				$('#loader, #modal-block').fadeOut(450, deferred.resolve);
			break;
		}

		return deferred.promise();
	},

	/** Transform Decimal number to hour:minute
	*/
	decimalNumberToTime: function(decimalNumber){

		// Check if the number is decimal //
		if(_.str.include(decimalNumber, '.')){
			var minutes = _.lpad(((_.rpad(_(decimalNumber).strRight('.'), 2, '0') / 100) * 60), 2, '0');
			var hour = _(decimalNumber).strLeft('.');

			if(hour == 0){
				var date = _(minutes).toNumber()+app.lang.minuteShort;
			}
			else{
				var date = hour+'h'+_(minutes).toNumber();
			}
		}
		else{
			var date = decimalNumber+'h';
		}

		return date;
	},

	/** Calcul the page and the offset
	*/
	calculPageOffset: function(page){

		var paginate = {};

		if(_.isUndefined(page)){
			paginate.page = 1;
			paginate.offset = 0;
		}
		else{
			paginate.page = parseInt(page, 10);
			paginate.offset = (paginate.page - 1) * app.config.itemsPerPage;
		}

		return paginate;
	},

	/** Calcul the sort By column and the order
	*/
	calculPageSort: function(sort){

		var sorter = {};

		sorter.by = _(sort).strLeft('-');
		sorter.order = _(sort).strRight('-');

		return sorter;
	},

	objectifyFilters: function (filterArray) {
		return $.extend({},filterArray);
	},

	/** Calcul the Filter By
	*/
	calculPageFilter: function(filter){

		var filt = {};

		filt.by = _(filter).strLeft('-');
		filt.value = _(filter).strRight('-');

		return filt;
	},

	/** Calcul the search argument of the page
	 */
	calculSearch: function (searchQuery, searchableFields) {

		//['|', ["name", "ilike", searchQuery], ["surface", "=", _(searchQuery).toNumber()]];
		//['&', ["state", "ilike", 'valid'], '|', ["name", "ilike", 'demande'], ["id", "=", _('demande').toNumber()]];

		var search = [];

		function isNumber(n) {
			return !isNaN(parseFloat(n)) && isFinite(n);
		};

		function convertFieldFilters(fieldsFilters) {
			var convertedFilters = [];

			function convertFilter(filter, operator) {
				return {key:filter.key, type: operator};
			};

			_.each(fieldsFilters, function (filter, index) {
				switch (filter.type) {
					case 'numeric':
						if (isNumber(searchQuery.search)) {
							convertedFilters.push(convertFilter(filter, '='));
						}
						break;
					case 'text':
						convertedFilters.push(convertFilter(filter, 'ilike'));
						break;
				}
			});
			return convertedFilters;
		};

		var filteredAndConvertedFilters = convertFieldFilters(searchableFields);

		function buildFilterObject(field,operator,value) {
			return {field: field, operator:operator, value:value}
		};

		// Check if there is a filter //
		if (!_.isUndefined(searchQuery.filter)) {
			if (!_.isUndefined(searchQuery.search)) {
				search.push('&');
			}
			search.push( buildFilterObject(searchQuery.filter.by,'ilike',searchQuery.filter.value));
		}

		// Check if there is a Search //
		if (!_.isUndefined(searchQuery.search)) {
			// Search on several fields //
			if (_.size(filteredAndConvertedFilters) > 1) {
				search.push('|');
				_.each(filteredAndConvertedFilters, function (item, index) {
					if (item.type == '=' && isNumber(searchQuery.search)) {
						var term = _(searchQuery.search).toNumber();
					} else {
						var term = searchQuery.search;

					}
					search.push(buildFilterObject(item.key,item.type,term));
				});
			}
			else {
				search.push( buildFilterObject(filteredAndConvertedFilters[0].key,filteredAndConvertedFilters[0].type,searchQuery.search));
			}
		}

		return app.objectifyFilters(search);
	},

	/** Notification Message
	*/
	notify: function(notifyModel, type, title, message) {

		"use strict";

		switch(notifyModel){
			case 'large' :
				var addClass = 'stack-bar-top big-icon';
				var width = '50%';
				var delay = 4500;
				var hide = true;
			break;

			default:
				var addClass = '';
				var width = '320px';
				var delay = 4500;
				var hide = true;
			break;

		}

		$.pnotify({
			title: title,
			text: message,
			addclass: addClass,
			width: width,
			type: type,
			hide: hide,
			animate_speed: 'normal',
			opacity: .9,
			icon: true,
			animation: 'slide',
			closer: true,
			closer_hover: false,
			delay: delay
		});
	}

};

// No conflict between Underscore && Underscore String //
_.mixin(_.str.exports());

/******************************************
* AFTER THE LOADING OF THE PAGE
*/
$(document).ready(function () {
	app.init('fr');
	$.ajaxSetup({
		contentType: "application/json",
		headers: {Authorization: 'Token token=' + app.current_user_token()},
		statusCode: {
			401: function () {
				// Redirect the to the login page.
				app.Router.navigate(app.routes.login.url, {trigger: true, replace: true});
			}
		}
	});
});

<|endoftext|>


<commit_before>// fork getUserMedia for multiple browser versions, for those
// that need prefixes
navigator.getUserMedia = (navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia);

// set up forked web audio context, for multiple browsers
// window. is needed otherwise Safari explodes
window.AudioContext = (window.AudioContext || window.webkitAudioContext);

var audioCtx = new window.AudioContext();
var source;
var stream;

//set up the different audio nodes we will use for the app
var analyser = audioCtx.createAnalyser();
analyser.minDecibels = -$('#sensitivity').val();
$('#sensitivity').change(function () {
    analyser.minDecibels = -$('#sensitivity').val();
});
analyser.maxDecibels = -0;
analyser.smoothingTimeConstant = 0;

// set up canvas context for visualizer
var canvas = $('#canvas');
var canvasCtx = document.getElementById("canvas").getContext("2d");
var appWidth = canvas.parent().width();
canvas.attr('width', appWidth);
WIDTH = canvas.width();
HEIGHT = canvas.height();
var drawVisual;

//main block for doing the audio recording

if (navigator.getUserMedia) {
    console.log('getUserMedia supported.');
    navigator.getUserMedia(
        // constraints - only audio needed for this app
        {
            audio: true
        },

        // Success callback
        function (stream) {
            source = audioCtx.createMediaStreamSource(stream);
            source.connect(analyser);
            $('#startBtn').show();
        },

        // Error callback
        function (err) {
            setTimeout(function () {
                window.alert('Please refresh and allow audio recording.');
            }, 0);
            console.error(err);
            $('#startBtn').attr('disabled', 'disabled');
            $('#stopBtn').attr('disabled', 'disabled');
        }
    );
} else {
    setTimeout(function () {
        window.alert('Your browser doesn\'t support audio recodering, please use newer browser instead. ');
    }, 0);
    console.error('getUserMedia not supported on your browser!');
    $('#startBtn').attr('disabled', 'disabled');
    $('#stopBtn').attr('disabled', 'disabled');
}

var player;
var enemies = [];
var score;
var gameArea = {
    start: function () {
        this.frameNo = 0;
    },
    clear: function () {
        canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
    }
};
analyser.fftSize = 32;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);

function updateGameArea() {
    drawVisual = requestAnimationFrame(updateGameArea);
    for (var e1 in enemies) {
        if (player.crashWith(enemies[e1])) {
            stopGame();
            return;
        }
    }
    gameArea.clear();
    gameArea.frameNo++;
    $('#score').text(gameArea.frameNo);

    analyser.getByteFrequencyData(dataArray);
    var avg = 0;
    for (var i = 0; i < bufferLength; i++) {
        avg += dataArray[i];
    }
    avg = avg / bufferLength;
    if (avg > 10) {
        player.speedX = 2;
    } else {
        player.speedX = 0;
    }
    if (avg > 30 && player.hitBottom()) {
        player.speedY = Math.max(-avg / 7, -7);
        console.log('jump ' + player.speedY);
    }
    player.update();

    if (gameArea.frameNo % 300 === 1) {
        enemy = new component(40, 40, 'red', 1000, HEIGHT - 40);
        enemy.speedX = -1;
        enemies.push(enemy);
    }
    for (var e2 in enemies) {
        enemies[e2].update();
    }

}

function component(width, height, color, x, y, type) {
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.gravity = 0.08;
    this.x = x;
    this.y = y;
    this.update = function () {
        this.speedY += this.gravity;
        this.x += this.speedX;
        this.y += this.speedY;
        this.hitBottom();
        canvasCtx.fillStyle = color;
        canvasCtx.fillRect(this.x, this.y, this.width, this.height);
    };
    this.hitBottom = function () {
        var btmPos = HEIGHT - this.height;
        if (this.y > btmPos) {
            this.y = HEIGHT - this.height;
            this.speedY = 0;
            return true;
        } else if (this.y === btmPos) {
            return true;
        } else {
            return false;
        }
    };
    this.crashWith = function (otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) ||
            (mytop > otherbottom) ||
            (myright < otherleft) ||
            (myleft > otherright)) {
            crash = false;
        }
        return crash;
    };
}

$('#startBtn').click(startGame);

$('#stopBtn').click(stopGame);

function startGame() {
    $('#stopBtn').show();
    $('#startBtn').hide();
    player = new component(60, 100, 'blue', 10, HEIGHT - 100);
    enemies = [];
    gameArea.start();
    updateGameArea();
}

function stopGame() {
    $('#stopBtn').hide();
    $('#startBtn').show();
    cancelAnimationFrame(drawVisual);
}

function visualize() {
    analyser.fftSize = 32;
    var bufferLength = analyser.frequencyBinCount;
    var dataArray = new Uint8Array(bufferLength);

    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

    function draw() {
        drawVisual = requestAnimationFrame(draw);

        analyser.getByteFrequencyData(dataArray);

        canvasCtx.fillStyle = 'rgb(0, 0, 0)';
        canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

        var barWidth = (WIDTH / bufferLength);
        var barHeight;
        var x = 0;
        var avg = 0;

        for (var i = 0; i < bufferLength; i++) {
            barHeight = dataArray[i];
            avg += dataArray[i];

            canvasCtx.fillStyle = 'rgb(' + (barHeight + 100) + ',50,50)';
            canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);

            x += barWidth + 1;
        }

        console.log(avg / bufferLength);
    }

    draw();
}
<commit_msg>add ground<commit_after>// fork getUserMedia for multiple browser versions, for those
// that need prefixes
navigator.getUserMedia = (navigator.getUserMedia ||
    navigator.webkitGetUserMedia ||
    navigator.mozGetUserMedia ||
    navigator.msGetUserMedia);

// set up forked web audio context, for multiple browsers
// window. is needed otherwise Safari explodes
window.AudioContext = (window.AudioContext || window.webkitAudioContext);

var audioCtx = new window.AudioContext();
var source;
var stream;

//set up the different audio nodes we will use for the app
var analyser = audioCtx.createAnalyser();
analyser.minDecibels = -$('#sensitivity').val();
$('#sensitivity').change(function () {
    analyser.minDecibels = -$('#sensitivity').val();
});
analyser.maxDecibels = -0;
analyser.smoothingTimeConstant = 0;

// set up canvas context for visualizer
var canvas = $('#canvas');
var canvasCtx = document.getElementById("canvas").getContext("2d");
var appWidth = canvas.parent().width();
canvas.attr('width', appWidth);
WIDTH = canvas.width();
HEIGHT = canvas.height();
var drawVisual;

//main block for doing the audio recording

if (navigator.getUserMedia) {
    console.log('getUserMedia supported.');
    navigator.getUserMedia(
        // constraints - only audio needed for this app
        {
            audio: true
        },

        // Success callback
        function (stream) {
            source = audioCtx.createMediaStreamSource(stream);
            source.connect(analyser);
            $('#startBtn').show();
        },

        // Error callback
        function (err) {
            setTimeout(function () {
                window.alert('Please refresh and allow audio recording.');
            }, 0);
            console.error(err);
            $('#startBtn').attr('disabled', 'disabled');
            $('#stopBtn').attr('disabled', 'disabled');
        }
    );
} else {
    setTimeout(function () {
        window.alert('Your browser doesn\'t support audio recodering, please use newer browser instead. ');
    }, 0);
    console.error('getUserMedia not supported on your browser!');
    $('#startBtn').attr('disabled', 'disabled');
    $('#stopBtn').attr('disabled', 'disabled');
}

var player;
var isCentered = false;
var enemies = [];
var grounds = [];
var score;
var gameArea = {
    start: function () {
        this.frameNo = 0;
    },
    clear: function () {
        canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);
    }
};
analyser.fftSize = 32;
var bufferLength = analyser.frequencyBinCount;
var dataArray = new Uint8Array(bufferLength);

function updateGameArea() {
    drawVisual = requestAnimationFrame(updateGameArea);
    for (var e1 in enemies) {
        if (player.crashWith(enemies[e1]) || player.y > HEIGHT) {
            stopGame();
            return;
        }
    }
    gameArea.clear();
    gameArea.frameNo++;
    $('#score').text(gameArea.frameNo);

    analyser.getByteFrequencyData(dataArray);
    var avg = 0;
    for (var i = 0; i < bufferLength; i++) {
        avg += dataArray[i];
    }
    avg = avg / bufferLength;
    if (avg > 10) {
        player.speedX = 2;
    } else {
        player.speedX = 0;
    }
    if (avg > 30 && player.hitGround()) {
        player.speedY = Math.max(-avg / 7, -7);
        console.log('jump ' + player.speedY);
    }
    player.update();

    for (var g1 in grounds) {
        grounds[g1].update();
    }

    if (gameArea.frameNo % 300 === 1) {
        enemy = new component(40, 40, 'red', 1000, HEIGHT - 40, 'enemy');
        enemy.speedX = -1;
        enemies.push(enemy);
    }
    for (var e2 in enemies) {
        enemies[e2].update();
    }

}

function component(width, height, color, x, y, type) {
    this.compType = type;
    this.width = width;
    this.height = height;
    this.speedX = 0;
    this.speedY = 0;
    this.gravity = 0.08;
    this.x = x;
    this.y = y;
    this.update = function () {
        this.speedY += this.gravity;
        this.y += this.speedY;
        this.hitGround();
        if ((!isCentered) &&
            (this.compType === 'player') &&
            (this.x >= (WIDTH - this.width) / 2)) {
            isCentered = !isCentered;
        }
        if (isCentered) {
            if (this.compType !== 'player') {
                this.x -= player.speedX;
            }
        } else {
            this.x += this.speedX;
        }
        canvasCtx.fillStyle = color;
        canvasCtx.fillRect(this.x, this.y, this.width, this.height);
    };
    this.hitGround = function () {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var ghighest = 0;
        for (var g in grounds) {
            var gleft = grounds[g].x;
            var gright = grounds[g].x + grounds[g].width;
            var gtop = grounds[g].y;
            if ((gleft <= myleft && gright >= myleft) ||
                (gleft <= myright && gright >= myright)) {
                ghighest = Math.max(ghighest, gtop);
            }
            // if ((this.speedX > 0 && mybottom >= gtop && myright >= gleft) ||
            //     (this.speedX < 0 && mybottom >= gtop && myleft <= gright)) {
            //     this.speedX = 0;
            // }
        }

        if (mybottom > ghighest) {
            this.y = ghighest - this.height;
            this.speedY = 0;
            return true;
        } else if (mybottom === ghighest) {
            return true;
        } else {
            return false;
        }
        return false;
    };
    this.crashWith = function (otherobj) {
        var myleft = this.x;
        var myright = this.x + (this.width);
        var mytop = this.y;
        var mybottom = this.y + (this.height);
        var otherleft = otherobj.x;
        var otherright = otherobj.x + (otherobj.width);
        var othertop = otherobj.y;
        var otherbottom = otherobj.y + (otherobj.height);
        var crash = true;
        if ((mybottom < othertop) ||
            (mytop > otherbottom) ||
            (myright < otherleft) ||
            (myleft > otherright)) {
            crash = false;
        }
        return crash;
    };
}

function ground(width, height, x) {
    this.compType = 'ground';
    this.width = width;
    this.height = height + 1;
    this.speedX = 0;
    this.speedY = 0;
    this.gravity = 0;
    this.x = x;
    this.y = HEIGHT - height - 1;
    this.update = function () {
        this.speedY += this.gravity;
        this.y += this.speedY;
        if (isCentered) {
            if (this.compType !== 'player') {
                this.x -= player.speedX;
            }
        } else {
            this.x += this.speedX;
        }
        canvasCtx.fillStyle = 'black';
        canvasCtx.fillRect(this.x, this.y, this.width, this.height);
    };
}

$('#startBtn').click(startGame);

$('#stopBtn').click(stopGame);

function startGame() {
    $('#stopBtn').show();
    $('#startBtn').hide();
    player = new component(60, 100, 'blue', 10, HEIGHT - 100, 'player');
    enemies = [];
    grounds = [new ground(500, 0, 0), new ground(200, 100, 500)];
    gameArea.start();
    updateGameArea();
}

function stopGame() {
    $('#stopBtn').hide();
    $('#startBtn').show();
    cancelAnimationFrame(drawVisual);
}

function visualize() {
    analyser.fftSize = 32;
    var bufferLength = analyser.frequencyBinCount;
    var dataArray = new Uint8Array(bufferLength);

    canvasCtx.clearRect(0, 0, WIDTH, HEIGHT);

    function draw() {
        drawVisual = requestAnimationFrame(draw);

        analyser.getByteFrequencyData(dataArray);

        canvasCtx.fillStyle = 'rgb(0, 0, 0)';
        canvasCtx.fillRect(0, 0, WIDTH, HEIGHT);

        var barWidth = (WIDTH / bufferLength);
        var barHeight;
        var x = 0;
        var avg = 0;

        for (var i = 0; i < bufferLength; i++) {
            barHeight = dataArray[i];
            avg += dataArray[i];

            canvasCtx.fillStyle = 'rgb(' + (barHeight + 100) + ',50,50)';
            canvasCtx.fillRect(x, HEIGHT - barHeight, barWidth, barHeight);

            x += barWidth + 1;
        }

        console.log(avg / bufferLength);
    }

    draw();
}
<|endoftext|>


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

app.controller('appController', ['$scope', '$http', function($scope, $http) {

  $http.get("https://api-equite-parole.github.io/api/2017-02-01--2017-02-26/chaines-generalistes.json").then(function(result) {

    //console.log(result);

    var content = [];
    angular.forEach(result.data, function(value, key) {
      content.push({
        "label": key,
        "value": value.total_temps_antenne.secondes,
        "color": "#2484c1"
      });
    });

    var data = {
      "sortOrder": "value-desc",
      "content": content
    };

    var pie = new d3pie("pieChart", {
      "header": {
        "title": {
          "text": "Temps d'antenne sur les chaînes généralistes du 1er Février 2017 au 26 Février 2017",
          "fontSize": 24,
          "font": "open sans"
        },
        "subtitle": {
          "text": "Equité de temps de parole pour les candidats à la présidentielle 2017",
          "color": "#999999",
          "fontSize": 12,
          "font": "open sans"
        },
        "titleSubtitlePadding": 9
      },
      "footer": {
        "color": "#999999",
        "fontSize": 10,
        "font": "open sans",
        "location": "bottom-left"
      },
      "size": {
        "canvasWidth":900,
        "pieOuterRadius": "90%"
      },
      "data": data,
      "labels": {
        "outer": {
          "pieDistance": 32
        },
        "inner": {
          "hideWhenLessThanPercentage": 3
        },
        "mainLabel": {
          "fontSize": 11
        },
        "percentage": {
          "color": "#ffffff",
          "decimalPlaces": 0
        },
        "value": {
          "color": "#adadad",
          "fontSize": 11
        },
        "lines": {
          "enabled": true
        },
        "truncation": {
          "enabled": true
        }
      },
      "effects": {
        "pullOutSegmentOnClick": {
          "effect": "linear",
          "speed": 400,
          "size": 8
        }
      },
      "misc": {
        "gradient": {
          "enabled": true,
          "percentage": 100
        }
      }
    });

  });

}]);
<commit_msg>fix url for api call<commit_after>
var app = angular.module('app', []);

app.controller('appController', ['$scope', '$http', function($scope, $http) {

  $http.get("https://equite-parole.github.io/api/2017-02-01--2017-02-26/chaines-generalistes.json").then(function(result) {

    //console.log(result);

    var content = [];
    angular.forEach(result.data, function(value, key) {
      content.push({
        "label": key,
        "value": value.total_temps_antenne.secondes,
        "color": "#2484c1"
      });
    });

    var data = {
      "sortOrder": "value-desc",
      "content": content
    };

    var pie = new d3pie("pieChart", {
      "header": {
        "title": {
          "text": "Temps d'antenne sur les chaînes généralistes du 1er Février 2017 au 26 Février 2017",
          "fontSize": 24,
          "font": "open sans"
        },
        "subtitle": {
          "text": "Equité de temps de parole pour les candidats à la présidentielle 2017",
          "color": "#999999",
          "fontSize": 12,
          "font": "open sans"
        },
        "titleSubtitlePadding": 9
      },
      "footer": {
        "color": "#999999",
        "fontSize": 10,
        "font": "open sans",
        "location": "bottom-left"
      },
      "size": {
        "canvasWidth":900,
        "pieOuterRadius": "90%"
      },
      "data": data,
      "labels": {
        "outer": {
          "pieDistance": 32
        },
        "inner": {
          "hideWhenLessThanPercentage": 3
        },
        "mainLabel": {
          "fontSize": 11
        },
        "percentage": {
          "color": "#ffffff",
          "decimalPlaces": 0
        },
        "value": {
          "color": "#adadad",
          "fontSize": 11
        },
        "lines": {
          "enabled": true
        },
        "truncation": {
          "enabled": true
        }
      },
      "effects": {
        "pullOutSegmentOnClick": {
          "effect": "linear",
          "speed": 400,
          "size": 8
        }
      },
      "misc": {
        "gradient": {
          "enabled": true,
          "percentage": 100
        }
      }
    });

  });

}]);
<|endoftext|>


<commit_before>var last_sms_id = -1;
var httpServer = new HTTPServer(8080);

// Logging the result from messages
function logMsg(msg){
	var r = "";
	['type', 'id', 'threadId', 'body', 'delivery', 'deliveryStatus', 'read', 'receiver', 'sender', 'timestamp', 'messageClass'].forEach(function (key){
		r += '
 ' + key + ': ' + msg[key];
	});
	console.log(r);
}

// Not very beautiful, but for now, it is OK
function update_loc(){
	$('[data-l10n-id]').each(function(index){
		$(this).html(navigator.mozL10n.get($(this).attr('data-l10n-id')));
	});
}

function load_page(requested_page){
	console.log('Loading page ' + requested_page);
	if (requested_page == "about"){
		$("#main-container").load("../content/about_content.html", function() {
			console.log('Loading of the HTML performed');
			update_loc();
		});
	} else if (requested_page == "server"){
		$("#main-container").load("../content/server_content.html", function() {
			console.log('Loading of the HTML performed');
			update_loc();

			var sstatus = document.getElementById('server-status');
			var ip     = document.getElementById('ip-address');
			var port   = document.getElementById('listening-port');
			var start_b  = document.getElementById('start-server');
			var stop_b   = document.getElementById('stop-server');

			IPUtils.getAddresses(function(ipAddress) {
				ip.textContent = ip.textContent || ipAddress;
			});

			port.textContent = httpServer.port;

			// may be to modify, when the server is correctly running
			if (httpServer.running){
				sstatus.textContent = navigator.mozL10n.get('running');
			} else {
				sstatus.textContent = navigator.mozL10n.get('stopped');
			}

			start_b.addEventListener('click', function() {
				console.log('Clicked on start');
			  	httpServer.start();
				sstatus.textContent = navigator.mozL10n.get('running');
			});

			stop_b.addEventListener('click', function() {
				console.log('Clicked on stop');
			  	httpServer.stop();
				sstatus.textContent = navigator.mozL10n.get('stopped');
			});

		});
	} else if (requested_page == "settings"){
		$("#main-container").load("../content/settings_content.html", function() {
			console.log('Loading of the HTML performed');
			update_loc();
			$('select').material_select();

			$("#select-language").change(function() {
				var l = $("#select-language").val();
				console.log('New selected language: ' + l);
				navigator.mozL10n.language.code = l;
			});
		});
	} else {
		$("#main-container").load("../content/index_content.html", function() {
			console.log('Loading of the HTML performed');
			update_loc();

			last_sms_id = -1;

			$('#sms-submit').on("click", function (ev){
				console.log("Submitting SMS form...");

				var resp = document.getElementById('response');
				if (resp == null) {
					$("#main-container").append('

');
				}
				$("#response").html(navigator.mozL10n.get('submitting_sms') + '...');

				var msg = document.getElementById('message').value;
				var phone = document.getElementById('contacts').value;
				console.log('Submitted message : ' + msg + ' Phone nb: ' + phone);

				var request;
				request = navigator.mozMobileMessage.send(phone, msg);

				request.onsuccess = function (){
					window.thing = this;
					console.log(this.result);
					console.log("Sent to: " + this.result);
					last_sms_id = this.result['id'];
					logMsg(this.result);
					$("#response").html('' + navigator.mozL10n.get('successfully_sent') + ' ✓
');

					/* check if the last sms was well delivered (receipt) */
					var checking_last_sms = window.setInterval(function(){
						if (last_sms_id != -1){
							var request = navigator.mozMobileMessage.getMessage(last_sms_id);
							request.onsuccess = function (){
								window.thing = this;
								console.error(this.result);

								if (this.result['deliveryStatus'] == 'success'){
									clearInterval(checking_last_sms);
									$("#response").append('' + navigator.mozL10n.get('successfully_received') + ' ✓');
								}

								logMsg(this.result);
							}

							request.onerror = function (){
								$("#response").html('Couldn\'t retrieve last sent SMS...');
								clearInterval(checking_last_sms);
							}
						}
					}, 5000);
				};

				request.onerror = function (){
					window.thing = this;
					console.error(this.error.name);
					console.error(this.error.message);
					$("#response").html('' + navigator.mozL10n.get('error_sending_message') + ' ✗');
					$("#response").append('' + this.error.name + ':' + this.error.message + '');
				};
			});

			var allContacts = navigator.mozContacts.getAll();

			allContacts.onsuccess = function(event) {
				var cursor = event.target;
				var gn, fn, tl;
				if (cursor.result) {
					gn = (cursor.result.givenName == null) ? "" : cursor.result.givenName[0]
					fn = (cursor.result.familyName == null) ? "" : cursor.result.familyName[0]
					tl = (cursor.result.tel == null) ? "" : cursor.result.tel[0].value
					console.log('Found one contact... Given name : ' + gn + ', Family name : ' + fn + ', Tel : ' + tl);

					// Append new contact to the select
					$('#contacts').append('<option value="' + tl + '">' + gn + ' ' + fn + '</option>');

					// Go to the next contact
					cursor.continue();
				} else {
					console.log("No more contacts, creating the Materialize select...");
					// Once the contacts are all retrieved, we create the Materialize select
					$('select').material_select();
				}
			};

			allContacts.onerror = function() {
				console.warn("Something went terribly wrong while retrieving the contacts!");
			};
		});
	}
}

// DOMContentLoaded is fired once the document has been loaded and parsed,
// but without waiting for other external resources to load (css/images/etc)
// That makes the app more responsive and perceived as faster.
// https://developer.mozilla.org/Web/Reference/Events/DOMContentLoaded
window.addEventListener('DOMContentLoaded', function() {

	// We'll ask the browser to use strict code to help us catch errors earlier.
	// https://developer.mozilla.org/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
	'use strict';

	httpServer.addEventListener('request', function(evt) {
		var request  = evt.request;
		var response = evt.response;

		console.log(request);

		if (request.path === 'image.jpg') {
		    response.headers['Content-Type'] = 'image/png';
		    response.sendFile('../img/icons/fox128x128.png');
		    return;
		}

		var paramsString = JSON.stringify(request.params, null, 2);
		var bodyString   = JSON.stringify(request.body, null, 2);

		var firstName = (request.body && request.body.first_name) || '';
		var lastName  = (request.body && request.body.last_name)  || '';

		var body = '<!DOCTYPE html><title>Firefox OS Web Server</title>
Hello World!

If you can read this, the Firefox OS Web Server is operational!

The path you requested is: ' + request.path + '

URL Parameters:

' + paramsString + '

POST Data:

' + bodyString + '

Sample Form
<form method="POST" action=".">
First Name:<input type="text" name="first_name" value="' + firstName + '">

Last Name:<input type="text" name="last_name" value="' + lastName + '">
<input type="submit" value="Submit"></form>
To see something really scary, click here :-)
';

		response.send(body);
	});

	// Loading the side nav
	var e = document.getElementById('nav-slide');
	if (e != null){
		console.log('Successfully retrieved nav-slide');
		$("#nav-slide").load("../slide.html", function() {
			$('.button-collapse').sideNav({
				menuWidth: 200, // Default is 240
				edge: 'left', // Choose the horizontal origin
				closeOnClick: true // Closes side-nav on  clicks, useful for Angular/Meteor
			});

			$('#home').on("click", function(ev){
				console.log("Clicked home");
				load_page("home");
			});
			$('#objects').on("click", function(ev){
				console.log("Clicked objects");
				//load_page("objects");
			});
			$('#server').on("click", function(ev){
				console.log("Clicked server");
				load_page("server");
			});
			$('#settings').on("click", function(ev){
				console.log("Clicked settings");
				load_page("settings");
			});
			$('#about').on("click", function(ev){
				console.log("Clicked about");
				load_page("about");
			});

			load_page("home");

		});
	} else {
		console.log('Error while retrieving nav-slide');
	}

	// We want to wait until the localisations library has loaded all the strings.
	// So we'll tell it to let us know once it's ready.
	navigator.mozL10n.once(start);

	function start() {
		// var message = document.getElementById('message');
		// message.textContent = translate('message');
		$('select').material_select();
	}

});

window.addEventListener('beforeunload', function() {
	httpServer.stop();
});

<commit_msg>Testing button launching browser (about to be test)<commit_after>var last_sms_id = -1;
var httpServer = new HTTPServer(8080);

// Logging the result from messages
function logMsg(msg){
	var r = "";
	['type', 'id', 'threadId', 'body', 'delivery', 'deliveryStatus', 'read', 'receiver', 'sender', 'timestamp', 'messageClass'].forEach(function (key){
		r += '
 ' + key + ': ' + msg[key];
	});
	console.log(r);
}

// Not very beautiful, but for now, it is OK
function update_loc(){
	$('[data-l10n-id]').each(function(index){
		$(this).html(navigator.mozL10n.get($(this).attr('data-l10n-id')));
	});
}

function load_page(requested_page){
	console.log('Loading page ' + requested_page);
	if (requested_page == "about"){
		$("#main-container").load("../content/about_content.html", function() {
			console.log('Loading of the HTML performed');
			update_loc();
		});
	} else if (requested_page == "server"){
		$("#main-container").load("../content/server_content.html", function() {
			console.log('Loading of the HTML performed');
			update_loc();

			var sstatus = document.getElementById('server-status');
			var ip     = document.getElementById('ip-address');
			var port   = document.getElementById('listening-port');
			var start_b  = document.getElementById('start-server');
			var stop_b   = document.getElementById('stop-server');

			IPUtils.getAddresses(function(ipAddress) {
				ip.textContent = ip.textContent || ipAddress;
			});

			port.textContent = httpServer.port;

			// may be to modify, when the server is correctly running
			if (httpServer.running){
				sstatus.textContent = navigator.mozL10n.get('running');
			} else {
				sstatus.textContent = navigator.mozL10n.get('stopped');
			}

			start_b.addEventListener('click', function() {
				console.log('Clicked on start');
			  	httpServer.start();
				sstatus.textContent = navigator.mozL10n.get('running');
			});

			stop_b.addEventListener('click', function() {
				console.log('Clicked on stop');
			  	httpServer.stop();
				sstatus.textContent = navigator.mozL10n.get('stopped');
			});

			$('#testing-server').on('click', function(){
				console.log('Clicked on testing');
				window.location.href = 'http://' + ip.textContent + ':' + port.textContent;
			});
		});
	} else if (requested_page == "settings"){
		$("#main-container").load("../content/settings_content.html", function() {
			console.log('Loading of the HTML performed');
			update_loc();
			$('select').material_select();

			$("#select-language").change(function() {
				var l = $("#select-language").val();
				console.log('New selected language: ' + l);
				navigator.mozL10n.language.code = l;
			});
		});
	} else {
		$("#main-container").load("../content/index_content.html", function() {
			console.log('Loading of the HTML performed');
			update_loc();

			last_sms_id = -1;

			$('#sms-submit').on("click", function (ev){
				console.log("Submitting SMS form...");

				var resp = document.getElementById('response');
				if (resp == null) {
					$("#main-container").append('

');
				}
				$("#response").html(navigator.mozL10n.get('submitting_sms') + '...');

				var msg = document.getElementById('message').value;
				var phone = document.getElementById('contacts').value;
				console.log('Submitted message : ' + msg + ' Phone nb: ' + phone);

				var request;
				request = navigator.mozMobileMessage.send(phone, msg);

				request.onsuccess = function (){
					window.thing = this;
					console.log(this.result);
					console.log("Sent to: " + this.result);
					last_sms_id = this.result['id'];
					logMsg(this.result);
					$("#response").html('' + navigator.mozL10n.get('successfully_sent') + ' ✓
');

					/* check if the last sms was well delivered (receipt) */
					var checking_last_sms = window.setInterval(function(){
						if (last_sms_id != -1){
							var request = navigator.mozMobileMessage.getMessage(last_sms_id);
							request.onsuccess = function (){
								window.thing = this;
								console.error(this.result);

								if (this.result['deliveryStatus'] == 'success'){
									clearInterval(checking_last_sms);
									$("#response").append('' + navigator.mozL10n.get('successfully_received') + ' ✓');
								}

								logMsg(this.result);
							}

							request.onerror = function (){
								$("#response").html('Couldn\'t retrieve last sent SMS...');
								clearInterval(checking_last_sms);
							}
						}
					}, 5000);
				};

				request.onerror = function (){
					window.thing = this;
					console.error(this.error.name);
					console.error(this.error.message);
					$("#response").html('' + navigator.mozL10n.get('error_sending_message') + ' ✗');
					$("#response").append('' + this.error.name + ':' + this.error.message + '');
				};
			});

			var allContacts = navigator.mozContacts.getAll();

			allContacts.onsuccess = function(event) {
				var cursor = event.target;
				var gn, fn, tl;
				if (cursor.result) {
					gn = (cursor.result.givenName == null) ? "" : cursor.result.givenName[0]
					fn = (cursor.result.familyName == null) ? "" : cursor.result.familyName[0]
					tl = (cursor.result.tel == null) ? "" : cursor.result.tel[0].value
					console.log('Found one contact... Given name : ' + gn + ', Family name : ' + fn + ', Tel : ' + tl);

					// Append new contact to the select
					$('#contacts').append('<option value="' + tl + '">' + gn + ' ' + fn + '</option>');

					// Go to the next contact
					cursor.continue();
				} else {
					console.log("No more contacts, creating the Materialize select...");
					// Once the contacts are all retrieved, we create the Materialize select
					$('select').material_select();
				}
			};

			allContacts.onerror = function() {
				console.warn("Something went terribly wrong while retrieving the contacts!");
			};
		});
	}
}

// DOMContentLoaded is fired once the document has been loaded and parsed,
// but without waiting for other external resources to load (css/images/etc)
// That makes the app more responsive and perceived as faster.
// https://developer.mozilla.org/Web/Reference/Events/DOMContentLoaded
window.addEventListener('DOMContentLoaded', function() {

	// We'll ask the browser to use strict code to help us catch errors earlier.
	// https://developer.mozilla.org/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode
	'use strict';

	httpServer.addEventListener('request', function(evt) {
		var request  = evt.request;
		var response = evt.response;

		console.log(request);

		if (request.path === 'image.jpg') {
		    response.headers['Content-Type'] = 'image/png';
		    response.sendFile('../img/icons/fox128x128.png');
		    return;
		}

		var paramsString = JSON.stringify(request.params, null, 2);
		var bodyString   = JSON.stringify(request.body, null, 2);

		var firstName = (request.body && request.body.first_name) || '';
		var lastName  = (request.body && request.body.last_name)  || '';

		var body = '<!DOCTYPE html><title>Firefox OS Web Server</title>
Hello World!

If you can read this, the Firefox OS Web Server is operational!

The path you requested is: ' + request.path + '

URL Parameters:

' + paramsString + '

POST Data:

' + bodyString + '

Sample Form
<form method="POST" action=".">
First Name:<input type="text" name="first_name" value="' + firstName + '">

Last Name:<input type="text" name="last_name" value="' + lastName + '">
<input type="submit" value="Submit"></form>
To see something really scary, click here :-)
';

		response.send(body);
	});

	// Loading the side nav
	var e = document.getElementById('nav-slide');
	if (e != null){
		console.log('Successfully retrieved nav-slide');
		$("#nav-slide").load("../slide.html", function() {
			$('.button-collapse').sideNav({
				menuWidth: 200, // Default is 240
				edge: 'left', // Choose the horizontal origin
				closeOnClick: true // Closes side-nav on  clicks, useful for Angular/Meteor
			});

			$('#home').on("click", function(ev){
				console.log("Clicked home");
				load_page("home");
			});
			$('#objects').on("click", function(ev){
				console.log("Clicked objects");
				//load_page("objects");
			});
			$('#server').on("click", function(ev){
				console.log("Clicked server");
				load_page("server");
			});
			$('#settings').on("click", function(ev){
				console.log("Clicked settings");
				load_page("settings");
			});
			$('#about').on("click", function(ev){
				console.log("Clicked about");
				load_page("about");
			});

			load_page("home");

		});
	} else {
		console.log('Error while retrieving nav-slide');
	}

	// We want to wait until the localisations library has loaded all the strings.
	// So we'll tell it to let us know once it's ready.
	navigator.mozL10n.once(start);

	function start() {
		// var message = document.getElementById('message');
		// message.textContent = translate('message');
		$('select').material_select();
	}

});

window.addEventListener('beforeunload', function() {
	httpServer.stop();
});

<|endoftext|>


<commit_before>var defaultPointSize = 0.09;
var defaultLOD = 12;
//var pointcloudPath = "Potree_Cleaned_rit1_take2/cloud.js";
var pointcloudPath = "bower_components/potree/resources/pointclouds/lion_takanawa/cloud_laz.js";

var pointcloud;
var skybox;
var stats;
var clock = new THREE.Clock();
var materials = {};

var renderer;
var camera;
var scene;
var mouse = {
	x : 1,
	y : 1
};
var projector, raycaster;
var spStart, spEnd, sConnection;
var placeStartMode = false;
var placeEndMode = false;
var cube, cameraCube, sceneCube;

var firstperson;

var useOculus = false;
function getFov() {
	if (useOculus) {
		return 110;
	} else {
		return 75;
	}
}

function loadSkybox() {
	cameraCube = new THREE.PerspectiveCamera(getFov(), window.innerWidth / window.innerHeight, 1, 100000);
	sceneCube = new THREE.Scene();

	var path = "bower_components/potree/resources/textures/skybox/";
	var format = ".jpg";
	var urls = [ path + 'px' + format, path + 'nx' + format, path + 'py' + format, path + 'ny' + format, path + 'pz' + format, path + 'nz' + format ];

	var textureCube = THREE.ImageUtils.loadTextureCube(urls, new THREE.CubeRefractionMapping());
	var material = new THREE.MeshBasicMaterial({
		color : 0xffffff,
		envMap : textureCube,
		refractionRatio : 0.95
	});

	var shader = THREE.ShaderLib["cube"];
	shader.uniforms["tCube"].value = textureCube;

	var material = new THREE.ShaderMaterial({

		fragmentShader : shader.fragmentShader,
		vertexShader : shader.vertexShader,
		uniforms : shader.uniforms,
		depthWrite : false,
		side : THREE.BackSide

	}),

	mesh = new THREE.Mesh(new THREE.BoxGeometry(10000, 10000, 10000), material);
	sceneCube.add(mesh);
}

function initGUI() {
	var gui = new dat.GUI({
		height : 5 * 32 - 1
	});

	var params = {
		PointSize : defaultPointSize,
		LOD : defaultLOD
	};

	var pLOD = gui.add(params, 'LOD', 0.5, 20);
	pLOD.onChange(function(value) {
		pointcloud.LOD = value;
	});

	var pPointSize = gui.add(params, 'PointSize', 0.01, 0.1);
	pPointSize.onChange(function(value) {
		pointcloudMaterial.size = value;
	});
}

function initThree() {
	scene = new THREE.Scene();
	camera = new THREE.PerspectiveCamera(getFov(), window.innerWidth / window.innerHeight, 0.001, 100000);

	projector = new THREE.Projector();
	raycaster = new THREE.Raycaster();

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

	//OculusRift
	effect = new THREE.OculusRiftEffect( renderer, {worldScale: 100} );
	effect.setSize( window.innerWidth, window.innerHeight );

	loadSkybox();
	scene.add(sceneCube);

	// pointcloud
	pointcloudMaterial = new THREE.PointCloudMaterial({
		size : defaultPointSize,
		vertexColors : true
	});

	// materials
	materials.rgb = new Potree.PointCloudRGBMaterial({ size: defaultPointSize});
	materials.color = new Potree.PointCloudColorMaterial({size: defaultPointSize});
	materials.height = new Potree.PointCloudHeightMaterial({size: defaultPointSize, min: 0, max: 10});
	materials.intensity = new Potree.PointCloudIntensityMaterial({size: defaultPointSize, min: 0, max: 65535});

	// load pointcloud
	var pco = POCLoader.load(pointcloudPath, {toOrigin: true});

	pointcloud = new Potree.PointCloudOctree(pco, materials.rgb);
	pointcloud.LOD = defaultLOD;
	pointcloud.rotation.set(-Math.PI/2.0, 0.0, 0.0);
	pointcloud.moveToOrigin();
	pointcloud.moveToGroundPlane();

	scene.add(pointcloud);

	// grid
	scene.add(createGrid(8, 8, 1));

	// measurement
	var sphereGeometry = new THREE.SphereGeometry(0.05, 32, 32);
	var sphereMaterial = new THREE.MeshBasicMaterial({
		color : 0xbb0000,
		shading : THREE.FlatShading
	});
	spStart = new THREE.Mesh(sphereGeometry, sphereMaterial);
	spEnd = new THREE.Mesh(sphereGeometry, sphereMaterial);
	// spStart.position.set(-1.1,1.05,2);
	// spEnd.position.set(1.3,1.0,1.15);
	spStart.position.set(-2.2, 1.9, 1.66);
	spEnd.position.set(0.02, 2, 2.64);
	scene.add(spStart);
	scene.add(spEnd);

	var lc = new THREE.Color(0xff0000);
	var lineGeometry = new THREE.Geometry();
	lineGeometry.vertices.push(spStart.position.clone(), spEnd.position.clone());
	lineGeometry.colors.push(lc, lc, lc);
	var lineMaterial = new THREE.LineBasicMaterial({
		vertexColors : THREE.VertexColors
	});
	sConnection = new THREE.Line(lineGeometry, lineMaterial);
	scene.add(sConnection);

	// controls
	camera.position.set(4, 6, 10);
	controls = new THREE.OrbitControls(camera, renderer.domElement);
	controls.target.set(0, 3, 0);
	camera.lookAt(controls.target);

	firstperson = new OculusFirstPersonControls(camera);

	window.addEventListener('resize', onResize, false);

	document.addEventListener('mousemove', onDocumentMouseMove, false);
	renderer.domElement.addEventListener('click', onClick, false);
}

function createGrid(width, length, spacing) {
	var material = new THREE.LineBasicMaterial({
		color : 0xBBBBBB
	});

	var geometry = new THREE.Geometry();
	for (var i = 0; i <= length; i++) {
		geometry.vertices.push(new THREE.Vector3(-(spacing * width) / 2, 0, i * spacing - (spacing * length) / 2));
		geometry.vertices.push(new THREE.Vector3(+(spacing * width) / 2, 0, i * spacing - (spacing * length) / 2));
	}

	for (var i = 0; i <= width; i++) {
		geometry.vertices.push(new THREE.Vector3(i * spacing - (spacing * width) / 2, 0, -(spacing * length) / 2));
		geometry.vertices.push(new THREE.Vector3(i * spacing - (spacing * width) / 2, 0, +(spacing * length) / 2));
	}

	var line = new THREE.Line(geometry, material, THREE.LinePieces);
	line.receiveShadow = true;
	return line;
}

function onResize() {
	  if(!useOculus){
	    windowHalf = new THREE.Vector2(window.innerWidth / 2, window.innerHeight / 2);
	    aspectRatio = window.innerWidth / window.innerHeight;

	    camera.aspect = aspectRatio;
	    camera.updateProjectionMatrix();

	    renderer.setSize(window.innerWidth, window.innerHeight);
	  } else {
	    effect.setSize(window.innerWidth, window.innerHeight);
	  }
	}

function onDocumentMouseMove(event) {
	event.preventDefault();

	mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
	mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}

function render() {
	requestAnimationFrame(render);

	pointcloud.update(camera);

	if (useOculus) firstperson.updateInput();

	//camera.updateMatrixWorld(true);

	vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
	projector.unprojectVector(vector, camera);
	raycaster.params = {
		"PointCloud" : {
			threshold : 0.1
		}
	};
	raycaster.ray.set(camera.position, vector.sub(camera.position).normalize());

	scene.traverse(function(object) {
		if (object instanceof Potree.PointCloudOctree) {
			object.update(camera);
		}
	});

	if (placeStartMode || placeEndMode) {
		var intersects = raycaster.intersectObject(pointcloud, true);

		if (intersects.length > 0) {
			var I = intersects[0];

			if (placeStartMode) {
				spStart.position.copy(I.point);
			} else if (placeEndMode) {
				spEnd.position.copy(I.point);
			}

			sConnection.geometry.vertices[0].copy(spStart.position);
			sConnection.geometry.vertices[1].copy(spEnd.position);
			sConnection.geometry.verticesNeedUpdate = true;
			sConnection.geometry.computeBoundingSphere();
		}
	}

	// placing distance label
	var labelPos = spStart.position.clone().add(spEnd.position).multiplyScalar(0.5);
	projector.projectVector(labelPos, camera);
	labelPos.x = (labelPos.x + 1) / 2 * window.innerWidth;
	labelPos.y = -(labelPos.y - 1) / 2 * window.innerHeight;

	var distance = spStart.position.distanceTo(spEnd.position);
	var lblDistance = document.getElementById("lblDistance");
	lblDistance.style.left = labelPos.x;
	lblDistance.style.top = labelPos.y;
	lblDistance.innerHTML = distance.toFixed(2);

	var numVisibleNodes = pointcloud.numVisibleNodes;
	var numVisiblePoints = pointcloud.numVisiblePoints;
	document.getElementById("lblNumVisibleNodes").innerHTML = "visible nodes: " + numVisibleNodes;
	document.getElementById("lblNumVisiblePoints").innerHTML = "visible points: " + Potree.utils.addCommas(numVisiblePoints);
	document.getElementById("lblPosition").innerHTML = "position of start: " + Potree.utils.addCommas(spStart.position.x)+ "/" + Potree.utils.addCommas(spStart.position.y)+"/" + Potree.utils.addCommas(spStart.position.z);

	if (!useOculus) {
	  //Non-Oculus rendering
	  renderer.render(scene, camera);
	} else {
      //Rendering through the Oculus effect
	  effect.render( scene, camera);
    }
};

initThree();
initGUI();
render();

function placeStart() {
	placeStartMode = true;
	placeEndMode = false;
}

function placeEnd() {
	placeStartMode = false;
	placeEndMode = true;
}

function onClick() {
	placeStartMode = false;
	placeEndMode = false;

	console.log(spStart.position);
	console.log(spEnd.position);
}

function toggleOculus() {
  useOculus = !useOculus;
  onResize();

  if (!useOculus) {
    camera.fov = 75;
	camera.updateProjectionMatrix();
	firstperson.disable();

	camera.position.set(4, 6, 10);
	controls.target.set(0, 3, 0);
	controls.update();
	camera.lookAt(controls.target);

  } else {
	camera.fov = 110;
	camera.updateProjectionMatrix();
	firstperson.enable();

  }

}<commit_msg>camera position<commit_after>var defaultPointSize = 0.09;
var defaultLOD = 12;
//var pointcloudPath = "Potree_Cleaned_rit1_take2/cloud.js";
//var pointcloudPath = "bower_components/potree/resources/pointclouds/lion_takanawa/cloud_laz.js";
var pointcloudPath = "converted_data/out_8/cloud.js";

var pointcloud;
var skybox;
var stats;
var clock = new THREE.Clock();
var materials = {};

var renderer;
var camera;
var scene;
var mouse = {
	x : 1,
	y : 1
};
var projector, raycaster;
var spStart, spEnd, sConnection;
var placeStartMode = false;
var placeEndMode = false;
var cube, cameraCube, sceneCube;

var firstperson;

var useOculus = false;
function getFov() {
	if (useOculus) {
		return 110;
	} else {
		return 75;
	}
}

function loadSkybox() {
	cameraCube = new THREE.PerspectiveCamera(getFov(), window.innerWidth / window.innerHeight, 1, 100000);
	sceneCube = new THREE.Scene();

	var path = "bower_components/potree/resources/textures/skybox/";
	var format = ".jpg";
	var urls = [ path + 'px' + format, path + 'nx' + format, path + 'py' + format, path + 'ny' + format, path + 'pz' + format, path + 'nz' + format ];

	var textureCube = THREE.ImageUtils.loadTextureCube(urls, new THREE.CubeRefractionMapping());
	var material = new THREE.MeshBasicMaterial({
		color : 0xffffff,
		envMap : textureCube,
		refractionRatio : 0.95
	});

	var shader = THREE.ShaderLib["cube"];
	shader.uniforms["tCube"].value = textureCube;

	var material = new THREE.ShaderMaterial({

		fragmentShader : shader.fragmentShader,
		vertexShader : shader.vertexShader,
		uniforms : shader.uniforms,
		depthWrite : false,
		side : THREE.BackSide

	}),

	mesh = new THREE.Mesh(new THREE.BoxGeometry(10000, 10000, 10000), material);
	sceneCube.add(mesh);
}

function initGUI() {
	var gui = new dat.GUI({
		height : 5 * 32 - 1
	});

	var params = {
		PointSize : defaultPointSize,
		LOD : defaultLOD
	};

	var pLOD = gui.add(params, 'LOD', 0.5, 20);
	pLOD.onChange(function(value) {
		pointcloud.LOD = value;
	});

	var pPointSize = gui.add(params, 'PointSize', 0.01, 0.1);
	pPointSize.onChange(function(value) {
		pointcloudMaterial.size = value;
	});
}

function initThree() {
	scene = new THREE.Scene();
	camera = new THREE.PerspectiveCamera(getFov(), window.innerWidth / window.innerHeight, 0.001, 100000);

	projector = new THREE.Projector();
	raycaster = new THREE.Raycaster();

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

	//OculusRift
	effect = new THREE.OculusRiftEffect( renderer, {worldScale: 100} );
	effect.setSize( window.innerWidth, window.innerHeight );

	loadSkybox();
	scene.add(sceneCube);

	// pointcloud
	pointcloudMaterial = new THREE.PointCloudMaterial({
		size : defaultPointSize,
		vertexColors : true
	});

	// materials
	materials.rgb = new Potree.PointCloudRGBMaterial({ size: defaultPointSize});
	materials.color = new Potree.PointCloudColorMaterial({size: defaultPointSize});
	materials.height = new Potree.PointCloudHeightMaterial({size: defaultPointSize, min: 0, max: 10});
	materials.intensity = new Potree.PointCloudIntensityMaterial({size: defaultPointSize, min: 0, max: 65535});

	// load pointcloud
	var pco = POCLoader.load(pointcloudPath, {toOrigin: true});

	pointcloud = new Potree.PointCloudOctree(pco, materials.rgb);
	pointcloud.LOD = defaultLOD;
	pointcloud.rotation.set(-Math.PI/2.0, 0.0, 0.0);
	pointcloud.moveToOrigin();
	pointcloud.moveToGroundPlane();

	scene.add(pointcloud);

	// grid
	scene.add(createGrid(8, 8, 1));

	// measurement
	var sphereGeometry = new THREE.SphereGeometry(0.05, 32, 32);
	var sphereMaterial = new THREE.MeshBasicMaterial({
		color : 0xbb0000,
		shading : THREE.FlatShading
	});
	spStart = new THREE.Mesh(sphereGeometry, sphereMaterial);
	spEnd = new THREE.Mesh(sphereGeometry, sphereMaterial);
	// spStart.position.set(-1.1,1.05,2);
	// spEnd.position.set(1.3,1.0,1.15);
	spStart.position.set(-2.2, 1.9, 1.66);
	spEnd.position.set(0.02, 2, 2.64);
	scene.add(spStart);
	scene.add(spEnd);

	var lc = new THREE.Color(0xff0000);
	var lineGeometry = new THREE.Geometry();
	lineGeometry.vertices.push(spStart.position.clone(), spEnd.position.clone());
	lineGeometry.colors.push(lc, lc, lc);
	var lineMaterial = new THREE.LineBasicMaterial({
		vertexColors : THREE.VertexColors
	});
	sConnection = new THREE.Line(lineGeometry, lineMaterial);
	scene.add(sConnection);

	// controls
	camera.position.set(-818, 12, -960);
	controls = new THREE.OrbitControls(camera, renderer.domElement);
	controls.target.set(-818, 12, -948);
	camera.lookAt(controls.target);

	firstperson = new OculusFirstPersonControls(camera);

	window.addEventListener('resize', onResize, false);

	document.addEventListener('mousemove', onDocumentMouseMove, false);
	renderer.domElement.addEventListener('click', onClick, false);
}

function createGrid(width, length, spacing) {
	var material = new THREE.LineBasicMaterial({
		color : 0xBBBBBB
	});

	var geometry = new THREE.Geometry();
	for (var i = 0; i <= length; i++) {
		geometry.vertices.push(new THREE.Vector3(-(spacing * width) / 2, 0, i * spacing - (spacing * length) / 2));
		geometry.vertices.push(new THREE.Vector3(+(spacing * width) / 2, 0, i * spacing - (spacing * length) / 2));
	}

	for (var i = 0; i <= width; i++) {
		geometry.vertices.push(new THREE.Vector3(i * spacing - (spacing * width) / 2, 0, -(spacing * length) / 2));
		geometry.vertices.push(new THREE.Vector3(i * spacing - (spacing * width) / 2, 0, +(spacing * length) / 2));
	}

	var line = new THREE.Line(geometry, material, THREE.LinePieces);
	line.receiveShadow = true;
	return line;
}

function onResize() {
	  if(!useOculus){
	    windowHalf = new THREE.Vector2(window.innerWidth / 2, window.innerHeight / 2);
	    aspectRatio = window.innerWidth / window.innerHeight;

	    camera.aspect = aspectRatio;
	    camera.updateProjectionMatrix();

	    renderer.setSize(window.innerWidth, window.innerHeight);
	  } else {
	    effect.setSize(window.innerWidth, window.innerHeight);
	  }
	}

function onDocumentMouseMove(event) {
	event.preventDefault();

	mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
	mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}

function render() {
	requestAnimationFrame(render);

	pointcloud.update(camera);

	if (useOculus) firstperson.updateInput();

	//camera.updateMatrixWorld(true);

	vector = new THREE.Vector3(mouse.x, mouse.y, 0.5);
	projector.unprojectVector(vector, camera);
	raycaster.params = {
		"PointCloud" : {
			threshold : 0.1
		}
	};
	raycaster.ray.set(camera.position, vector.sub(camera.position).normalize());

	scene.traverse(function(object) {
		if (object instanceof Potree.PointCloudOctree) {
			object.update(camera);
		}
	});

	if (placeStartMode || placeEndMode) {
		var intersects = raycaster.intersectObject(pointcloud, true);

		if (intersects.length > 0) {
			var I = intersects[0];

			if (placeStartMode) {
				spStart.position.copy(I.point);
			} else if (placeEndMode) {
				spEnd.position.copy(I.point);
			}

			sConnection.geometry.vertices[0].copy(spStart.position);
			sConnection.geometry.vertices[1].copy(spEnd.position);
			sConnection.geometry.verticesNeedUpdate = true;
			sConnection.geometry.computeBoundingSphere();
		}
	}

	// placing distance label
	var labelPos = spStart.position.clone().add(spEnd.position).multiplyScalar(0.5);
	projector.projectVector(labelPos, camera);
	labelPos.x = (labelPos.x + 1) / 2 * window.innerWidth;
	labelPos.y = -(labelPos.y - 1) / 2 * window.innerHeight;

	var distance = spStart.position.distanceTo(spEnd.position);
	var lblDistance = document.getElementById("lblDistance");
	lblDistance.style.left = labelPos.x;
	lblDistance.style.top = labelPos.y;
	lblDistance.innerHTML = distance.toFixed(2);

	var numVisibleNodes = pointcloud.numVisibleNodes;
	var numVisiblePoints = pointcloud.numVisiblePoints;
	document.getElementById("lblNumVisibleNodes").innerHTML = "visible nodes: " + numVisibleNodes;
	document.getElementById("lblNumVisiblePoints").innerHTML = "visible points: " + Potree.utils.addCommas(numVisiblePoints);
	document.getElementById("lblPosition").innerHTML = "position of start: " + Potree.utils.addCommas(spStart.position.x)+ "/" + Potree.utils.addCommas(spStart.position.y)+"/" + Potree.utils.addCommas(spStart.position.z);

	if (!useOculus) {
	  //Non-Oculus rendering
	  renderer.render(scene, camera);
	} else {
      //Rendering through the Oculus effect
	  effect.render( scene, camera);
    }
};

initThree();
initGUI();
render();

function placeStart() {
	placeStartMode = true;
	placeEndMode = false;
}

function placeEnd() {
	placeStartMode = false;
	placeEndMode = true;
}

function onClick() {
	placeStartMode = false;
	placeEndMode = false;

	//console.log(spStart.position);
	//console.log(spEnd.position);
}

function toggleOculus() {
  useOculus = !useOculus;
  onResize();

  if (!useOculus) {
    camera.fov = 75;
	camera.updateProjectionMatrix();
	firstperson.disable();

	camera.position.set(4, 6, 10);
	controls.target.set(0, 3, 0);
	controls.update();
	camera.lookAt(controls.target);

  } else {
	camera.fov = 110;
	camera.updateProjectionMatrix();
	firstperson.enable();

  }

}<|endoftext|>