<commit_before>/// <reference path="../Services/IdentityService.js" />
/// <reference path="../Services/PollService.js" />
/// <reference path="../Services/VoteService.js" />
(function () {
    angular
        .module('GVA.Voting')
        .controller('ResultsPageController', ResultsPageController);

    ResultsPageController.$inject = ['$scope', '$routeParams', 'IdentityService', 'VoteService', 'RoutingService'];

    function ResultsPageController($scope, $routeParams, IdentityService, VoteService, RoutingService) {

        var pollId = $routeParams.pollId;
        var tokenId = $routeParams['tokenId'] || '';
        var chart;

        // Turn "/#/results/abc/123" into "/#/voting/abc/123"
        $scope.votingLink = RoutingService.getVotePageUrl(pollId, tokenId);

        $scope.winner = 'Lorem';
        //Whether or not we have an "s" on the end of "Winner"
        $scope.plural = '';

        $scope.voteCount = 0;

        var canvas = document.createElement('canvas');

        var textWidth = function (text) {
            var context = canvas.getContext('2d');
            context.font = '16px Open Sans';
            var metrics = context.measureText(text);
            return metrics.width;
        };

        var drawD3Chart = function (data) {
            // Hack to fix lack of data reloading
            document.getElementById('results-chart').innerHTML = '';

            data = data.sort(function (a, b) { return b.Sum - a.Sum; });

            var chartHeight = Math.min(data.length * 50 + 100, 600);
            var chartWidth = Math.min(600, document.getElementById('results-chart').offsetWidth);

            var longestTextWidth = d3.max(data, function (d) { return textWidth(d.Name); });

            var margin = { top: 30, right: 10, bottom: 10, left: longestTextWidth + 10 };
            var width = chartWidth - margin.left - margin.right;
            var height = chartHeight - margin.top - margin.bottom;

            var minX = d3.min(data, function (d) { return d.Sum; });
            var maxX = d3.max(data, function (d) { return d.Sum; });

            var x = d3.scale.linear()
                .range([0, width])
                .domain([Math.min(0, minX), maxX]).nice();

            var dataRange = x.domain()[1] - x.domain()[0];
            var tickFrequency = Math.max((Math.pow(10, (Math.round(Math.log(dataRange) / Math.log(10)) - 1))), 1);

            var y = d3.scale.ordinal()
                .rangeRoundBands([0, height], 0.2)
                .domain(data.map(function (d) { return d.Name; }));

            var xAxis = d3.svg.axis()
                .scale(x)
                .orient('top')
                .ticks(dataRange / tickFrequency); // Ticks is *how many* ticks we display, not the frequency...

            var yAxis = d3.svg.axis()
                .scale(y)
                .orient('left');

            var chart = d3.select('#results-chart')
                .append('svg')
                    .attr('width', chartWidth)
                    .attr('height', chartHeight)
                .append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

            chart.append('g')
                .attr('class', 'x axis')
                .call(xAxis);

            chart.append('g')
                .attr('class', 'y axis')
                .call(yAxis)
                .append('line')
                .attr('x1', x(0))
                .attr('x2', x(0))
                .attr('y2', height);

            chart.selectAll('.bar')
                .data(data)
                .enter().append('rect')
                .attr('class', function (d) { return d.Sum < 0 ? 'bar negative' : 'bar positive'; })
                .attr('x', function (d) {
                    return x(Math.min(0, d.Sum));
                })
                .attr('y', function (d) {
                    return y(d.Name);
                })
                .attr('width', function (d) {
                    return Math.abs(x(-d.Sum) - x(0));
                })
                .attr('height', 50);
        };

        var reloadData = function () {
            VoteService.getResults(pollId, getResultsSuccessCallback);
        };

        function getResultsSuccessCallback(data, status) {

            if (data) {
                $scope.voteCount = data.length;
            }

            var groupedData = {};

            // Group together votes for the same options
            data.forEach(function (d) {
                if (!(d.OptionName in groupedData)) {
                    groupedData[d.OptionName] = { Value: 0, Voters: [] };
                }

                groupedData[d.OptionName].Value += d.VoteValue;
                groupedData[d.OptionName].Voters.push(d.VoterName);

            });

            var winningScore = 0;

            var datapoints = [];

            // Separate into datapoints
            for (var key in groupedData) {
                if (groupedData.hasOwnProperty(key)) {
                    datapoints.push({ Name: key, Sum: groupedData[key].Value, Voters: groupedData[key].Voters });
                    winningScore = Math.max(winningScore, groupedData[key].Value);
                }
            }

            var winners = datapoints.filter(function (d) {
                return d.Sum === winningScore;
            });

            $scope.winner = winners.map(function (d) {
                return d.Name;
            }).join(', ');

            $scope.plural = (winners.length > 1) ? 's (Draw)' : '';

            drawD3Chart(datapoints);
        }

        VoteService.refreshLastChecked(pollId);
        reloadData();
        setInterval(reloadData, 3000);
    }
})();
<commit_msg>Dynamic sizing of bars<commit_after>/// <reference path="../Services/IdentityService.js" />
/// <reference path="../Services/PollService.js" />
/// <reference path="../Services/VoteService.js" />
(function () {
    angular
        .module('GVA.Voting')
        .controller('ResultsPageController', ResultsPageController);

    ResultsPageController.$inject = ['$scope', '$routeParams', 'IdentityService', 'VoteService', 'RoutingService'];

    function ResultsPageController($scope, $routeParams, IdentityService, VoteService, RoutingService) {

        var pollId = $routeParams.pollId;
        var tokenId = $routeParams['tokenId'] || '';
        var chart;

        // Turn "/#/results/abc/123" into "/#/voting/abc/123"
        $scope.votingLink = RoutingService.getVotePageUrl(pollId, tokenId);

        $scope.winner = 'Lorem';
        //Whether or not we have an "s" on the end of "Winner"
        $scope.plural = '';

        $scope.voteCount = 0;

        var canvas = document.createElement('canvas');

        var textWidth = function (text) {
            var context = canvas.getContext('2d');
            context.font = '16px Open Sans';
            var metrics = context.measureText(text);
            return metrics.width;
        };

        var drawD3Chart = function (data) {
            // Hack to fix lack of data reloading
            document.getElementById('results-chart').innerHTML = '';

            data = data.sort(function (a, b) { return b.Sum - a.Sum; });

            var chartHeight = Math.min(data.length * 60, 600);
            var chartWidth = Math.min(600, document.getElementById('results-chart').offsetWidth);

            var longestTextWidth = d3.max(data, function (d) { return textWidth(d.Name); });

            var margin = { top: 30, right: 10, bottom: 10, left: longestTextWidth + 10 };
            var width = chartWidth - margin.left - margin.right;
            var height = chartHeight - margin.top - margin.bottom;

            var minX = d3.min(data, function (d) { return d.Sum; });
            var maxX = d3.max(data, function (d) { return d.Sum; });

            var x = d3.scale.linear()
                .range([0, width])
                .domain([Math.min(0, minX), maxX]).nice();

            var dataRange = x.domain()[1] - x.domain()[0];
            var tickFrequency = Math.max((Math.pow(10, (Math.round(Math.log(dataRange) / Math.log(10)) - 1))), 1);

            var y = d3.scale.ordinal()
                .rangeRoundBands([0, height], 0.1)
                .domain(data.map(function (d) { return d.Name; }));

            var xAxis = d3.svg.axis()
                .scale(x)
                .orient('top')
                .ticks(dataRange / tickFrequency); // Ticks is *how many* ticks we display, not the frequency...

            var yAxis = d3.svg.axis()
                .scale(y)
                .orient('left');

            var chart = d3.select('#results-chart')
                .append('svg')
                    .attr('width', chartWidth)
                    .attr('height', chartHeight)
                .append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');

            chart.append('g')
                .attr('class', 'x axis')
                .call(xAxis);

            chart.append('g')
                .attr('class', 'y axis')
                .call(yAxis)
                .append('line')
                .attr('x1', x(0))
                .attr('x2', x(0))
                .attr('y2', height);

            chart.selectAll('.bar')
                .data(data)
                .enter().append('rect')
                .attr('class', function (d) { return d.Sum < 0 ? 'bar negative' : 'bar positive'; })
                .attr('x', function (d) {
                    return x(Math.min(0, d.Sum));
                })
                .attr('y', function (d) {
                    return y(d.Name);
                })
                .attr('width', function (d) {
                    return Math.abs(x(-d.Sum) - x(0));
                })
                .attr('height', y.rangeBand());
        };

        var reloadData = function () {
            VoteService.getResults(pollId, getResultsSuccessCallback);
        };

        function getResultsSuccessCallback(data, status) {

            if (data) {
                $scope.voteCount = data.length;
            }

            var groupedData = {};

            // Group together votes for the same options
            data.forEach(function (d) {
                if (!(d.OptionName in groupedData)) {
                    groupedData[d.OptionName] = { Value: 0, Voters: [] };
                }

                groupedData[d.OptionName].Value += d.VoteValue;
                groupedData[d.OptionName].Voters.push(d.VoterName);

            });

            var winningScore = 0;

            var datapoints = [];

            // Separate into datapoints
            for (var key in groupedData) {
                if (groupedData.hasOwnProperty(key)) {
                    datapoints.push({ Name: key, Sum: groupedData[key].Value, Voters: groupedData[key].Voters });
                    winningScore = Math.max(winningScore, groupedData[key].Value);
                }
            }

            var winners = datapoints.filter(function (d) {
                return d.Sum === winningScore;
            });

            $scope.winner = winners.map(function (d) {
                return d.Name;
            }).join(', ');

            $scope.plural = (winners.length > 1) ? 's (Draw)' : '';

            drawD3Chart(datapoints);
        }

        VoteService.refreshLastChecked(pollId);
        reloadData();
        setInterval(reloadData, 3000);
    }
})();
<|endoftext|>


<commit_before>/*
    Star Game Engine
*/

var se = new Object();

window.animationFrame = (function(){
    return  window.requestAnimationFrame       ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame    ||
        window.oRequestAnimationFrame      ||
        window.msRequestAnimationFrame     ||
        function(/* function */ callback, /* DOMElement */ element){
            window.setTimeout(callback, 1000 / 60);
        };
})();

se.windowGameMain = null;

se.updateFrame = function (){
    se.windowGameMain.update();
    animationFrame(se.updateFrame);
}

/*
    Windows Game
*/
se.WindowGame = function (elementID){
	var self = this;
    this.element = document.getElementById(elementID);
    if (this.element.getContext){
        this.ctx = canvas.getContext('2d');
    }
    this.scenes = [];
    this.joystick = new se.Joystick();
    self.updateSize();
    $(window).resize(function(){
    	var scene = self.getSceneCurrent().resetCamera();
    	self.updateSize();
    });
};
se.WindowGame.prototype.getWidth = function(){
    return this.element.width;
};
se.WindowGame.prototype.getHeight = function(){
    return this.element.height;
};
se.WindowGame.prototype.getSceneCurrent = function(){
    return this.scenes[0];
};
se.WindowGame.prototype.setSize = function(width, height){
    var elem = this.element;
    this.element.width = width;
    this.element.height = height;
}
se.WindowGame.prototype.updateSize = function(){
	var ele = $(this.element);
	var parent = ele.parent();
	this.setSize(parent.width(), parent.height());
}
se.WindowGame.prototype.clrscr = function(){
    this.ctx.clearRect(0,0,this.getWidth(), this.getHeight());
};
se.WindowGame.prototype.getContext = function(){
    return this.ctx;
};
se.WindowGame.prototype.addScene = function(scene){
    this.scenes.push(scene);
    scene.parent = this;
};
se.WindowGame.prototype.render = function(){
    this.getSceneCurrent().render(this.ctx);
};
se.WindowGame.prototype.update = function(){
    // this.updateSize();
    this.render();
};
se.WindowGame.prototype.init = function(){
    se.windowGameMain = this;
    animationFrame(se.updateFrame);
};

/*
    Scene
*/
se.Scene = function (){
    this.camera = new se.GameObject('MainCamera',0,0,0,0);
    this.camera.parent = this;
    this.camX = 0;
    this.camY = 0;
    this.objs = [this.camera];
};
se.Scene.prototype.getWidth = function(){
    return this.parent.getWidth();
};
se.Scene.prototype.getHeight = function(){
    return this.parent.getHeight();
};
se.Scene.prototype.getCamera = function(){
    return this.camera;
};
se.Scene.prototype.getObjs = function(){
    return this.objs;
};
se.Scene.prototype.add = function(obj){
    this.objs.push(obj);
    obj.parent = this;
};
se.Scene.prototype.render = function(ctx){
    this.check_move_cam(ctx);
    this.clear(ctx);
    this.renderBackground(ctx);
    for(var i in this.objs){
        this.objs[i].render(ctx);
    }
};
se.Scene.prototype.renderBackground = function(ctx){
	ctx.fillStyle = 'rgba(135, 206, 250,1)';
	ctx.fillRect(
        this.camera.getX(),
        this.camera.getY(),
        this.getWidth(),
        this.getHeight()
    );
}
se.Scene.prototype.clear = function(ctx){
    ctx.clearRect(
        this.camera.getX(),
        this.camera.getY(),
        this.getWidth(),
        this.getHeight()
    );
}
se.Scene.prototype.check_move_cam = function(ctx){
    if(this.camX != this.camera.getX() || this.camY != this.camera.getY()){
        var x = this.camX - this.camera.getX();
        var y = this.camY - this.camera.getY();
        ctx.translate(x,y);
        this.camX = this.camera.getX();
        this.camY = this.camera.getY();
    }
}
se.Scene.prototype.resetCamera = function(){
	this.camX = 0;
	this.camY = 0;
}

/*
    GameObject
*/
se.GameObject = function (name, x, y, width, height){
    this.name = name;
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.components = [];
    this.colliders = [];
    this.renderer = null;
};
se.GameObject.prototype.getX = function(){
    return this.x;
};
se.GameObject.prototype.getY = function(){
    return this.y;
};
se.GameObject.prototype.getWidth = function(){
    return this.width;
};
se.GameObject.prototype.getHeight = function(){
    return this.height;
};
se.GameObject.prototype.getColliders = function(){
    return this.colliders;
};
se.GameObject.prototype.setRenderer = function(renderer){
	renderer.setParent(this);
    this.renderer = renderer;
};
se.GameObject.prototype.render = function(ctx){
    this.update();
    if(this.renderer) this.renderer.render(ctx);
};
se.GameObject.prototype.update = function(){
    for(var i in this.components){
        this.components[i].update(this);
    }
};
se.GameObject.prototype.addComponent = function(component){
    this.components.push(component);
    component.setParent(this);
    return this;
};
se.GameObject.prototype.addCollider = function(collider){
    this.colliders.push(collider);
    collider.setParent(this);
    return this;
};
se.GameObject.prototype.move = function(x,y){
    this.x = x;
    this.y = y;
};
se.GameObject.prototype.sum = function(x,y){
    var xb = this.x;
    var yb = this.y;
    this.x += x;
    this.y += y;
    if(this.checkCollision()){
        this.x = xb;
        this.y = yb;
    }
};
se.GameObject.prototype.checkCollision = function(){
    var scene = this.parent;
    var objs = scene.getObjs();
    for(var i in objs){
        var obj = objs[i];
        if(this != obj){
            if( this.isColliding( obj.getColliders() ) )
                return true;
        }
    }
    return false;
}
se.GameObject.prototype.isColliding = function(colliders){
	var cols1 = this.getColliders();
	var cols2 = colliders;
	for(var i in cols1){
        for(var j in cols2){
            var col1 = cols1[i];
            var col2 = cols2[j];
            if(col1.checkContido(col2)){
                return true;
            }
        }
    }
    return false;
}

/*
    Joystick
*/
se.Joystick = function (){
    this.key = null;
    var self = this;
    var x = 0;
    var y = 0;
    this.jump = false;
    $(document).keydown(function(e){
        self.key = e.keyCode;
        self.update();
    });
    $(document).keyup(function(e){
        self.key = null;
        self.reset();
    });
}

se.Joystick.prototype.update = function(){
    var key = this.key;
    if (key == '65'){ // Left
        this.x = -1;
    } else if (key == '68'){ // 'right'
        this.x = 1;
    } else if (key == '87'){ // Up
        this.y = -1;
    } else if (key == '83'){ // 'Down'
        this.y = 1;
    } else if (key == '32'){ // 'Space'
        this.jump = true
    }
}

se.Joystick.prototype.reset = function (){
    this.x = 0;
    this.y = 0;
    this.jump = false;
}

se.Joystick.prototype.getAxis = function (name){
    if(name == 'horizontal') return this.x;
    if(name == 'vertical') return this.y;
    if(name == 'jump') return this.jump;
    return 0;
}

/*
    ComponentScript
*/
se.ComponentScript = function (function_update){
    this.update = function_update;
};
se.ComponentScript.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
    ComponentPlayerController
*/
se.ComponentPlayerController = function (game,speed,gravity){
    this.window = game;
    this.speed = speed;
};
se.ComponentPlayerController.prototype.update = function(obj){
    var x = game.joystick.getAxis('horizontal') * this.speed;
    if(x)
        obj.sum(x,0);
    //var y = game.joystick.getAxis('vertical') * this.speed;
    if(game.joystick.getAxis('jump')){
        obj.sum(0, -1 * this.speed * 2);
    }
};
se.ComponentPlayerController.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
    ComponentFollowPlayer
*/
se.ComponentFollowPlayer = function (obj_player){
    this.obj_player = obj_player;
}
se.ComponentFollowPlayer.prototype.update = function(obj){
	var scene = this.parent.parent;

    var posx = scene.getWidth() / 2 - this.obj_player.width / 2;
    posx = this.obj_player.x + (this.obj_player.width / 2) - posx;
    var posy = scene.getHeight() / 2 - this.obj_player.height / 2;
    posy = this.obj_player.y + (this.obj_player.height / 2) - posy;

    obj.move(posx,posy);
}
se.ComponentFollowPlayer.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
    ComponentRigidBody
*/
se.ComponentRigidBody = function (gravity){
    this.gravity = gravity;
}
se.ComponentRigidBody.prototype.update = function(obj){
    obj.sum(0, this.gravity);
}
se.ComponentRigidBody.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
BoxRender
*/
se.BoxRenderer = function(color){
	this.color = color;
}
se.BoxRenderer.prototype.render = function(ctx){
    var obj = this.parent;
    var cbkp = ctx.fillStyle; // Backup
    ctx.fillStyle = this.color;
    ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
    ctx.fillStyle = cbkp; // Restore backup

}
se.BoxRenderer.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
    Collider
*/
se.BoxCollider = function (x, y, width, height){
	this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}
se.BoxCollider.prototype.setParent = function(obj){
	this.parent = obj;
}
se.BoxCollider.prototype.getPoints = function(){
	var obj = this.parent;
	var x = obj.getX() + this.x;
	var y = obj.getY() + this.y;
	var width = this.width;
	var height = this.height;

	var points = [];
    points.push([x, y]);
    points.push([x + width, y]);
    points.push([x, y + height]);
    points.push([x + width, y + height]);
	return points;
}

se.BoxCollider.prototype.checkContido = function(collider){
	var ps1 = this.getPoints();
	var ps2 = collider.getPoints();
	var min = ps2[0];
    var max = ps2[3];
	for(var i in ps1){
        if(ps1[i][0] >= min[0] && ps1[i][0] <= max[0] && ps1[i][1] >= min[1] && ps1[i][1] <= max[1])
            return true;
    }
	return false;
}

<commit_msg>Removendo o igual (=) na comparacao de contido para que dois objetos se encostem<commit_after>/*
    Star Game Engine
*/

var se = new Object();

window.animationFrame = (function(){
    return  window.requestAnimationFrame       ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame    ||
        window.oRequestAnimationFrame      ||
        window.msRequestAnimationFrame     ||
        function(/* function */ callback, /* DOMElement */ element){
            window.setTimeout(callback, 1000 / 60);
        };
})();

se.windowGameMain = null;

se.updateFrame = function (){
    se.windowGameMain.update();
    animationFrame(se.updateFrame);
}

/*
    Windows Game
*/
se.WindowGame = function (elementID){
	var self = this;
    this.element = document.getElementById(elementID);
    if (this.element.getContext){
        this.ctx = canvas.getContext('2d');
    }
    this.scenes = [];
    this.joystick = new se.Joystick();
    self.updateSize();
    $(window).resize(function(){
    	var scene = self.getSceneCurrent().resetCamera();
    	self.updateSize();
    });
};
se.WindowGame.prototype.getWidth = function(){
    return this.element.width;
};
se.WindowGame.prototype.getHeight = function(){
    return this.element.height;
};
se.WindowGame.prototype.getSceneCurrent = function(){
    return this.scenes[0];
};
se.WindowGame.prototype.setSize = function(width, height){
    var elem = this.element;
    this.element.width = width;
    this.element.height = height;
}
se.WindowGame.prototype.updateSize = function(){
	var ele = $(this.element);
	var parent = ele.parent();
	this.setSize(parent.width(), parent.height());
}
se.WindowGame.prototype.clrscr = function(){
    this.ctx.clearRect(0,0,this.getWidth(), this.getHeight());
};
se.WindowGame.prototype.getContext = function(){
    return this.ctx;
};
se.WindowGame.prototype.addScene = function(scene){
    this.scenes.push(scene);
    scene.parent = this;
};
se.WindowGame.prototype.render = function(){
    this.getSceneCurrent().render(this.ctx);
};
se.WindowGame.prototype.update = function(){
    // this.updateSize();
    this.render();
};
se.WindowGame.prototype.init = function(){
    se.windowGameMain = this;
    animationFrame(se.updateFrame);
};

/*
    Scene
*/
se.Scene = function (){
    this.camera = new se.GameObject('MainCamera',0,0,0,0);
    this.camera.parent = this;
    this.camX = 0;
    this.camY = 0;
    this.objs = [this.camera];
};
se.Scene.prototype.getWidth = function(){
    return this.parent.getWidth();
};
se.Scene.prototype.getHeight = function(){
    return this.parent.getHeight();
};
se.Scene.prototype.getCamera = function(){
    return this.camera;
};
se.Scene.prototype.getObjs = function(){
    return this.objs;
};
se.Scene.prototype.add = function(obj){
    this.objs.push(obj);
    obj.parent = this;
};
se.Scene.prototype.render = function(ctx){
    this.check_move_cam(ctx);
    this.clear(ctx);
    this.renderBackground(ctx);
    for(var i in this.objs){
        this.objs[i].render(ctx);
    }
};
se.Scene.prototype.renderBackground = function(ctx){
	ctx.fillStyle = 'rgba(135, 206, 250,1)';
	ctx.fillRect(
        this.camera.getX(),
        this.camera.getY(),
        this.getWidth(),
        this.getHeight()
    );
}
se.Scene.prototype.clear = function(ctx){
    ctx.clearRect(
        this.camera.getX(),
        this.camera.getY(),
        this.getWidth(),
        this.getHeight()
    );
}
se.Scene.prototype.check_move_cam = function(ctx){
    if(this.camX != this.camera.getX() || this.camY != this.camera.getY()){
        var x = this.camX - this.camera.getX();
        var y = this.camY - this.camera.getY();
        ctx.translate(x,y);
        this.camX = this.camera.getX();
        this.camY = this.camera.getY();
    }
}
se.Scene.prototype.resetCamera = function(){
	this.camX = 0;
	this.camY = 0;
}

/*
    GameObject
*/
se.GameObject = function (name, x, y, width, height){
    this.name = name;
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.components = [];
    this.colliders = [];
    this.renderer = null;
};
se.GameObject.prototype.getX = function(){
    return this.x;
};
se.GameObject.prototype.getY = function(){
    return this.y;
};
se.GameObject.prototype.getWidth = function(){
    return this.width;
};
se.GameObject.prototype.getHeight = function(){
    return this.height;
};
se.GameObject.prototype.getColliders = function(){
    return this.colliders;
};
se.GameObject.prototype.setRenderer = function(renderer){
	renderer.setParent(this);
    this.renderer = renderer;
};
se.GameObject.prototype.render = function(ctx){
    this.update();
    if(this.renderer) this.renderer.render(ctx);
};
se.GameObject.prototype.update = function(){
    for(var i in this.components){
        this.components[i].update(this);
    }
};
se.GameObject.prototype.addComponent = function(component){
    this.components.push(component);
    component.setParent(this);
    return this;
};
se.GameObject.prototype.addCollider = function(collider){
    this.colliders.push(collider);
    collider.setParent(this);
    return this;
};
se.GameObject.prototype.move = function(x,y){
    this.x = x;
    this.y = y;
};
se.GameObject.prototype.sum = function(x,y){
    var xb = this.x;
    var yb = this.y;
    this.x += x;
    this.y += y;
    if(this.checkCollision()){
        this.x = xb;
        this.y = yb;
    }
};
se.GameObject.prototype.checkCollision = function(){
    var scene = this.parent;
    var objs = scene.getObjs();
    for(var i in objs){
        var obj = objs[i];
        if(this != obj){
            if( this.isColliding( obj.getColliders() ) )
                return true;
        }
    }
    return false;
}
se.GameObject.prototype.isColliding = function(colliders){
	var cols1 = this.getColliders();
	var cols2 = colliders;
	for(var i in cols1){
        for(var j in cols2){
            var col1 = cols1[i];
            var col2 = cols2[j];
            if(col1.checkContido(col2)){
                return true;
            }
        }
    }
    return false;
}

/*
    Joystick
*/
se.Joystick = function (){
    this.key = null;
    var self = this;
    var x = 0;
    var y = 0;
    this.jump = false;
    $(document).keydown(function(e){
        self.key = e.keyCode;
        self.update();
    });
    $(document).keyup(function(e){
        self.key = null;
        self.reset();
    });
}

se.Joystick.prototype.update = function(){
    var key = this.key;
    if (key == '65'){ // Left
        this.x = -1;
    } else if (key == '68'){ // 'right'
        this.x = 1;
    } else if (key == '87'){ // Up
        this.y = -1;
    } else if (key == '83'){ // 'Down'
        this.y = 1;
    } else if (key == '32'){ // 'Space'
        this.jump = true
    }
}

se.Joystick.prototype.reset = function (){
    this.x = 0;
    this.y = 0;
    this.jump = false;
}

se.Joystick.prototype.getAxis = function (name){
    if(name == 'horizontal') return this.x;
    if(name == 'vertical') return this.y;
    if(name == 'jump') return this.jump;
    return 0;
}

/*
    ComponentScript
*/
se.ComponentScript = function (function_update){
    this.update = function_update;
};
se.ComponentScript.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
    ComponentPlayerController
*/
se.ComponentPlayerController = function (game,speed,gravity){
    this.window = game;
    this.speed = speed;
};
se.ComponentPlayerController.prototype.update = function(obj){
    var x = game.joystick.getAxis('horizontal') * this.speed;
    if(x)
        obj.sum(x,0);
    //var y = game.joystick.getAxis('vertical') * this.speed;
    if(game.joystick.getAxis('jump')){
        obj.sum(0, -1 * this.speed * 2);
    }
};
se.ComponentPlayerController.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
    ComponentFollowPlayer
*/
se.ComponentFollowPlayer = function (obj_player){
    this.obj_player = obj_player;
}
se.ComponentFollowPlayer.prototype.update = function(obj){
	var scene = this.parent.parent;

    var posx = scene.getWidth() / 2 - this.obj_player.width / 2;
    posx = this.obj_player.x + (this.obj_player.width / 2) - posx;
    var posy = scene.getHeight() / 2 - this.obj_player.height / 2;
    posy = this.obj_player.y + (this.obj_player.height / 2) - posy;

    obj.move(posx,posy);
}
se.ComponentFollowPlayer.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
    ComponentRigidBody
*/
se.ComponentRigidBody = function (gravity){
    this.gravity = gravity;
}
se.ComponentRigidBody.prototype.update = function(obj){
    obj.sum(0, this.gravity);
}
se.ComponentRigidBody.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
BoxRender
*/
se.BoxRenderer = function(color){
	this.color = color;
}
se.BoxRenderer.prototype.render = function(ctx){
    var obj = this.parent;
    var cbkp = ctx.fillStyle; // Backup
    ctx.fillStyle = this.color;
    ctx.fillRect(obj.x, obj.y, obj.width, obj.height);
    ctx.fillStyle = cbkp; // Restore backup

}
se.BoxRenderer.prototype.setParent = function(obj){
	this.parent = obj;
}

/*
    Collider
*/
se.BoxCollider = function (x, y, width, height){
	this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
}
se.BoxCollider.prototype.setParent = function(obj){
	this.parent = obj;
}
se.BoxCollider.prototype.getPoints = function(){
	var obj = this.parent;
	var x = obj.getX() + this.x;
	var y = obj.getY() + this.y;
	var width = this.width;
	var height = this.height;

	var points = [];
    points.push([x, y]);
    points.push([x + width, y]);
    points.push([x, y + height]);
    points.push([x + width, y + height]);
	return points;
}

se.BoxCollider.prototype.checkContido = function(collider){
	var ps1 = this.getPoints();
	var ps2 = collider.getPoints();
	var min = ps2[0];
    var max = ps2[3];
	for(var i in ps1){
        if(ps1[i][0] > min[0] && ps1[i][0] < max[0] && ps1[i][1] > min[1] && ps1[i][1] < max[1])
            return true;
    }
	return false;
}

<|endoftext|>


<commit_before>/*
 *  Free Room Finder Website
 *
 *
 *  Authors -- Crow's Foot Group
 *  -------------------------------------------------------
 *
 *  Jonathan Gillett
 *  Joseph Heron
 *  Amit Jain
 *  Wesley Unwin
 *  Anthony Jihn
 *
 *
 *  License
 *  -------------------------------------------------------
 *
 *  Copyright (C) 2012 Crow's Foot Group
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/* The root URL for the RESTful services */
var rootURL = "http://free-room.dom/api";

$(document).ready(function () {
	/* Display the statistics when page is loaded */
	busyProfs();
	totalEnrollment();

});

/* Get the list of the top 10 busiest professors and populate the table */
function busyProfs() {
	console.log('busyprofs');
	$.ajax({
		type: 'GET',
		url: rootURL + '/busyprofs/10',
		dataType: "json", // data type of response
		success: displayTable
	});
}

/* Get the total enrollment for all students and plot the chart */
function totalEnrollment() {
	console.log('busyprofs');
	$.ajax({
		type: 'GET',
		url: rootURL + '/totalregistered',
		dataType: "json", // data type of response
		success: plotEnrollmentAll
	});
}

/* Function which populates the busiest profs table with the top 10
 * busiest professors
 */
function displayTable(data) {
	console.log('displayTable');
	// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
	var list = data == null ? [] : (data.busyProfs instanceof Array ? data.busyProfs : [data.busyProfs]);

	$.each(list, function(index, prof) {
		$('#tbody_busyprofs').append('
' + prof.professor + '	' + prof.student_num + '
');
	});
}

/* Function which plots the student enrollment for all students */
function plotEnrollmentAll(data) {
	console.log('plotEnrollmentAll');
	var chart;
    var options = {
        chart: {
            renderTo: 'enrollment_all',
            type: 'area'
        },
        title: {
            text: 'UOIT Enrollment'
        },
        xAxis: {
            labels: {
                formatter: function() {
                    return this.value; // clean, unformatted number for year
                }
            }
        },
        yAxis: {
            title: {
                text: 'Number of Students'
            },
            labels: {
                formatter: function() {
                    return this.value / 1000 +'k';
                }
            }
        },
        tooltip: {
            formatter: function() {
                return this.series.name +' enrolled '+
                    Highcharts.numberFormat(this.y, 0) +'
students in '+ this.x;
            }
        },
        plotOptions: {
            area: {
                pointStart: 2003,
                marker: {
                    enabled: false,
                    symbol: 'circle',
                    radius: 2,
                    states: {
                        hover: {
                            enabled: true
                        }
                    }
                }
            }
        },
        series: [{
            name: 'UOIT',
            data: [100, 220, 300, 500, 900, 1200, 2000]
        }]
    };

    /* Get the enrollment data from the REST api and add it to the series */
	console.log('enrollmentAllGetData');
	// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
	var list = data == null ? [] : (data.totalRegistered instanceof Array ? data.totalRegistered : [data.totalRegistered]);
	var arr_registered = [];
	var approx_reg = 0;

	$.each(list, function(index, enrollment) {
		alert(parseInt(enrollment.registered));

		/* Approximate the number of students attending as total / 5 (assume avg. course load of 5) */
		approx_reg = parseInt(enrollment.registered) / 5;

		/* Add the approx number of registered students to the plotting data */
		options.series[0].data.push(approx_reg);
	});

	chart = new Highcharts.Chart(options);
}<commit_msg>Added support to display the enrollment plot using test data for years < 2009<commit_after>/*
 *  Free Room Finder Website
 *
 *
 *  Authors -- Crow's Foot Group
 *  -------------------------------------------------------
 *
 *  Jonathan Gillett
 *  Joseph Heron
 *  Amit Jain
 *  Wesley Unwin
 *  Anthony Jihn
 *
 *
 *  License
 *  -------------------------------------------------------
 *
 *  Copyright (C) 2012 Crow's Foot Group
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/* The root URL for the RESTful services */
var rootURL = "http://free-room.dom/api";

$(document).ready(function () {
	/* Display the statistics when page is loaded */
	if (window.location.pathname.match(/statistics\.php/))
	{
		busyProfs();
		totalEnrollment();
	}
});

/* Get the list of the top 10 busiest professors and populate the table */
function busyProfs() {
	console.log('busyprofs');
	$.ajax({
		type: 'GET',
		url: rootURL + '/busyprofs/10',
		dataType: "json", // data type of response
		success: displayTable
	});
}

/* Get the total enrollment for all students and plot the chart */
function totalEnrollment() {
	console.log('busyprofs');
	$.ajax({
		type: 'GET',
		url: rootURL + '/totalregistered',
		dataType: "json", // data type of response
		success: plotEnrollmentAll
	});
}

/* Function which populates the busiest profs table with the top 10
 * busiest professors
 */
function displayTable(data) {
	console.log('displayTable');
	// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
	var list = data == null ? [] : (data.busyProfs instanceof Array ? data.busyProfs : [data.busyProfs]);

	$.each(list, function(index, prof) {
		$('#tbody_busyprofs').append('
' + prof.professor + '	' + prof.student_num + '
');
	});
}

/* Function which plots the student enrollment for all students */
function plotEnrollmentAll(data) {
	console.log('plotEnrollmentAll');
	var chart;
    var options = {
        chart: {
            renderTo: 'enrollment_all',
            type: 'area'
        },
        title: {
            text: 'UOIT Enrollment'
        },
        xAxis: {
            labels: {
                formatter: function() {
                    return this.value; // clean, unformatted number for year
                }
            }
        },
        yAxis: {
            title: {
                text: 'Number of Students'
            },
            labels: {
                formatter: function() {
                    return this.value / 1000 +'k';
                }
            }
        },
        tooltip: {
            formatter: function() {
                return this.series.name +' enrolled '+
                    Highcharts.numberFormat(this.y, 0) +'
students in '+ this.x;
            }
        },
        plotOptions: {
            area: {
                pointStart: 2003,
                marker: {
                    enabled: false,
                    symbol: 'circle',
                    radius: 2,
                    states: {
                        hover: {
                            enabled: true
                        }
                    }
                }
            }
        },
        series: [{
            name: 'UOIT',
            data: [ 300, 546, 1349, 2188, 4210, 5832]
        }]
    };

    /* Get the enrollment data from the REST api and add it to the series */
	console.log('enrollmentAllGetData');
	// JAX-RS serializes an empty list as null, and a 'collection of one' as an object (not an 'array of one')
	var list = data == null ? [] : (data.totalRegistered instanceof Array ? data.totalRegistered : [data.totalRegistered]);
	var arr_registered = [];
	var approx_reg = 0;

	$.each(list, function(index, enrollment) {
		alert(parseInt(enrollment.registered));

		/* Approximate the number of students attending as total / 5 (assume avg. course load of 5) */
		approx_reg = parseInt(enrollment.registered) / 5;

		/* Add the approx number of registered students to the plotting data */
		options.series[0].data.push(approx_reg);
	});

	chart = new Highcharts.Chart(options);
}<|endoftext|>


<commit_before>function getDateNumFromDate(dateObject){
  // console.log('date before: ' + dateObject.getTime());
  dateObject.setMilliseconds(0); dateObject.setSeconds(0); dateObject.setMinutes(0); dateObject.setHours(0);
  console.log('date after' + dateObject.getTime());
  return dateObject.valueOf();
};

function User(){
  this.userName = '';
  this.userEmail = '';
  this.dailyWaterIntakeGoal = 0;
  this.dailyWaterIntake = 0;
  this.dailyProteinIntakeGoal = 0;
  this.dailyProteinIntake = 0;
  this.dailyExerciseGoal = 0;
  this.dailyExercise = 0;
  this.currentDate = new Date();
  var test = getDateNumFromDate(new Date());
  this.currentDateNumber = test;
  this.userData = [];

  console.log('creating User ' + this.currentDate.valueOf() + ' ' + this.currentDateNumber);
}

User.prototype.getUserDataFromStorage = function() {
//  initialize user name and goals
  console.log('getUserDataFromStorage');
  if (localStorage.getItem('OnTrack-currentUser')) {
    var loadUserInfo = JSON.parse(localStorage.getItem('OnTrack-currentUser'));

    this.userName = loadUserInfo.userName;
    this.userEmail = loadUserInfo.userEmail;

    this.dailyWaterIntakeGoal = loadUserInfo.dailyWaterIntakeGoal;
    this.dailyProteinIntakeGoal = loadUserInfo.dailyProteinIntakeGoal;
    this.dailyExerciseGoal = loadUserInfo.dailyExerciseGoal;
    console.log(this.UserName + ' ' + this.dailyWaterIntakeGoal);

  }
  else console.log('error trying to get current user from storage');

  // check the date - if current date (not time) is same as stored in currentUser local Storage
  // then initialize progress from local storage, otherwise set to zero.
  var todayDate = new Date();
  var today = getDateNumFromDate(todayDate);

  console.log('current date num; ' + today + ' loaded Date Num: ' + loadUserInfo.currentDateNumber);
  if ( today == loadUserInfo.currentDateNumber) {
    // We're on the same day
    console.log('same day');
    this.dailyWaterIntake = loadUserInfo.dailyWaterIntake;
    this.dailyProteinIntake = loadUserInfo.dailyProteinIntake;
    this.dailyExercise = loadUserInfo.dailyExerciseGoal;
  } else {
    console.log('new day');
    // today is a new day - set our daily progress to 0
    this.dailyWaterIntake = 0;
    this.dailyProteinIntake = 0;
    this.dailyExercise = 0;
  }
  this.currentDateNumber = today;
  this.currentDateNumber = new Date();

};

User.prototype.drinkWater = function(amount) {
  this.dailyWaterIntake += 1;
};

User.prototype.eatProtein = function(amount) {
  this.dailyProteinIntake += amount;
};

User.prototype.exercise = function(amount) {
};

User.prototype.writeUserInfoToLocalStorage = function() {

// update info in our OnTrack-currentUser so data is always persisted
  localStorage.setItem('OnTrack-currentUser',JSON.stringify(currentUserData));

};

function currentUserDataArray () {
  var myArray = [];

  myArray.push(currentUser.currentDateNumber);
  myArray.push(currentUser.userName);
  myArray.push(currentUser.userEmail);
  myArray.push(currentUser.dailyWaterIntakeGoal);
  myArray.push(currentUser.dailyWaterIntake);
  myArray.push(currentUser.dailyProteinIntakeGoal);
  myArray.push(currentUser.dailyProteinIntake);
  myArray.push(currentUser.dailyExerciseGoal);
  myArray.push(currentUser.dailyExercise);
  return myArray;
};

User.prototype.updateUserData = function(){
  var loadUserData = localStorage.getItem('OnTrack-currentUserData');
  if (loadUserData) {
    //we already have userData stored.
    var lastUserData = loadUserData[loadUserData.length - 1];
    if (lastUserData[0] === currentUser.currentDateNumber){
      // we have a match - current date is same as last date stored.
      loadUserData.pop();
      loadUserData.push(currentUserDataArray());
    } else {
      // last data doesn't match, push new data.
      loadUserData.push(currentUserDataArray);
    }

    this.userData = loadUserData;
  }

// write data to a new key that includes username
// data is an array of array data. One element for each day
// each day looks like [daynumber, waterIntake, waterGoal, proteinIntake, proteinGoal, exercise, exerciseGoal]
// when we write the data, we read in the existing data, check the day number of the last element
// if it is the same as current date, we pop that off the end of the array, replace it with current and write the whole new array to storage
// if it is not the same (less than), we push our current user data to end and re-write array
// if it is less than, someone has changed the clock and we bail

};

User.prototype.updateLocalStorage = function() {
// update userInfo and userData to local storage
};

// one or more functions to get an array of chart data from the localStorage userData.
User.prototype.getChartData = function () {
};

User.prototype.clearCurrentUserStorage = function () {
  if (localStorage.getItem('OnTrack-currentUser')) {
    localStorage.removeItem('OnTrack-currentUser');
  }
};

User.prototype.registerNewUser = function (){
  console.log('registering new user');
  this.userName = document.getElementById('nameInput').value;
  this.userEmail = document.getElementById('emailInput').value;
  this.dailyWaterIntakeGoal = document.getElementById('waterInput').value;
  this.dailyProteinIntakeGoal = document.getElementById('proteinInput').value;
  this.dailyExerciseGoal = document.getElementById('exerciseInput').value;
  // console.log('Localstorage username: ' + JSON.parse(localStorage.getItem('OnTrack-currentUser')).userName + ' entered name: ' + this.userName);
  if (localStorage.getItem('OnTrack-currentUser')) {
    if (JSON.parse(localStorage.getItem('OnTrack-currentUser')).userName == this.userName) {
      console.log('Local Storage for OnTrack User ' + this.userName + ' Exists');
      DlgShow('Sorry ' + this.UserName + ', that name is already in use.', 'Do you want to login as <b>' + name + '<b> or change your user name?');
    } else {
      localStorage.setItem('OnTrack-currentUser',JSON.stringify(currentUser));
      console.log('User: ' + this.UserName + ' water intake: ' + this.dailyWaterIntakeGoal + ' protein intake: ' + this.dailyProteinIntakeGoal + ' exercise: ' + this.dailyExerciseGoal);
      window.open('daily.html', '_self');
    }
  } else {
    localStorage.setItem('OnTrack-currentUser',JSON.stringify(currentUser));
    console.log('User: ' + this.UserName + ' water intake: ' + this.dailyWaterIntakeGoal + ' protein intake: ' + this.dailyProteinIntakeGoal + ' exercise: ' + this.dailyExerciseGoal);
    window.open('daily.html', '_self');
  }
};
<commit_msg>more work on userObject to<commit_after>function getDateNumFromDate(dateObject){
  // console.log('date before: ' + dateObject.getTime());
  dateObject.setMilliseconds(0); dateObject.setSeconds(0); dateObject.setMinutes(0); dateObject.setHours(0);
  console.log('date after' + dateObject.getTime());
  return dateObject.valueOf();
};

function User(){
  this.userName = '';
  this.userEmail = '';
  this.dailyWaterIntakeGoal = 0;
  this.dailyWaterIntake = 0;
  this.dailyProteinIntakeGoal = 0;
  this.dailyProteinIntake = 0;
  this.dailyExerciseGoal = 0;
  this.dailyExercise = 0;
  this.currentDate = new Date();
  var test = getDateNumFromDate(new Date());
  this.currentDateNumber = test;
  this.userData = [];

  console.log('creating User ' + this.currentDate.valueOf() + ' ' + this.currentDateNumber);
}

User.prototype.getUserDataFromStorage = function() {
//  initialize user name and goals
  console.log('getUserDataFromStorage');
  if (localStorage.getItem('OnTrack-currentUser')) {
    var loadUserInfo = JSON.parse(localStorage.getItem('OnTrack-currentUser'));

    this.userName = loadUserInfo.userName;
    this.userEmail = loadUserInfo.userEmail;

    this.dailyWaterIntakeGoal = loadUserInfo.dailyWaterIntakeGoal;
    this.dailyProteinIntakeGoal = loadUserInfo.dailyProteinIntakeGoal;
    this.dailyExerciseGoal = loadUserInfo.dailyExerciseGoal;
    console.log(this.UserName + ' ' + this.dailyWaterIntakeGoal);

  }
  else console.log('error trying to get current user from storage');

  // check the date - if current date (not time) is same as stored in currentUser local Storage
  // then initialize progress from local storage, otherwise set to zero.
  var todayDate = new Date();
  var today = getDateNumFromDate(todayDate);

  console.log('current date num; ' + today + ' loaded Date Num: ' + loadUserInfo.currentDateNumber);
  if ( today == loadUserInfo.currentDateNumber) {
    // We're on the same day
    console.log('same day');
    this.dailyWaterIntake = loadUserInfo.dailyWaterIntake;
    this.dailyProteinIntake = loadUserInfo.dailyProteinIntake;
    this.dailyExercise = loadUserInfo.dailyExerciseGoal;
  } else {
    console.log('new day');
    // today is a new day - set our daily progress to 0
    this.dailyWaterIntake = 0;
    this.dailyProteinIntake = 0;
    this.dailyExercise = 0;
  }
  this.currentDateNumber = today;
  this.currentDate = new Date();
  this.userData = loadUserInfo.userData;

};

User.prototype.drinkWater = function(amount) {
  this.dailyWaterIntake += 1;
  this.updateLocalStorage();

};

User.prototype.eatProtein = function(amount) {
  this.dailyProteinIntake += amount;
  this.updateLocalStorage();
};

User.prototype.exercise = function(amount) {
  this.updateLocalStorage();
};

function currentUserDataArray () {
  var myArray = [];

  myArray.push(currentUser.currentDateNumber);
  myArray.push(currentUser.userName);
  myArray.push(currentUser.userEmail);
  myArray.push(currentUser.dailyWaterIntakeGoal);
  myArray.push(currentUser.dailyWaterIntake);
  myArray.push(currentUser.dailyProteinIntakeGoal);
  myArray.push(currentUser.dailyProteinIntake);
  myArray.push(currentUser.dailyExerciseGoal);
  myArray.push(currentUser.dailyExercise);
  return myArray;
};

User.prototype.updateUserData = function(){
  // write data to a new key that includes username
  // data is an array of array data. One element for each day
  // each day looks like [daynumber, waterIntake, waterGoal, proteinIntake, proteinGoal, exercise, exerciseGoal]
  // when we write the data, we read in the existing data, check the day number of the last element
  // if it is the same as current date, we pop that off the end of the array, replace it with current and write the whole new array to storage
  // if it is not the same (less than), we push our current user data to end and re-write array
  // if it is less than, someone has changed the clock and we bail

  // var loadUserData = localStorage.getItem('OnTrack-currentUserData');
  var loadUserData = this.userData;
  if (loadUserData.length > 0 ) {
    console.log('we have some data already' + loadUserData);
    //we already have userData stored.

    var lastUserData = loadUserData[loadUserData.length - 1];
    if (lastUserData[0] === currentUser.currentDateNumber){
      console.log('we have a match');
      // we have a match - current date is same as last date stored.
      loadUserData.pop();
      loadUserData.push(currentUserDataArray());
    } else {
      // last data doesn't match, push new data.
      loadUserData.push(currentUserDataArray());
    }

    this.userData = loadUserData;
  } else {
    // no userData stored yet
    console.log('creating userDataArray');
    this.userData.push(currentUserDataArray());
  }

};

User.prototype.updateLocalStorage = function() {
// update userInfo and userData to local storage
  currentUser.updateUserData();
  localStorage.setItem('OnTrack-currentUser',JSON.stringify(currentUser));

};

// one or more functions to get an array of chart data from the localStorage userData.
User.prototype.getChartData = function () {
};

User.prototype.clearCurrentUserStorage = function () {
  if (localStorage.getItem('OnTrack-currentUser')) {
    localStorage.removeItem('OnTrack-currentUser');
  }
};

User.prototype.registerNewUser = function (){
  console.log('registering new user');
  this.userName = document.getElementById('nameInput').value;
  this.userEmail = document.getElementById('emailInput').value;
  this.dailyWaterIntakeGoal = document.getElementById('waterInput').value;
  this.dailyProteinIntakeGoal = document.getElementById('proteinInput').value;
  this.dailyExerciseGoal = document.getElementById('exerciseInput').value;
  // console.log('Localstorage username: ' + JSON.parse(localStorage.getItem('OnTrack-currentUser')).userName + ' entered name: ' + this.userName);
  if (localStorage.getItem('OnTrack-currentUser')) {
    if (JSON.parse(localStorage.getItem('OnTrack-currentUser')).userName == this.userName) {
      console.log('Local Storage for OnTrack User ' + this.userName + ' Exists');
      DlgShow('Sorry ' + this.UserName + ', that name is already in use.', 'Do you want to login as <b>' + name + '<b> or change your user name?');
    } else {
      localStorage.setItem('OnTrack-currentUser',JSON.stringify(currentUser));
      console.log('User: ' + this.UserName + ' water intake: ' + this.dailyWaterIntakeGoal + ' protein intake: ' + this.dailyProteinIntakeGoal + ' exercise: ' + this.dailyExerciseGoal);
      window.open('daily.html', '_self');
    }
  } else {
    localStorage.setItem('OnTrack-currentUser',JSON.stringify(currentUser));
    console.log('User: ' + this.UserName + ' water intake: ' + this.dailyWaterIntakeGoal + ' protein intake: ' + this.dailyProteinIntakeGoal + ' exercise: ' + this.dailyExerciseGoal);
    window.open('daily.html', '_self');
  }
};

User.prototype.updateHTML = function () {
//localStorage
// var retrievedData = localStorage.getItem('OnTrack-currentUser');
// var currentUserTwo = JSON.parse(retrievedData);

  document.getElementById('waterFromStorage').innerHTML = 'Your water intake goal is: ' + this.dailyWaterIntakeGoal + '.';
  document.getElementById('proteinFromStorage').innerHTML = 'Your protein intake goal is: ' + this.dailyProteinIntakeGoal + '.';
  document.getElementById('exerciseFromStorage').innerHTML = 'Your exercise goal is ' + this.dailyExerciseGoal + ' per day.';
  document.getElementById('helloMessage').innerHTML = 'Hello ' + this.userName + '.';
  console.log(this.userName);

  console.log(currentUser);
};
<|endoftext|>


<commit_before>"use strict";

function verif_form_sortie() {
  if (parseInt(document.getElementById('najout').value) >= 1) {
    document.getElementById("formulaire").submit();
  }
}

function submanut(x) {
  var number = document.getElementById("number");

  if ((number.value - x) > 0 ) {
    number.value = (number.value - x).toFixed(2);
  }
}

function number_write(x) {
  var text_box = document.getElementById("number");
  text_box.value = text_box.value + x;
}

function number_clear() {
  const input = document.getElementById("number");
  input.value = "";
  input.setCustomValidity("");
}

/*
 * nom: HTML
 * id: HTML <input>
 * masse_max: float
 * masse_bac: float
 */

function masse_write(nom, id, masse_max, masse_bac) {
  const input = document.getElementById("number");
  const number_value = parseFloat(input.value);
  const masse_reele = number_value - masse_bac;

  if (masse_reele > 0.00) {
    if (number_value <= masse_max) {
      const masseTotale = document.getElementById("massetot");
      masseTotale.textContent = (parseFloat(masseTotale.textContent) + masse_reele).toFixed(2);

      id.value = (parseFloat(id.value) + masse_reele).toFixed(2);
      nom.textContent = (parseFloat(nom.textContent) + masse_reele).toFixed(2);
      input.value = "";

      const nAjout = document.getElementById("najout");
      nAjout.value = parseInt(nAjout.value) + 1;

      number_clear();
    } else {
      input.setCustomValidity("Masse supérieure aux limites de pesée de la balance.");
    }
  } else {
      input.setCustomValidity("Masse entrée inférieure au poids du conteneur ou inférieure ou égale à 0.");
  }
}

function aff_dechets_recycle() {
  var index, len, bname;
  const ref2 = document.getElementById("sel_filiere");
  const tabref2 = ref2.value.split('|');
  ref2.disabled = true;
    const id_filiere = document.getElementById("id_filiere");
  id_filiere.value = tabref2[0];

  const type_dechet = document.getElementById("type_dechet");
  type_dechet.value = tabref2[1];

  const tabtyps = tabref2[1].split('a');
  for (index = 0, len = tabtyps.length; index < len; ++index) {
    console.log(tabtyps[index]);
    console.log(tabref2[1].split('a'));

    bname = tabtyps[index]
    if(parseInt(bname > 0)){
document.getElementById(bname).style.display = "block";
    }
}

}

function masse_write_recycle(nom, id, masse_max, masse_bac) {
    const ref = document.getElementById("sel_filiere");
  const tabref = ref.value.split('|');

  const id_filiere = document.getElementById("id_filiere");
  id_filiere.value = tabref[0];

  const type_dechet = document.getElementById("type_dechet");
  type_dechet.value = tabref[1];

  ref.disabled = true;
  const input = document.getElementById("number");
  const number_value = parseFloat(input.value);
  const masse_reele = number_value - masse_bac;

  if (masse_reele > 0.00) {
    if (number_value <= masse_max) {
      const masseTotale = document.getElementById("massetot");
      masseTotale.textContent = (parseFloat(masseTotale.textContent) + masse_reele).toFixed(2);

      id.value = (parseFloat(id.value) + masse_reele).toFixed(2);
      nom.textContent = (parseFloat(nom.textContent) + masse_reele).toFixed(2);
      input.value = "";

      const nAjout = document.getElementById("najout");
      nAjout.value = parseInt(nAjout.value) + 1;

      number_clear();
    } else {
      input.setCustomValidity("Masse supérieure aux limites de pesée de la balance.");
    }
  } else {
      input.setCustomValidity("Masse entrée inférieure au poids du conteneur ou inférieure ou égale à 0.");
  }
}

function recocom() {
  document.getElementById("commentaire").value =
    document.getElementById("commentaireini").value;
}

function tdechet_add(pesee_max) {
  const ref = document.getElementById("sel_filiere");
  const tabref = ref.value.split('|');

  const id_filiere = document.getElementById("id_filiere");
  id_filiere.value = tabref[0];

  const id_type_dechet = document.getElementById("id_type_dechet");
  id_type_dechet.value = tabref[1];

  const type_dechet = document.getElementById("type_dechet");
  type_dechet.value = tabref[2];

  ref.disabled = true;
  masse_write(document.getElementById(tabref[1]), document.getElementById("m"+tabref[1]), pesee_max, 0.0);
}
<commit_msg>transformation de l'interface de collecte de maniere à encaisser plusieurstypes_dechets_evac sur le meme bon de sortie recycleur et pour un meme recycleur...<commit_after>"use strict";

function verif_form_sortie() {
  if (parseInt(document.getElementById('najout').value) >= 1) {
    document.getElementById("formulaire").submit();
  }
}

function submanut(x) {
  var number = document.getElementById("number");

  if ((number.value - x) > 0 ) {
    number.value = (number.value - x).toFixed(2);
  }
}

function number_write(x) {
  var text_box = document.getElementById("number");
  text_box.value = text_box.value + x;
}

function number_clear() {
  const input = document.getElementById("number");
  input.value = "";
  input.setCustomValidity("");
}

/*
 * nom: HTML
 * id: HTML <input>
 * masse_max: float
 * masse_bac: float
 */

function masse_write(nom, id, masse_max, masse_bac) {
  const input = document.getElementById("number");
  const number_value = parseFloat(input.value);
  const masse_reele = number_value - masse_bac;

  if (masse_reele > 0.00) {
    if (number_value <= masse_max) {
      const masseTotale = document.getElementById("massetot");
      masseTotale.textContent = (parseFloat(masseTotale.textContent) + masse_reele).toFixed(2);

      id.value = (parseFloat(id.value) + masse_reele).toFixed(2);
      nom.textContent = (parseFloat(nom.textContent) + masse_reele).toFixed(2);
      input.value = "";

      const nAjout = document.getElementById("najout");
      nAjout.value = parseInt(nAjout.value) + 1;

      number_clear();
    } else {
      input.setCustomValidity("Masse supérieure aux limites de pesée de la balance.");
    }
  } else {
      input.setCustomValidity("Masse entrée inférieure au poids du conteneur ou inférieure ou égale à 0.");
  }
}

function aff_dechets_recycle() {
  var index, len, bname;
  const ref2 = document.getElementById("sel_filiere");
  const tabref2 = ref2.value.split('|');
  ref2.disabled = true;
    const id_filiere = document.getElementById("id_filiere");
  id_filiere.value = tabref2[0];

  const type_dechet = document.getElementById("type_dechet");
  type_dechet.value = tabref2[1];

  const tabtyps = tabref2[1].split('a');
  for (index = 0, len = tabtyps.length; index < len; ++index) {
    console.log(tabtyps[index]);
    console.log tabtyps;

    bname = tabtyps[index]
    if(parseInt(bname > 0)){
document.getElementById(bname).style.display = "block";
    }
}

}

function masse_write_recycle(nom, id, masse_max, masse_bac) {
    const ref = document.getElementById("sel_filiere");
  const tabref = ref.value.split('|');

  const id_filiere = document.getElementById("id_filiere");
  id_filiere.value = tabref[0];

  const type_dechet = document.getElementById("type_dechet");
  type_dechet.value = tabref[1];

  ref.disabled = true;
  const input = document.getElementById("number");
  const number_value = parseFloat(input.value);
  const masse_reele = number_value - masse_bac;

  if (masse_reele > 0.00) {
    if (number_value <= masse_max) {
      const masseTotale = document.getElementById("massetot");
      masseTotale.textContent = (parseFloat(masseTotale.textContent) + masse_reele).toFixed(2);

      id.value = (parseFloat(id.value) + masse_reele).toFixed(2);
      nom.textContent = (parseFloat(nom.textContent) + masse_reele).toFixed(2);
      input.value = "";

      const nAjout = document.getElementById("najout");
      nAjout.value = parseInt(nAjout.value) + 1;

      number_clear();
    } else {
      input.setCustomValidity("Masse supérieure aux limites de pesée de la balance.");
    }
  } else {
      input.setCustomValidity("Masse entrée inférieure au poids du conteneur ou inférieure ou égale à 0.");
  }
}

function recocom() {
  document.getElementById("commentaire").value =
    document.getElementById("commentaireini").value;
}

function tdechet_add(pesee_max) {
  const ref = document.getElementById("sel_filiere");
  const tabref = ref.value.split('|');

  const id_filiere = document.getElementById("id_filiere");
  id_filiere.value = tabref[0];

  const id_type_dechet = document.getElementById("id_type_dechet");
  id_type_dechet.value = tabref[1];

  const type_dechet = document.getElementById("type_dechet");
  type_dechet.value = tabref[2];

  ref.disabled = true;
  masse_write(document.getElementById(tabref[1]), document.getElementById("m"+tabref[1]), pesee_max, 0.0);
}
<|endoftext|>


<commit_before>function votaciones(){
	this.id_usuario
	this.id_equipo
	this.id_evento
	this.fecha
    this.bool = true

	this.getVotaciones = function(){
        var offset = 0;
        if ( $('#votaciones-list li').length > 0 && this.bool == false) {
            offset = $('#votaciones-list li').length;
        } else {
            $('#votaciones-list').html('').listview('refresh');
        }

		var xhr = new XMLHttpRequest();
        var send = new FormData();
        send.append('id_equipo',this.id_equipo);
        send.append('offset',offset);
		xhr.open('POST', path + 'app/getVotaciones');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send(send);
        $.mobile.loading('show');
        xhr.timeout = 10000;
        xhr.ontimeout = function () {
            $.mobile.loading('hide');
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onerror = function(e){
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onload = function(e){
            //alert(this.response);
        	$.mobile.loading('hide');
        	if(this.status == 200){
        		if(this.response && JSON.parse(this.response)){
        			var json = JSON.parse(this.response);
        			var inc = '';
        			var logo = '';
        			for(var i = 0; i < json.length; i++ ){
                        var date = new Date();
                        var estado = '';
                        date = getFormattedDate(date);

                        if(json[i].logo != null){
                            logo = path + 'equipos/' + json[i].id_equipo + '/logos/' + json[i].logo;
                        } else {
                            logo = "jquerymobile/img-dportes/logo-encuentro.png";
                        }
        				/*inc += "
";
        				inc += "";
        				inc += "
";
        				inc += "
";
        				inc += "

"+localStorage.getItem('nombre_equipo')+"

";
        				inc += "
VS
";
        				inc += "

"+json[i].nombre+"

";
        				inc += "
";
        				inc += "
";
        				inc += "";
        				inc += "
";*/
                        if(date <= json[i].date_final){
                            inc += "
";
                            estado = 'Abierto';
                            redirect = 1;
                        } else {
                            inc += "
";
                            estado = 'Cerrado';
                            redirect = 2;
                        }

                        inc += "";
                        inc += "
";
                        inc += "
";
                        inc += "
"+estado+"
";
                        inc += "

"+localStorage.getItem('nombre_equipo')+"

";
                        inc += "
VS
";
                        inc += "

"+json[i].nombre+"

";
                        inc += "
";
                        inc += "
";
                        inc += "";
                        inc += "
";
        			}

        			$('#votaciones-list').append(inc).listview('refresh');

                    if(json.length >= 5){
                        document.getElementById('vot-more').style.display = "block";
                    } else {
                        document.getElementById('vot-more').style.display = "none";
                    }
        		}
        	}
        };
	}

    this.getJugadoresVotaciones = function(){
        var xhr = new XMLHttpRequest();
        var send = new FormData();
        send.append('id_equipo',this.id_equipo);
        send.append('id_evento',this.id_evento);
        send.append('id_usuario',this.id_usuario);
        xhr.open('POST', path + 'app/getJugadoresVotaciones');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send(send);
        $.mobile.loading('show');
        xhr.timeout = 10000;
        xhr.ontimeout = function () {
            $.mobile.loading('hide');
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onerror = function(e){
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onload = function(e){
            try{
            if(this.status == 200){
                if(this.response && JSON.parse(this.response)){
                    var json = JSON.parse(this.response);
                    var foto = '';
                    var now = +(new Date);
                    var inc = "

Tienes un periodo de 24 horas para votar

";
                    for(var i = 0; i < json.length; i++ ){
                        if(json[i].foto != null){
                            foto = path + 'perfiles/' + json[i].id_usuario + '/' + json[i].foto + '?timestamp=' + now;
                        } else {
                            foto = "jquerymobile/img-dportes/foto.png";
                        }
                        inc += "
";
                        inc += "";
                        inc += "

";
                        inc += "
"+json[i].nombre+"
";
                        inc += "

";
                        inc += "
";
                    }
                    $('#votaciones-jg-list').html(inc).listview('refresh');
                }
            }
            } catch(e){
                alert(e);
            }
        };
    }

    this.setVotaciones = function(){
        var xhr = new XMLHttpRequest();
        var send = new FormData();
        send.append('id_equipo',this.id_equipo);
        send.append('id_evento',this.id_evento);
        send.append('id_usuario',this.id_usuario);
        xhr.open('POST', path + 'app/setVotaciones');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send(send);
        $.mobile.loading('show');
        xhr.timeout = 10000;
        xhr.ontimeout = function () {
            $.mobile.loading('hide');
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onerror = function(e){
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onload = function(e){
            if(this.status == 200){
                alert(this.response);
            }
        };
    }

	this.getPodio = function(){
		var xhr = new XMLHttpRequest();
        var send = new FormData();
        send.append('id_equipo',this.id_equipo);
        send.append('id_evento',this.id_evento);
		xhr.open('POST', path + 'app/getPodio');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send(send);
        $.mobile.loading('show');
        xhr.timeout = 10000;
        xhr.ontimeout = function () {
            $.mobile.loading('hide');
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onerror = function(e){
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onload = function(e){
        	$.mobile.loading('hide');
        	if(this.status == 200){
        		if(this.response && JSON.parse(this.response)){
        			var json = JSON.parse(this.response);
        			var inc = '';
        			var foto = '';
        			for(var i = 0; i < json.length; i++ ){
        				inc += "
";
        				inc += "

";
        				inc += "
";
        				inc += "";
        				inc += "
1º
";
        				inc += "
";
        				inc += "
"+json[i].nombre+"
";
        				inc += "
";
        				inc += "
";
        			}
        		}
        	}
        };
	}
}

function setVotacion(id,nombre){
    navigator.notification.confirm(
        '¿Desea votar por '+nombre+'?',
        function(button){
            if(button == 1){
                alert('acepto');
            }
        },
        'Advertencia',
        'Si,No'
    )
}

function setParametrosPodio(evento,redirect){
    sessionStorage.evento = evento;
    if(redirect == 1){
        $.mobile.navigate("#votaciones", {transition: "fade"});
    } else {
       $.mobile.navigate("#podio", {transition: "fade"});
    }
}<commit_msg>cambio<commit_after>function votaciones(){
	this.id_usuario
	this.id_equipo
	this.id_evento
	this.fecha
    this.bool = true

	this.getVotaciones = function(){
        var offset = 0;
        if ( $('#votaciones-list li').length > 0 && this.bool == false) {
            offset = $('#votaciones-list li').length;
        } else {
            $('#votaciones-list').html('').listview('refresh');
        }

		var xhr = new XMLHttpRequest();
        var send = new FormData();
        send.append('id_equipo',this.id_equipo);
        send.append('offset',offset);
		xhr.open('POST', path + 'app/getVotaciones');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send(send);
        $.mobile.loading('show');
        xhr.timeout = 10000;
        xhr.ontimeout = function () {
            $.mobile.loading('hide');
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onerror = function(e){
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onload = function(e){
            //alert(this.response);
        	$.mobile.loading('hide');
        	if(this.status == 200){
        		if(this.response && JSON.parse(this.response)){
        			var json = JSON.parse(this.response);
        			var inc = '';
        			var logo = '';
        			for(var i = 0; i < json.length; i++ ){
                        var date = new Date();
                        var estado = '';
                        date = getFormattedDate(date);

                        if(json[i].logo != null){
                            logo = path + 'equipos/' + json[i].id_equipo + '/logos/' + json[i].logo;
                        } else {
                            logo = "jquerymobile/img-dportes/logo-encuentro.png";
                        }
        				/*inc += "
";
        				inc += "";
        				inc += "
";
        				inc += "
";
        				inc += "

"+localStorage.getItem('nombre_equipo')+"

";
        				inc += "
VS
";
        				inc += "

"+json[i].nombre+"

";
        				inc += "
";
        				inc += "
";
        				inc += "";
        				inc += "
";*/
                        if(date <= json[i].date_final){
                            inc += "
";
                            estado = 'Abierto';
                            redirect = 1;
                        } else {
                            inc += "
";
                            estado = 'Cerrado';
                            redirect = 2;
                        }

                        inc += "";
                        inc += "
";
                        inc += "
";
                        inc += "
"+estado+"
";
                        inc += "

"+localStorage.getItem('nombre_equipo')+"

";
                        inc += "
VS
";
                        inc += "

"+json[i].nombre+"

";
                        inc += "
";
                        inc += "
";
                        inc += "";
                        inc += "
";
        			}

        			$('#votaciones-list').append(inc).listview('refresh');

                    if(json.length >= 5){
                        document.getElementById('vot-more').style.display = "block";
                    } else {
                        document.getElementById('vot-more').style.display = "none";
                    }
        		}
        	}
        };
	}

    this.getJugadoresVotaciones = function(){
        var xhr = new XMLHttpRequest();
        var send = new FormData();
        send.append('id_equipo',this.id_equipo);
        send.append('id_evento',this.id_evento);
        send.append('id_usuario',this.id_usuario);
        xhr.open('POST', path + 'app/getJugadoresVotaciones');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send(send);
        $.mobile.loading('show');
        xhr.timeout = 10000;
        xhr.ontimeout = function () {
            $.mobile.loading('hide');
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onerror = function(e){
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onload = function(e){
            try{
            if(this.status == 200){
                if(this.response && JSON.parse(this.response)){
                    var json = JSON.parse(this.response);
                    var foto = '';
                    var now = +(new Date);
                    var inc = "

Tienes un periodo de 24 horas para votar

";
                    for(var i = 0; i < json.length; i++ ){
                        if(json[i].foto != null){
                            foto = path + 'perfiles/' + json[i].id_usuario + '/' + json[i].foto + '?timestamp=' + now;
                        } else {
                            foto = "jquerymobile/img-dportes/foto.png";
                        }
                        inc += "
";
                        inc += "";
                        inc += "

";
                        inc += "
"+json[i].nombre+"
";
                        inc += "

";
                        inc += "
";
                    }
                    $('#votaciones-jg-list').html(inc).listview('refresh');
                }
            }
            } catch(e){
                alert(e);
            }
        };
    }

    this.setVotacionUsuario = function(){
        var xhr = new XMLHttpRequest();
        var send = new FormData();
        send.append('id_equipo',this.id_equipo);
        send.append('id_evento',this.id_evento);
        send.append('id_usuario',this.id_usuario);
        send.append('id_votante',localStorage.getItem('id'));
        xhr.open('POST', path + 'app/setVotacionUsuario');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send(send);
        $.mobile.loading('show');
        xhr.timeout = 10000;
        xhr.ontimeout = function () {
            $.mobile.loading('hide');
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onerror = function(e){
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onload = function(e){
            if(this.status == 200){
                alert(this.response);
            }
        };
    }

	this.getPodio = function(){
		var xhr = new XMLHttpRequest();
        var send = new FormData();
        send.append('id_equipo',this.id_equipo);
        send.append('id_evento',this.id_evento);
		xhr.open('POST', path + 'app/getPodio');
        xhr.setRequestHeader('Cache-Control', 'no-cache');
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        xhr.send(send);
        $.mobile.loading('show');
        xhr.timeout = 10000;
        xhr.ontimeout = function () {
            $.mobile.loading('hide');
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onerror = function(e){
            navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK');
        };
        xhr.onload = function(e){
        	$.mobile.loading('hide');
        	if(this.status == 200){
        		if(this.response && JSON.parse(this.response)){
        			var json = JSON.parse(this.response);
        			var inc = '';
        			var foto = '';
        			for(var i = 0; i < json.length; i++ ){
        				inc += "
";
        				inc += "

";
        				inc += "
";
        				inc += "";
        				inc += "
1º
";
        				inc += "
";
        				inc += "
"+json[i].nombre+"
";
        				inc += "
";
        				inc += "
";
        			}
        		}
        	}
        };
	}
}

function setVotacion(id,nombre){
    navigator.notification.confirm(
        '¿Desea votar por '+nombre+'?',
        function(button){
            if(button == 1){
                var vot = new votaciones();
                vot.id_usuario = id;
                vot.id_evento = sessionStorage.getItem('evento');
                vot.id_equipo = localStorage.getItem('equipo');
                vot.setVotacionUsuario();
                delete vot;
            }
        },
        'Aviso',
        'Si,No'
    )
}

function setParametrosPodio(evento,redirect){
    sessionStorage.evento = evento;
    if(redirect == 1){
        $.mobile.navigate("#votaciones", {transition: "fade"});
    } else {
       $.mobile.navigate("#podio", {transition: "fade"});
    }
}<|endoftext|>


<commit_before>var app = angular.module("weatherApp", []);
app.controller("weatherCtrl", function ($scope, $http) {
	$scope.latitude = "getting information";
	$scope.longitude = "getting information";
	$scope.city = "Getting your city";
	!$scope.foundLocation;
	function showLocation(position) {
		$scope.$apply(function () {
			$scope.latitude = position.coords.latitude;
		});

		$scope.$apply(function () {
			$scope.longitude = position.coords.longitude;
		});

		var latitude = position.coords.latitude;
		var longitude = position.coords.longitude;
		var theUrl = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=eda675af27838319581929bf29229f14&l";
		console.log(theUrl);
		$http.get(theUrl)
			.success(function (response) {
				$scope.city = response.name;
				//variables
				var kelvin = response.main.temp;
				var degreesExact = (kelvin * (9 / 5)) - 459.67;
				var degrees = Math.round(degreesExact)
				var weatherType = response.weather[0].main;
				var date = new Date();
				var time = date.getHours;

				console.log(weatherType)
				$scope.temperature = degrees;
				$scope.foundLocation = true;

				if (weatherType = "Clear") {
						$scope.imageName = "clear";
				}
				else {
					$scope.imageName = "cloudy"
				}
				if (time => 18) {
					$scope.dayNight = "night";
				}
				else {
					$scope.dayNight = "day";
				}
				$scope.bgImage = "background-image: url(images/" + $scope.dayNight + "/" + $scope.imageName + ".jpg)";

			});

	}

	function errorHandler(err) {
		if (err.code == 1) {
			alert("Error: Access is denied!");
		} else if (err.code == 2) {
			alert("Error: Position is unavailable!");
		}
	}

	if (navigator.geolocation) {
		// timeout at 60000 milliseconds (60 seconds)
		var options = {
			timeout: 60000
		};
		navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);

	} else {
		alert("Sorry, browser does not support geolocation!");
	}
});<commit_msg>beautify code.<commit_after>var app = angular.module("weatherApp", []);
app.controller("weatherCtrl", function ($scope, $http) {
	$scope.latitude = "getting information";
	$scope.longitude = "getting information";
	$scope.city = "Getting your city";
	!$scope.foundLocation;

	function showLocation(position) {
		$scope.$apply(function () {
			$scope.latitude = position.coords.latitude;
		});

		$scope.$apply(function () {
			$scope.longitude = position.coords.longitude;
		});

		var latitude = position.coords.latitude;
		var longitude = position.coords.longitude;
		var theUrl = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=eda675af27838319581929bf29229f14&l";
		console.log(theUrl);
		$http.get(theUrl)
			.success(function (response) {
				$scope.city = response.name;
				//variables
				var kelvin = response.main.temp;
				var degreesExact = (kelvin * (9 / 5)) - 459.67;
				var degrees = Math.round(degreesExact)
				var weatherType = response.weather[0].main;
				var date = new Date();
				var time = date.getHours;

				console.log(weatherType)
				$scope.temperature = degrees;
				$scope.foundLocation = true;

				if (weatherType = "Clear") {
					$scope.imageName = "clear";
				} else {
					$scope.imageName = "cloudy"
				}
				if (time => 18) {
					$scope.dayNight = "night";
				} else {
					$scope.dayNight = "day";
				}
				$scope.bgImage = "background-image: url(images/" + $scope.dayNight + "/" + $scope.imageName + ".jpg)";

			});
	}

	function errorHandler(err) {
		if (err.code == 1) {
			alert("Error: Access is denied!");
		} else if (err.code == 2) {
			alert("Error: Position is unavailable!");
		}
	}
	if (navigator.geolocation) {
		// timeout at 60000 milliseconds (60 seconds)
		var options = {
			timeout: 60000
		};
		navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);

	} else {
		alert("Sorry, browser does not support geolocation!");
	}
});<|endoftext|>


<commit_before>var app = angular.module("weatherApp", []);
app.controller("weatherCtrl", function ($scope, $http) {
	$scope.latitude = "getting information";
	$scope.longitude = "getting information";
	$scope.city = "Getting your city";
	function showLocation(position) {
		$scope.$apply(function() {
			$scope.latitude = position.coords.latitude;
		});

		$scope.$apply(function() {
			$scope.longitude = position.coords.longitude;
		});

		var latitude = position.coords.latitude;
		var longitude = position.coords.longitude;
		var theUrl = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=eda675af27838319581929bf29229f14&l";
		console.log(theUrl);
		$http.get(theUrl)
			.success(function(response) {
			$scope.city = response.name;
			var kelvin = response.main.temp;
			var degreesExact = (kelvin * (9/5)) - 459.67;
			var degrees = Math.round(degreesExact)
			$scope.temperature = degrees;
		});

	}

	function errorHandler(err) {
		if (err.code == 1) {
			alert("Error: Access is denied!");
		} else if (err.code == 2) {
			alert("Error: Position is unavailable!");
		}
	}

		if (navigator.geolocation) {
			// timeout at 60000 milliseconds (60 seconds)
			var options = {
				timeout: 60000
			};
			navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);

		} else {
			alert("Sorry, browser does not support geolocation!");
		}
});
<commit_msg>beautify<commit_after>var app = angular.module("weatherApp", []);
app.controller("weatherCtrl", function ($scope, $http) {
	$scope.latitude = "getting information";
	$scope.longitude = "getting information";
	$scope.city = "Getting your city";

	function showLocation(position) {
		$scope.$apply(function () {
			$scope.latitude = position.coords.latitude;
		});

		$scope.$apply(function () {
			$scope.longitude = position.coords.longitude;
		});

		var latitude = position.coords.latitude;
		var longitude = position.coords.longitude;
		var theUrl = "http://api.openweathermap.org/data/2.5/weather?lat=" + latitude + "&lon=" + longitude + "&APPID=eda675af27838319581929bf29229f14&l";
		console.log(theUrl);
		$http.get(theUrl)
			.success(function (response) {
				$scope.city = response.name;
				var kelvin = response.main.temp;
				var degreesExact = (kelvin * (9 / 5)) - 459.67;
				var degrees = Math.round(degreesExact)
				$scope.temperature = degrees;
			});

	}

	function errorHandler(err) {
		if (err.code == 1) {
			alert("Error: Access is denied!");
		} else if (err.code == 2) {
			alert("Error: Position is unavailable!");
		}
	}

	if (navigator.geolocation) {
		// timeout at 60000 milliseconds (60 seconds)
		var options = {
			timeout: 60000
		};
		navigator.geolocation.getCurrentPosition(showLocation, errorHandler, options);

	} else {
		alert("Sorry, browser does not support geolocation!");
	}
});<|endoftext|>


<commit_before>var moment = require('moment')
var prettyBytes = require('pretty-bytes')

// HTML elements
var $body = $('body')
var $progressBar = $('#progressBar')
var $streamedFileName = $('#streamedFileName')
var $numPeers = $('#numPeers')
var $downloaded = $('#downloaded')
var $total = $('#total')
var $remaining = $('#remaining')
var $uploadSpeed = $('#uploadSpeed')
var $downloadSpeed = $('#downloadSpeed')

var announceList = [
['udp://tracker.openbittorrent.com:80'],
['udp://tracker.internetwarriors.net:1337'],
['udp://tracker.leechers-paradise.org:6969'],
['udp://tracker.coppersurfer.tk:6969'],
['udp://exodus.desync.com:6969'],
['wss://tracker.webtorrent.io'],
['wss://tracker.btorrent.xyz'],
['wss://tracker.openwebtorrent.com'],
['wss://tracker.fastcast.nz']
]

global.WEBTORRENT_ANNOUNCE = announceList
.map(function (arr) {
	return arr[0]
})
.filter(function (url) {
	return url.indexOf('wss://') === 0 || url.indexOf('ws://') === 0
})

var client = new WebTorrent()

client.on('error', function(err) {
	console.error('ERROR: ' + err.message)
})

// Download by form input
$('form').submit(function(e) {
	e.preventDefault() // Prevent page refresh

	var torrentId = $('form input[name=torrentId]').val()

	if (torrentId.length > 0)
		downloadTorrent(torrentId)
})

// Download by URL hash
onHashChange()
window.addEventListener('hashchange', onHashChange)
function onHashChange () {
	var hash = decodeURIComponent(window.location.hash.substring(1)).trim()
	if (hash !== '') downloadTorrent(hash)
}

function downloadTorrent(torrentId) {
	console.log('Downloading torrent from ' + torrentId)
	client.add(torrentId, onTorrent)
}

function onTorrent(torrent) {
	torrent.on('warning', console.log)
	torrent.on('error', console.log)

	console.log('Got torrent metadata!')

	// Find largest file
	var largestFile = torrent.files[0]
	for (var i = 1; i < torrent.files.length; i++) {
		if (torrent.files[i].length > largestFile.length)
			largestFile = torrent.files[i]
	}

	// Display name of the file being streamed
	$streamedFileName.html(largestFile.name)

	// Update clipboard share url
	$('#share-url').val('https://ferrolho.github.io/magnet-player/#' + torrent.infoHash);

	// Stream the file in the browser
	largestFile.appendTo('#output')

	// hide magnet input
	$('#magnet-input').slideUp()

	// show player
	$('#hero').slideDown()

	// Trigger statistics refresh
	torrent.on('done', onDone)
	setInterval(onProgress, 500)
	onProgress()

	// Statistics
	function onProgress () {
		// Peers
		$numPeers.html(torrent.numPeers + (torrent.numPeers === 1 ? ' peer' : ' peers'))

		// Progress
		var percent = Math.round(torrent.progress * 100 * 100) / 100
		$progressBar.width(percent + '%')
		$downloaded.html(prettyBytes(torrent.downloaded))
		$total.html(prettyBytes(torrent.length))

		// Remaining time
		var remaining
		if (torrent.done) {
			remaining = 'Done'
		} else {
			remaining = moment.duration(torrent.timeRemaining / 1000, 'seconds').humanize()
			remaining = remaining[0].toUpperCase() + remaining.substring(1) + ' remaining'
		}
		$remaining.html(remaining)

		// Speed rates
		$downloadSpeed.html(prettyBytes(torrent.downloadSpeed) + '/s')
		$uploadSpeed.html(prettyBytes(torrent.uploadSpeed) + '/s')
	}

	function onDone () {
		$body.addClass('is-seed')
		onProgress()
	}
}
<commit_msg>Update webtorrent.js<commit_after>var moment = require('moment')
var prettyBytes = require('pretty-bytes')

// HTML elements
var $body = $('body')
var $progressBar = $('#progressBar')
var $streamedFileName = $('#streamedFileName')
var $numPeers = $('#numPeers')
var $downloaded = $('#downloaded')
var $total = $('#total')
var $remaining = $('#remaining')
var $uploadSpeed = $('#uploadSpeed')
var $downloadSpeed = $('#downloadSpeed')

var announceList = [
['udp://tracker.openbittorrent.com:80'],
['udp://tracker.internetwarriors.net:1337'],
['udp://tracker.leechers-paradise.org:6969'],
['udp://tracker.coppersurfer.tk:6969'],
['udp://exodus.desync.com:6969'],
['wss://tracker.webtorrent.io'],
['wss://tracker.btorrent.xyz'],
['wss://tracker.openwebtorrent.com'],
['wss://tracker.fastcast.nz']
]

global.WEBTORRENT_ANNOUNCE = announceList
.map(function (arr) {
	return arr[0]
})
.filter(function (url) {
	return url.indexOf('wss://') === 0 || url.indexOf('ws://') === 0
})

var client = new WebTorrent()

client.on('error', function(err) {
	console.error('ERROR: ' + err.message)
})

// Download by form input
$('form').submit(function(e) {
	e.preventDefault() // Prevent page refresh

	var torrentId = $('form input[name=torrentId]').val()

	if (torrentId.length > 0)
		downloadTorrent(torrentId)
})

// Download by URL hash
onHashChange()
window.addEventListener('hashchange', onHashChange)
function onHashChange () {
	var hash = decodeURIComponent(window.location.hash.substring(1)).trim()
	if (hash !== '') downloadTorrent(hash)
}

function downloadTorrent(torrentId) {
	console.log('Downloading torrent from ' + torrentId)
	client.add(torrentId, onTorrent)
}

function onTorrent(torrent) {
	torrent.on('warning', console.log)
	torrent.on('error', console.log)

	console.log('Got torrent metadata!')

	// Find largest file
	var largestFile = torrent.files[0]
	for (var i = 1; i < torrent.files.length; i++) {
		if (torrent.files[i].length > largestFile.length)
			largestFile = torrent.files[i]
	}

	// Display name of the file being streamed
	$streamedFileName.html(largestFile.name)

	// Update clipboard share url
	$('#share-url').val('https://webtotr.github.io/magnet-player/#' + torrent.infoHash);

	// Stream the file in the browser
	largestFile.appendTo('#output')

	// hide magnet input
	$('#magnet-input').slideUp()

	// show player
	$('#hero').slideDown()

	// Trigger statistics refresh
	torrent.on('done', onDone)
	setInterval(onProgress, 500)
	onProgress()

	// Statistics
	function onProgress () {
		// Peers
		$numPeers.html(torrent.numPeers + (torrent.numPeers === 1 ? ' peer' : ' peers'))

		// Progress
		var percent = Math.round(torrent.progress * 100 * 100) / 100
		$progressBar.width(percent + '%')
		$downloaded.html(prettyBytes(torrent.downloaded))
		$total.html(prettyBytes(torrent.length))

		// Remaining time
		var remaining
		if (torrent.done) {
			remaining = 'Done'
		} else {
			remaining = moment.duration(torrent.timeRemaining / 1000, 'seconds').humanize()
			remaining = remaining[0].toUpperCase() + remaining.substring(1) + ' remaining'
		}
		$remaining.html(remaining)

		// Speed rates
		$downloadSpeed.html(prettyBytes(torrent.downloadSpeed) + '/s')
		$uploadSpeed.html(prettyBytes(torrent.uploadSpeed) + '/s')
	}

	function onDone () {
		$body.addClass('is-seed')
		onProgress()
	}
}
<|endoftext|>