<commit_before>// The board is in top-down view style, referenced as [X][Y].
/*
    0   1   2   3   4   5   6
0   x   -   x       x       x
1   |   1   |
2   x   -   x       x       x
3
4   x       x       x       x
*/

// Constants
var BOX_P1 = 'R';
var BOX_P2 = 'B';
var DOT = '•';
var LINE = '1';

// Vendor Functions
Array.prototype.getUnique = function () {
    // Stack Overflow: http://stackoverflow.com/a/1961068
    var u = {}, a = [];

    for(var i = 0, l = this.length; i < l; ++i){
        if(u.hasOwnProperty(this[i])) {
            continue;
        }

        a.push(this[i]);
        u[this[i]] = 1;
    }

    return a;
};

Array.prototype.randomItem = function () {
    // Stack Overflow: http://stackoverflow.com/a/5915123
    return this[Math.floor(Math.random()*this.length)];
};

Array.prototype.copy = function () {
    // Stack Overflow: http://stackoverflow.com/a/7486130
    return this.slice(0);
};

// Functions
function Board (x, y) {
    // Creates a board with the specified number of dots

    x = x * 2 + 1;
    y = y * 2 + 1;

    var board = new Array(y);
    var rowEven = new Array(x);
    var rowOdd = new Array(x);

    for (var i = 0; i < rowEven.length; i += 2) {
        rowEven[i] = DOT;
    }

    for (var k = 0; k < y; k+= 2) {
        board[k] = rowEven.copy();
    }

    for (var j = 1; j < y; j += 2) {
        board[j] = rowOdd.copy();
    }

    return board;
}

function IsBox (board, x, y) {
    // Given x and y coordinates, find if cardinal neighbors are connected

    if (board[y+1][x] && board[y-1][x] && board[y][x+1] && board[y][x-1])
        return true;
    else
        return false;
}

function CheckBoardForNewBoxes (board, alliance) {
    // For each box coordinate, color the box in if it's complete

    var moveMade = false;

    for (var i = 1; i < board.length; i += 2) {
        for (var j = 1; j < board[0].length; j += 2) {
            if (!board[i][j] && IsBox(board, j, i)) {
                board[i][j] = alliance;
                moveMade = true;
            }
        }
    }

    return moveMade;
}

function Connect (board, x, y, alliance) {
    // Draws a line at coordinates [x, y]

    board[y][x] = LINE;
    return CheckBoardForNewBoxes(board, alliance);
}

function IsConnected (board, x1, y1, x2, y2) {
    // Returns whether a line has been drawn between two points

    var midx = (x1 + x2) / 2;
    var midy = (y1 + y2) / 2;

    return board[midy][midx];
}

function FindAllAvailableMoves (board) {
    // Returns a list of coordinates of all unconnected dot pairs

    var moves = [];

    for (var i = 1; i < board[0].length; i += 2) {
        for (var j = 0; j < board.length; j += 2) {
            if (!board[j][i])
                moves.push([i,j]);
        }
    }

	for (var i = 0; i < board[0].length; i += 2) {
        for (var j = 1; j < board.length; j += 2) {
            if (!board[j][i])
                moves.push([i,j]);
        }
    }

    return moves;
}

function FindNeighbors (board, x, y) {
    // Given a dot at [x,y], return a list of unconnected neighboring dot coordinates

    var neighbors = [];
    var maxIndexX = board.length--;
    var maxIndexY = board[0].length--;

    if (x + 2 <= maxIndexX) {
        neighbors.push([x+2, y]);
        if (y + 2 <= maxIndexY) neighbors.push([x+2, y+2]);
        if (y - 2 >= 0) neighbors.push([x+2, y-2]);
    }

    if (x - 2 >= 0) {
        neighbors.push([x-2, y]);
        if (y + 2 <= maxIndexY) neighbors.push([x-2, y+2]);
        if (y - 2 >= 0) neighbors.push([x-2, y-2]);
    }

    return neighbors;
}

function FindAvailableNeighbors (board, x, y) {
    // Given a dot at [x,y], return a list of unconnected neighboring dot coordinates

    var neighbors = FindNeighbors(board, x, y);
    var validNeighbors = [];

    for (var i = 0; i < neighbors.length; i++) {
        var nx = neighbors[i][0];
        var ny = neighbors[i][1];

        if (!IsConnected(board, x, y, nx, ny))
            validNeighbors.push([nx,ny]);
    }

    return validNeighbors;
}

function CalculateScore (board) {
    // Returns a number based on the current board's score

    var scores = [0, 0];

    for (var i = 1; i < board[0].length; i += 2) {
        for (var j = 1; j < board.length; j += 2) {
            if (board[j][i] == BOX_P1) scores[0]++;
            else if (board[j][i] == BOX_P2) scores[1]++;
        }
    }

    return scores;
}

function AIRandom (board, alliance) {
    // Given a choice of all available moves, this AI takes a random one

    var moves = FindAllAvailableMoves(board);
    var move = moves.randomItem();
    return Connect(board, move[0], move[1]);
}

function AIGreedy (board, alliance) {
    // This AI will move at random unless it finds a move that will increase its score

    var moves = FindAllAvailableMoves(board);
    var score = CalculateScore(board);
    var moveMade = false;
	var boxMade = false;

    for(var i = 0; i < moves.length; i++) {
        var newBoard = board.copy();
        var move = moves[i];

        Connect(newBoard, move[0], move[1]);

        var newScore = CalculateScore(newBoard);

        if (newScore > score) {
            boxMade = Connect(board, move[0], move[1]);
            moveMade = true;
            break;
        }
    }

    if (!moveMade) boxMade = AIRandom(board, alliance);

	return boxMade;
}

function AIMove (board, alliance, moveAlgorithm) {
	// Continue making moves until AI's turn is up
	var notDone = false;
	do {
		moveAlgorithm(board, alliance);
	} while (notDone)
}<commit_msg>Fixed AI move glitches<commit_after>// The board is in top-down view style, referenced as [X][Y].
/*
    0   1   2   3   4   5   6
0   x   -   x       x       x
1   |   1   |
2   x   -   x       x       x
3
4   x       x       x       x
*/

// Constants
var BOX_P1 = 'R';
var BOX_P2 = 'B';
var DOT = '•';
var LINE = '1';

// Vendor Functions
Array.prototype.getUnique = function () {
    // Stack Overflow: http://stackoverflow.com/a/1961068
    var u = {}, a = [];

    for(var i = 0, l = this.length; i < l; ++i){
        if(u.hasOwnProperty(this[i])) {
            continue;
        }

        a.push(this[i]);
        u[this[i]] = 1;
    }

    return a;
};

Array.prototype.randomItem = function () {
    // Stack Overflow: http://stackoverflow.com/a/5915123
    return this[Math.floor(Math.random()*this.length)];
};

Array.prototype.copy = function () {
    // Stack Overflow: http://stackoverflow.com/a/7486130
    return this.slice(0);
};

// Functions
function Board (x, y) {
    // Creates a board with the specified number of dots

    x = x * 2 + 1;
    y = y * 2 + 1;

    var board = new Array(y);
    var rowEven = new Array(x);
    var rowOdd = new Array(x);

    for (var i = 0; i < rowEven.length; i += 2) {
        rowEven[i] = DOT;
    }

    for (var k = 0; k < y; k+= 2) {
        board[k] = rowEven.copy();
    }

    for (var j = 1; j < y; j += 2) {
        board[j] = rowOdd.copy();
    }

    return board;
}

function IsBox (board, x, y) {
    // Given x and y coordinates, find if cardinal neighbors are connected

    if (board[y+1][x] && board[y-1][x] && board[y][x+1] && board[y][x-1])
        return true;
    else
        return false;
}

function CheckBoardForNewBoxes (board, alliance) {
    // For each box coordinate, color the box in if it's complete

    var moveMade = false;

    for (var i = 1; i < board.length; i += 2) {
        for (var j = 1; j < board[0].length; j += 2) {
            if (!board[i][j] && IsBox(board, j, i)) {
                board[i][j] = alliance;
                moveMade = true;
            }
        }
    }

    return moveMade;
}

function Connect (board, x, y, alliance) {
    // Draws a line at coordinates [x, y]

    board[y][x] = LINE;
    return CheckBoardForNewBoxes(board, alliance);
}

function IsConnected (board, x1, y1, x2, y2) {
    // Returns whether a line has been drawn between two points

    var midx = (x1 + x2) / 2;
    var midy = (y1 + y2) / 2;

    return board[midy][midx];
}

function FindAllAvailableMoves (board) {
    // Returns a list of coordinates of all unconnected dot pairs

    var moves = [];

    for (var i = 1; i < board[0].length; i += 2) {
        for (var j = 0; j < board.length; j += 2) {
            if (!board[j][i])
                moves.push([i,j]);
        }
    }

	for (var k = 0; k < board[0].length; k += 2) {
        for (var l = 1; l < board.length; l += 2) {
            if (!board[l][k])
                moves.push([k,l]);
        }
    }

    return moves;
}

function FindNeighbors (board, x, y) {
    // Given a dot at [x,y], return a list of unconnected neighboring dot coordinates

    var neighbors = [];
    var maxIndexX = board.length--;
    var maxIndexY = board[0].length--;

    if (x + 2 <= maxIndexX) {
        neighbors.push([x+2, y]);
        if (y + 2 <= maxIndexY) neighbors.push([x+2, y+2]);
        if (y - 2 >= 0) neighbors.push([x+2, y-2]);
    }

    if (x - 2 >= 0) {
        neighbors.push([x-2, y]);
        if (y + 2 <= maxIndexY) neighbors.push([x-2, y+2]);
        if (y - 2 >= 0) neighbors.push([x-2, y-2]);
    }

    return neighbors;
}

function FindAvailableNeighbors (board, x, y) {
    // Given a dot at [x,y], return a list of unconnected neighboring dot coordinates

    var neighbors = FindNeighbors(board, x, y);
    var validNeighbors = [];

    for (var i = 0; i < neighbors.length; i++) {
        var nx = neighbors[i][0];
        var ny = neighbors[i][1];

        if (!IsConnected(board, x, y, nx, ny))
            validNeighbors.push([nx,ny]);
    }

    return validNeighbors;
}

function CalculateScore (board) {
    // Returns a number based on the current board's score

    var scores = [0, 0];

    for (var i = 1; i < board[0].length; i += 2) {
        for (var j = 1; j < board.length; j += 2) {
            if (board[j][i] == BOX_P1) scores[0]++;
            else if (board[j][i] == BOX_P2) scores[1]++;
        }
    }

    return scores;
}

function AIRandom (board, alliance) {
    // Given a choice of all available moves, this AI takes a random one

    var moves = FindAllAvailableMoves(board);
    var move = moves.randomItem();
    return Connect(board, move[0], move[1], alliance);
}

function AIGreedy (board, alliance) {
    // This AI will move at random unless it finds a move that will increase its score

    var moves = FindAllAvailableMoves(board);
    var score = CalculateScore(board);
    var moveMade = false;
	var boxMade = false;

    for(var i = 0; i < moves.length; i++) {
        var newBoard = board.copy();
        var move = moves[i];

        Connect(newBoard, move[0], move[1]);

        var newScore = CalculateScore(newBoard);

        if (newScore > score) {
            boxMade = Connect(board, move[0], move[1], alliance);
            moveMade = true;
            break;
        }
    }

    if (!moveMade) boxMade = AIRandom(board, alliance);

	return boxMade;
}

function AIMove (board, alliance, moveAlgorithm) {
	// Continue making moves until AI's turn is up
	var notDone = false;
	do {
		notDone = moveAlgorithm(board, alliance);
	} while (notDone);
}<|endoftext|>


<commit_before>const solutions = 'https://api.github.com/repos/Aboisier/Polyalgo/contents/Documentation';

var writeChallenges = function(data, state, id)
{
	if(state == "success")
	{
		//('#' + id).append('
');
		$.each(data, function (index, val) {

			if(val.name != undefined)
			{
				str = '
' + val.name + '
'

				$('#' + id).append(str);
			}
		});
		//('#' + id).append('
');
	}

}

var writeCategories = function (data, state)
{
	if(state == "success")
	{
		$.each(data, function (index, val) {

			if(val.name != undefined)
			{
				var name = val.name.replace(/\s+/g, '');

				str = '

' +
						'
 '+ val.name + '
' +
						'

';
				$('#competitions').append(str);

				$.getJSON(val.url, function(data, state) { writeChallenges(data, state, name); });
			}
		});
	}
}

$.getJSON('https://api.github.com/repos/Aboisier/Polyalgo/contents/Documentation', writeCategories);
<commit_msg>Documentation du code<commit_after>// Le lien vers le dossier contenant tous les compétitions et solutions.
const dir = 'https://api.github.com/repos/Aboisier/Polyalgo/contents/Documentation';

/**
 * Écrit le nom de chaque challenge d'une catégorie avec un lien vers
 * le dossier contenant l'énoncé et les solutions.
 * @param {JSON} data - La réponse JSON de call de l'api de GitHub.
 * @param {state} state - L'état de la réponse du call de l'api de GitHub.
 * @param {string} id - L'ID du div dans lequel ajouter les challenges.
 */
var writeChallenges = function(data, state, id)
{
	if(state == "success")
	{
		$.each(data, function (index, val) {

			if(val.name != undefined)
			{
				str = '
' + val.name + '
'

				$('#' + id).append(str);
			}
		});
	}
}

/**
 * Génère le html de chaque catégorie de challenge. Pour chaque dossier
 * contenu dans  le dossier Documentation du repo, une catégorie est créée.
 * @param {JSON} data - La réponse JSON de call de l'api de GitHub.
 * @param {state} state - L'état de la réponse du call de l'api de GitHub.
 */
var writeCategories = function (data, state)
{
	if(state == "success")
	{
		$.each(data, function (index, val) {

			if(val.name != undefined)
			{
				var name = val.name.replace(/\s+/g, '');

				str = '

' +
						'
 '+ val.name + '
' +
						'

';
				$('#competitions').append(str);

				$.getJSON(val.url, function(data, state) { writeChallenges(data, state, name); });
			}
		});
	}
}

// Génère le code de tous les challenges solutions de la page algorithmes.
$.getJSON(dir, writeCategories);
<|endoftext|>


<commit_before>/**
* JavaScript project for accessing and normalizing the accelerometer and gyroscope data on mobile devices
*
* @author Doruk Eker <dorukeker@gmail.com>
* @copyright 2014 Doruk Eker <http://dorukeker.com>
* @version 0.0.1
* @license MIT License | http://opensource.org/licenses/MIT
*/

/*-------------------------------------------------------*/
/* PULBIC VARIABLES */

var gn = new Object();

/*-------------------------------------------------------*/
/* PRIVATE VARIABLES */

var gn_interval = null;					// Timer to return values
var gn_isCalibrating = false;			// Flag if calibrating
var gn_calibrationValues = new Array();	// Array to store values when calculating alpha offset
var gn_calibrationValue = 0;			// Alpha offset value
var gn_gravityCoefficient = 0;			// Coefficient to normalze gravity related values
var gn_isready = false;					// Flag if event listeners are added

gn.log = null;						// Function to callback on error. There is no default value. It can only be set by the user on gn.init()

/* OPTIONS */
gn._frequency 				= 50;		// Frequency for the return data in milliseconds
gn._gravityNormalized		= true;		// Flag if to normalize gravity values
gn._directionAbsolute	= false;	// Flag if to return absolute or relative alpha values
gn._decimalCount			= 2;		// Number of digits after the decimals point for the return values

gn._values = {
	do:{
		alpha:0,
		beta:0,
		gamma:0,
		absolute:false
	},
	dm:{
		x:0,
		y:0,
		z:0,
		gx:0,
		gy:0,
		gz:0,
		alpha:0,
		beta:0,
		gamma:0
	}
}

/*-------------------------------------------------------*/
/* PUBLIC FUNCTIONS */

/*
*
* Initialize the object
*
* @param object options - values are as follows. If set in the init function they overwrite the default option values
* @param int options.frequency
* @param boolean options.gravityNormalized
* @param boolean options.directionAbsolute
*
*/
gn.init = function(options){

	// Assign options that are passed with the init function
	if(options && options.frequency) gn._frequency = options.frequency;
	if(options && options.gravityNormalized) gn._gravityNormalized = options.gravityNormalized;
	if(options && options.directionAbsolute) gn._directionAbsolute = options.directionAbsolute;
	if(options && options.decimalCount) gn._decimalCount = options.decimalCount;

	try{
		calibrate();
		gn_setupListeners();
	} catch(err){
		onError(err);
	}

	gn_isready = true;
}

/*
*
* Stops all the tracking and listening on the window objects
*
*/
gn.end = function(){
	try{
		gn.stop();
		window.removeEventListener('deviceorientation',onDeviceOrientationHandler);
		window.removeEventListener('devicemotion',onDeviceMotionHandler);
		gn_isready = false;
	} catch(err){
		onError(err);
	}
}

/*
*
* Starts tracking the values
*
* @param function callback - Callback function to read the values
*
*/
gn.start = function(callback){
	if(!gn_isready){
		onError({message:'GyroNorm is not initialized. First call gn.init()' , code:1});
		return;
	}
	calibrate();
	gn_interval = setInterval(function(){
		callback(snapShot());
	},gn._frequency);
}

/*
*
* Stops tracking the values
*
*/
gn.stop = function(){
	if(gn_interval){
		clearInterval(gn_interval);
	}
}

/*
*
* Toggles if to normalize gravity related values
*
* @param boolean flag
*
*/
gn.normalizeGravity = function(flag){
	gn._gravityNormalized = (flag)?true:false;
}

/*
*
* Toggles if to give absolute orientation values
*
* @param boolean flag
*
*/
gn.giveAbsoluteOrientation = function(flag){
	gn._directionAbsolute = (flag)?true:false;
}

/*
*
* Sets the current alpha value as "0"
*
*/
gn.setHeadDirection = function(){
	gn._directionAbsolute = false;
	calibrate();
}

/*-------------------------------------------------------*/
/* PRIVATE FUNCTIONS */

/*
*
* Starts listening to the eventa on the window object
*
*/
function gn_setupListeners(){
	window.addEventListener('deviceorientation',onDeviceOrientationHandler,true);
	window.addEventListener('devicemotion',onDeviceMotionHandler,true);
	window.addEventListener('compassneedscalibration',onCompassNeedsCalibrationHandler,true);
}

/*
*
* Starts listening to orientation event on the window object
*
*/
function onError(err){
	if(gn.log){
		if(typeof(err) == 'string'){
			err = {message:err , code:0}
		}
		gn.log(err);
	}
}

/*
*
* Gets called only in calibration mode. Gets the mean value of the alpha deviations. And stores it as calibration.
*
*/
function updateCalibration(){
	if(gn_calibrationValues.length > 19){
		gn_calibrationValues.splice(0,5);
		var total = 0;
		for(var i = 0 ; i < gn_calibrationValues.length ; i++){
			total += gn_calibrationValues[i];
		}
		gn_calibrationValue = parseInt(total / 15);
		gn_isCalibrating = false;
	}
}

/*
*
* Handler for deviceo orientation event
*
*/
function onDeviceOrientationHandler(event){
	// Check if values are returned correctly
	if(!event.alpha && !event.beta && !event.gamma){
		onError({message:'Device orientation event values are not returned as expected.' , code:2 });
		window.removeEventListener('deviceorientation',onDeviceOrientationHandler);
	}

	// For the first 20 values add the alpha to calibration list
	if(gn_isCalibrating){
		gn_calibrationValues.push(event.alpha);
		updateCalibration();
		return;
	}

	// Assign event values to the object values
	gn._values.do.alpha = event.alpha;
	gn._values.do.beta = event.beta;
	gn._values.do.gamma = event.gamma;
	gn._values.do.absolute = event.absolute;
}

/*
*
* Handler for device motion event
*
*/
function onDeviceMotionHandler(event){

	// Assign gravity coefficient. Assumes that the user is holding the phot up right facing the screen.
	// If you cannot make this assumption because of the usecase, disable the normalization via changing the option 'gravityNormalized' value to false
	if(gn_gravityCoefficient == 0){
		gn_gravityCoefficient = (event.accelerationIncludingGravity.z < 0)?1:-1;
		return;
	}

	// Assign event values to the object values
	gn._values.dm.x = event.acceleration.x;
	gn._values.dm.y = event.acceleration.y;
	gn._values.dm.z = event.acceleration.z;

	gn._values.dm.gx = event.accelerationIncludingGravity.x;
	gn._values.dm.gy = event.accelerationIncludingGravity.y;
	gn._values.dm.gz = event.accelerationIncludingGravity.z;

	gn._values.dm.alpha = event.rotationRate.alpha;
	gn._values.dm.beta = event.rotationRate.beta;
	gn._values.dm.gamma = event.rotationRate.gamma;
}

/*
*
* Handler for device motion event
*
*/
function onCompassNeedsCalibrationHandler(event){

	onError({message:'Compass is not calibrated.' , code:3});

}

/*
*
* Utility function to round with digits after the decimal point
*
* @param float number - the original number to round
*
*/
function rnd(number){
	return Math.round(number * Math.pow(10 , gn._decimalCount)) / Math.pow(10 , gn._decimalCount);
}

/*
*
* Starts calibration
*
*/
function calibrate(){
	gn_isCalibrating = true;
	gn_calibrationValues = new Array();
}

/*
*
* Takes a snapshot of the values
*
*/
function snapShot(){

	// Send absolute or relative alpha. Default is relative.
	var alphaToSend = 0;
	if(!gn._directionAbsolute){
		alphaToSend = gn._values.do.alpha - gn_calibrationValue;
		alphaToSend = (alphaToSend < 0)?(360 - Math.abs(alphaToSend)):alphaToSend;
	} else {
		alphaToSend = gn._values.do.alpha;
	}

	var snapShot = {
		do:{
			alpha:rnd(alphaToSend),
			beta:rnd(gn._values.do.beta),
			gamma:rnd(gn._values.do.gamma),
			absolute:gn._values.do.absolute
		},
		dm:{
			x:rnd(gn._values.dm.x),
			y:rnd(gn._values.dm.y),
			z:rnd(gn._values.dm.z),
			gx:rnd(gn._values.dm.gx),
			gy:rnd(gn._values.dm.gy),
			gz:rnd(gn._values.dm.gz),
			alpha:rnd(gn._values.dm.alpha),
			beta:rnd(gn._values.dm.beta),
			gamma:rnd(gn._values.dm.gamma)
		}
	};

	// Normalize gravity
	if(gn._gravityNormalized){
		snapShot.dm.gx *= gn_gravityCoefficient;
		snapShot.dm.gy *= gn_gravityCoefficient;
		snapShot.dm.gz *= gn_gravityCoefficient;
	}

	return snapShot;
}
<commit_msg>Update name of the public function<commit_after>/**
* JavaScript project for accessing and normalizing the accelerometer and gyroscope data on mobile devices
*
* @author Doruk Eker <dorukeker@gmail.com>
* @copyright 2014 Doruk Eker <http://dorukeker.com>
* @version 0.0.1
* @license MIT License | http://opensource.org/licenses/MIT
*/

/*-------------------------------------------------------*/
/* PULBIC VARIABLES */

var gn = new Object();

/*-------------------------------------------------------*/
/* PRIVATE VARIABLES */

var gn_interval = null;					// Timer to return values
var gn_isCalibrating = false;			// Flag if calibrating
var gn_calibrationValues = new Array();	// Array to store values when calculating alpha offset
var gn_calibrationValue = 0;			// Alpha offset value
var gn_gravityCoefficient = 0;			// Coefficient to normalze gravity related values
var gn_isready = false;					// Flag if event listeners are added

gn.log = null;						// Function to callback on error. There is no default value. It can only be set by the user on gn.init()

/* OPTIONS */
gn._frequency 				= 50;		// Frequency for the return data in milliseconds
gn._gravityNormalized		= true;		// Flag if to normalize gravity values
gn._directionAbsolute	= false;	// Flag if to return absolute or relative alpha values
gn._decimalCount			= 2;		// Number of digits after the decimals point for the return values

gn._values = {
	do:{
		alpha:0,
		beta:0,
		gamma:0,
		absolute:false
	},
	dm:{
		x:0,
		y:0,
		z:0,
		gx:0,
		gy:0,
		gz:0,
		alpha:0,
		beta:0,
		gamma:0
	}
}

/*-------------------------------------------------------*/
/* PUBLIC FUNCTIONS */

/*
*
* Initialize the object
*
* @param object options - values are as follows. If set in the init function they overwrite the default option values
* @param int options.frequency
* @param boolean options.gravityNormalized
* @param boolean options.directionAbsolute
*
*/
gn.init = function(options){

	// Assign options that are passed with the init function
	if(options && options.frequency) gn._frequency = options.frequency;
	if(options && options.gravityNormalized) gn._gravityNormalized = options.gravityNormalized;
	if(options && options.directionAbsolute) gn._directionAbsolute = options.directionAbsolute;
	if(options && options.decimalCount) gn._decimalCount = options.decimalCount;

	try{
		calibrate();
		gn_setupListeners();
	} catch(err){
		onError(err);
	}

	gn_isready = true;
}

/*
*
* Stops all the tracking and listening on the window objects
*
*/
gn.end = function(){
	try{
		gn.stop();
		window.removeEventListener('deviceorientation',onDeviceOrientationHandler);
		window.removeEventListener('devicemotion',onDeviceMotionHandler);
		gn_isready = false;
	} catch(err){
		onError(err);
	}
}

/*
*
* Starts tracking the values
*
* @param function callback - Callback function to read the values
*
*/
gn.start = function(callback){
	if(!gn_isready){
		onError({message:'GyroNorm is not initialized. First call gn.init()' , code:1});
		return;
	}
	calibrate();
	gn_interval = setInterval(function(){
		callback(snapShot());
	},gn._frequency);
}

/*
*
* Stops tracking the values
*
*/
gn.stop = function(){
	if(gn_interval){
		clearInterval(gn_interval);
	}
}

/*
*
* Toggles if to normalize gravity related values
*
* @param boolean flag
*
*/
gn.normalizeGravity = function(flag){
	gn._gravityNormalized = (flag)?true:false;
}

/*
*
* Toggles if to give absolute orientation values
*
* @param boolean flag
*
*/
gn.giveAbsoluteDirection = function(flag){
	gn._directionAbsolute = (flag)?true:false;
}

/*
*
* Sets the current alpha value as "0"
*
*/
gn.setHeadDirection = function(){
	gn._directionAbsolute = false;
	calibrate();
}

/*-------------------------------------------------------*/
/* PRIVATE FUNCTIONS */

/*
*
* Starts listening to the eventa on the window object
*
*/
function gn_setupListeners(){
	window.addEventListener('deviceorientation',onDeviceOrientationHandler,true);
	window.addEventListener('devicemotion',onDeviceMotionHandler,true);
	window.addEventListener('compassneedscalibration',onCompassNeedsCalibrationHandler,true);
}

/*
*
* Starts listening to orientation event on the window object
*
*/
function onError(err){
	if(gn.log){
		if(typeof(err) == 'string'){
			err = {message:err , code:0}
		}
		gn.log(err);
	}
}

/*
*
* Gets called only in calibration mode. Gets the mean value of the alpha deviations. And stores it as calibration.
*
*/
function updateCalibration(){
	if(gn_calibrationValues.length > 19){
		gn_calibrationValues.splice(0,5);
		var total = 0;
		for(var i = 0 ; i < gn_calibrationValues.length ; i++){
			total += gn_calibrationValues[i];
		}
		gn_calibrationValue = parseInt(total / 15);
		gn_isCalibrating = false;
	}
}

/*
*
* Handler for deviceo orientation event
*
*/
function onDeviceOrientationHandler(event){
	// Check if values are returned correctly
	if(!event.alpha && !event.beta && !event.gamma){
		onError({message:'Device orientation event values are not returned as expected.' , code:2 });
		window.removeEventListener('deviceorientation',onDeviceOrientationHandler);
	}

	// For the first 20 values add the alpha to calibration list
	if(gn_isCalibrating){
		gn_calibrationValues.push(event.alpha);
		updateCalibration();
		return;
	}

	// Assign event values to the object values
	gn._values.do.alpha = event.alpha;
	gn._values.do.beta = event.beta;
	gn._values.do.gamma = event.gamma;
	gn._values.do.absolute = event.absolute;
}

/*
*
* Handler for device motion event
*
*/
function onDeviceMotionHandler(event){

	// Assign gravity coefficient. Assumes that the user is holding the phot up right facing the screen.
	// If you cannot make this assumption because of the usecase, disable the normalization via changing the option 'gravityNormalized' value to false
	if(gn_gravityCoefficient == 0){
		gn_gravityCoefficient = (event.accelerationIncludingGravity.z < 0)?1:-1;
		return;
	}

	// Assign event values to the object values
	gn._values.dm.x = event.acceleration.x;
	gn._values.dm.y = event.acceleration.y;
	gn._values.dm.z = event.acceleration.z;

	gn._values.dm.gx = event.accelerationIncludingGravity.x;
	gn._values.dm.gy = event.accelerationIncludingGravity.y;
	gn._values.dm.gz = event.accelerationIncludingGravity.z;

	gn._values.dm.alpha = event.rotationRate.alpha;
	gn._values.dm.beta = event.rotationRate.beta;
	gn._values.dm.gamma = event.rotationRate.gamma;
}

/*
*
* Handler for device motion event
*
*/
function onCompassNeedsCalibrationHandler(event){

	onError({message:'Compass is not calibrated.' , code:3});

}

/*
*
* Utility function to round with digits after the decimal point
*
* @param float number - the original number to round
*
*/
function rnd(number){
	return Math.round(number * Math.pow(10 , gn._decimalCount)) / Math.pow(10 , gn._decimalCount);
}

/*
*
* Starts calibration
*
*/
function calibrate(){
	gn_isCalibrating = true;
	gn_calibrationValues = new Array();
}

/*
*
* Takes a snapshot of the values
*
*/
function snapShot(){

	// Send absolute or relative alpha. Default is relative.
	var alphaToSend = 0;
	if(!gn._directionAbsolute){
		alphaToSend = gn._values.do.alpha - gn_calibrationValue;
		alphaToSend = (alphaToSend < 0)?(360 - Math.abs(alphaToSend)):alphaToSend;
	} else {
		alphaToSend = gn._values.do.alpha;
	}

	var snapShot = {
		do:{
			alpha:rnd(alphaToSend),
			beta:rnd(gn._values.do.beta),
			gamma:rnd(gn._values.do.gamma),
			absolute:gn._values.do.absolute
		},
		dm:{
			x:rnd(gn._values.dm.x),
			y:rnd(gn._values.dm.y),
			z:rnd(gn._values.dm.z),
			gx:rnd(gn._values.dm.gx),
			gy:rnd(gn._values.dm.gy),
			gz:rnd(gn._values.dm.gz),
			alpha:rnd(gn._values.dm.alpha),
			beta:rnd(gn._values.dm.beta),
			gamma:rnd(gn._values.dm.gamma)
		}
	};

	// Normalize gravity
	if(gn._gravityNormalized){
		snapShot.dm.gx *= gn_gravityCoefficient;
		snapShot.dm.gy *= gn_gravityCoefficient;
		snapShot.dm.gz *= gn_gravityCoefficient;
	}

	return snapShot;
}
<|endoftext|>


<commit_before>//On commence par déclarer toutes nos variables

//On ajoute un div au body. Le div du html va ainsi pouvoir contenir notre tooltip

var div = d3.select("body").append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

//Variables qui définissent les dimensions de l'image
var width = 1400,
    height = 800;

//On définit la variable zoomON qui va permettre de zoom au click.
var zoomON;

//On définit les variables width et height pour définir les dimensions de nos boutons de sélection d'année.

var button_width = 20, button_height = 20;

// La variable projection pour projeter les données sur la carte
var projection = d3.geo.mercator()
    .center([0, 45 ])
    .scale(190)
    .translate([width/2, height/2])
    .rotate([0,0]);

//Création de l'image au format SVG
var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)
    .attr("viewBox", "0 0 " + width + " " + height);

//On ajoute à notre image un rectangle qui sera notre fond bleu

svg.append("rect")
    .attr("class", "background")
    .attr("width", width)
    .attr("height", height);

//L'objet path permet de manipuler les données géographiques de nos fichiers GeoJson
//En fait, path (=chemin) permet de dessiner le contour de nos objets.
var path = d3.geo.path()
    .projection(projection);

//Variable g, qui permet de grouper les éléments de l'image SVG
var g = svg.append("g");

//Le zoom

var Myzoom = d3.behavior.zoom()
    .on("zoom",function() {
	g.attr("transform","translate("+ d3.event.translate.join(",")+")scale("+d3.event.scale+")")

    });

svg.call(Myzoom)

//La légende

var color = d3.scale.ordinal() //Fonction qui permet d'associer une couleur à une catégorie
    .domain(["0", "1", "2 à 5", "5 à 10", "10++"])
    .range(["AliceBlue", "GoldenRod", "DarkGoldenRod", "IndianRed", "DarkRed"]);

var taille_rect= 15; //Taille des rectangles
var legendSpacing = 4; //Espace entre les rectangles

var legend =svg.selectAll(".legend")//On sélectionne tous les éléments qu'on va créer
    .data(color.domain())// On récupère nos 3 catégories à légender
    .enter()// On crée des espaces réservés pour chaque donnée (3 donc)
    .append("g") // On ajoute l'élément g à l'image
    .attr("class", "legend") // On définit la classe des objets
    .attr("transform", function(d, i) { // On crée un attribut qui va modifier nos éléments en terme de dimensions en fonction des index de domain.

	var hauteur = taille_rect;
	var x = hauteur;
	var y = i * 30;
	return "translate(" + x + "," + y + ")";
    });

//Contruction de la légende
legend.append("rect") // On ajoute un rectangle à l'image pour chaque élément
    .attr("width", taille_rect)
    .attr("height", taille_rect)
    .style("fill", color)
    .style("stroke", "black");

legend.append("text") // On ajoute du texte pour chaque élément
    .attr("x", taille_rect + legendSpacing)
    .attr("y", taille_rect - legendSpacing)
    .text(function(d) { return d; });

//Construction de tous nos pays avec leurs stages respectifs.

//Fonction qui permet de charger les données dans l'ordre où on place nos fichiers GeoJson.
queue()
    .defer(d3.json, "data/world.json")
    .defer(d3.json, "data/internship.json")
    .await(makeMyMap);

//fonction qui créee la map en fonction des données qu'on a chargé précedemment
function makeMyMap(error, countries, internship) {

    //On s'occupe des pays du fichier World.json
    g.selectAll(".countries")
	.data(topojson.object(countries, countries.objects.countries).geometries)
	.enter()
	.append("path")
	.attr("d", path)
	.attr("class", "countries")
	.on("mouseover", mouseover)

	.on("mousemove",  function(d) {

	    var creation_compteurs = d3.nest()
		.key(function(d) { return d.properties.country; })
		.key(function(d) { return d.properties.id; })
		.rollup(function(leaves) { return leaves.length; })
		.entries(internship.features);

	    var creation_compteurs_regions = d3.nest()
		.key(function(d) { return d.properties.region; })
		.key(function(d) { return d.properties.id; })
		.rollup(function(leaves) { return leaves.length; })
		.entries(internship.features);

	    var compteur;
	    for (var i = 0; i < creation_compteurs.length; i++) {
		if (d.properties.name == creation_compteurs[i].key) {
		    compteur = creation_compteurs[i].values.length;
		    break;
		    return compteur;
		}
		else {
		    compteur = 0;
		}
	    }

	    //Ca c'est ce qui s'affiche dans la fenêtre au passage de la souris
	    div.html(d.properties.name  + "
" + "internships: " + compteur )
		.style("left", (d3.event.pageX) + "px")
		.style("top", (d3.event.pageY - 50) + "px");
	})

	.on("mouseout", mouseout)
 	.attr("fill", couleur)
	.on("click",ClickPays);

    g.selectAll(".internship")
	.data(internship.features)
	.enter()
	.append("path")
	.attr("d", path.pointRadius(1))
	.attr("class", "internship")
	.on("mouseover", mouseover)
	.on("mousemove", mousemove)
	.on("mouseout", mouseout);

    function couleur(d) {

	var creation_compteurs = d3.nest()
	    .key(function(d) { return d.properties.country; })
	    .key(function(d) { return d.properties.id; })
	    .rollup(function(leaves) { return leaves.length; })
	    .entries(internship.features);

	var color = "AliceBlue";
	for (var i = 0; i < creation_compteurs.length; i++) {
	    if (d.properties.name == creation_compteurs[i].key) {
		if (creation_compteurs[i].values.length  == 1) {
		    color = "GoldenRod";
		    return color;
		}

		else if (creation_compteurs[i].values.length  > 1 && creation_compteurs[i].values.length < 6) {
		    color = "DarkGoldenRod";
		    return color;
		}

		else if (creation_compteurs[i].values.length > 5 && creation_compteurs[i].values.length < 10 ) {
		    color = "IndianRed";
		    return color;
		}

		else if (creation_compteurs[i].values.length >= 10) {
		    color = "DarkRed";
		    return color;
		}

	    }
	}

	return color;
    }
}

function ClickPays(d) {

    function BackToMap(d) {

	svg.select(".button_back").remove();
	svg.select(".text_button_back").remove();
	g.selectAll(".regions").remove();
	g.selectAll(".internshipFr").remove();
	g.selectAll(".cities").remove();

	queue()
	    .defer(d3.json, "data/world.json")
	    .defer(d3.json, "data/internship.json")
	    .await(makeMyMap);

    }

    function ClickZoom(d) {

	var x, y, z;

	//Si le zoom n'est pas actif, on peut zoomer.

	if (zoomON == null) {
	    var centroid = path.centroid(d);
	    x = centroid[0];
	    y = centroid[1];
	    z = 11;

	    zoomON = 1; //On note le zoom comme étant actif
	}

	//Ici on retourne à la position initiale car le zoom est actif. Donc on veut dezoomer.

	else {
	    x = width / 2;
	    y = height / 2;
	    z = 1;
	    zoomON = null;
	}

	//Ici on spécifie les élement que l'on souhaite être concernés par le zoom.
	g.selectAll(".countries")
	    .classed("active", zoomON)
	    .transition()
	    .duration(750)
	    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + z + ")translate(" + -x + "," + -y + ")");

	g.selectAll(".regions")
	    .classed("active", zoomON )
	    .transition()
	    .duration(750)
	    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + z + ")translate(" + -x + "," + -y + ")");

	g.selectAll(".internshipFr")
	    .classed("active", zoomON )
	    .transition()
	    .duration(750)
	    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + z + ")translate(" + -x + "," + -y + ")");

	g.selectAll(".cities")
	    .classed("active", zoomON )
	    .transition()
	    .duration(750)
	    .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")scale(" + z + ")translate(" + -x + "," + -y + ")");

    }

    function makeMyFrance(error, regions, internship, cities) {

	g.selectAll(".regions")
	    .data(regions.features)
	    .enter()
	    .append("path")
	    .attr("d", path)
	    .attr("class", "regions")
	    .on("mouseover", mouseover)
	    .on("mousemove",  function(d) {

		var creation_compteurs_regions = d3.nest()
		    .key(function(d) { return d.properties.region; })
		    .key(function(d) { return d.properties.id; })
		    .rollup(function(leaves) { return leaves.length; })
		    .entries(internship.features);

		var compteur_regions;
		for (var i = 0; i < creation_compteurs_regions.length; i++) {
		    if (d.properties.nom == creation_compteurs_regions[i].key) {
			compteur_regions = creation_compteurs_regions[i].values.length;
			break;
			return compteur_regions;
		    }
		    else {
			compteur_regions = 0;
		    }
		}

		//Ca c'est ce qui s'affiche dans la fenêtre au passage de la souris
		div.html(d.properties.nom  + "
" + "compteur " + compteur_regions )
		    .style("left", (d3.event.pageX) + "px")
		    .style("top", (d3.event.pageY - 50) + "px");
	    })

	    .on("mouseout", mouseout)
	    .attr("fill", couleur_region);

	function couleur_region(d) {

	    var creation_compteurs_regions = d3.nest()
		.key(function(d) { return d.properties.region; })
		.key(function(d) { return d.properties.id; })
		.rollup(function(leaves) { return leaves.length; })
		.entries(internship.features);

	    var color_region = "AliceBlue";
	    for (var i = 0; i < creation_compteurs_regions.length; i++) {
		if (d.properties.nom == creation_compteurs_regions[i].key) {
		    if (creation_compteurs_regions[i].values.length  == 1) {
			color_region = "GoldenRod";
			return color_region;
		    }

		    else if (creation_compteurs_regions[i].values.length  > 1 && creation_compteurs_regions[i].values.length < 6) {
			color_region = "DarkGoldenRod";
			return color_region;
		    }

		    else if (creation_compteurs_regions[i].values.length > 5 && creation_compteurs_regions[i].values.length < 10 ) {
			color_region = "IndianRed";
			return color_region;
		    }

		    else if (creation_compteurs_regions[i].values.length >= 10) {
			color_region = "DarkRed";
			return color_region;
		    }

		}
	    }

	    return color_region;
	}

	g.selectAll(".internshipFr")
	    .data(internship.features
		  .filter(function(d)  { return d.properties.country == "France";  }))
	    .enter()
	    .append("path")
	    .attr("d", path.pointRadius(0.2))
	    .attr("class", "internshipFr")
	    .on("mouseover", mouseover)
	    .on("mousemove", mousemove)
	    .on("mouseout", mouseout);

	g.selectAll(".cities")
	    .data(cities.features)
	    .enter()
	    .append("path")
	    .attr("d", path.pointRadius(0.1))
	    .attr("class", "cities")
	    .on("mouseover", mouseover)
	    .on("mousemove", function (d){
		div.html("City: " + d.properties.name  + "
"  )
		    .style("left", (d3.event.pageX) + "px")
		    .style("top", (d3.event.pageY - 50) + "px");
	    })
	    .on("mouseout", mouseout);

	ClickZoom(d);

    }

    if (d.properties.name === "France") {

	svg.append("rect")
	    .attr("class", "button_back")
	    .attr("width", 25)
	    .attr("height", 25)
	    .attr("x", 200)
	    .attr("y", 200)
	    .on("click", BackToMap);

	svg.append("text")
	    .attr("class", "text_button_back")
	    .attr("x", 230)
	    .attr("y", 215)
	    .text("retour à la map");

	g.selectAll(".internship").remove();
	g.selectAll(".countries").remove();

	queue()
	    .defer(d3.json, "data/regions.json")
	    .defer(d3.json, "data/internship.json")
	    .defer(d3.json, "data/cities.json")
	    .await(makeMyFrance);

    }

}

function mouseover(){
    div.transition()
	.duration(200)
	.style("opacity", .9);
}

function mousemove(d){
    div.html("City: " + d.properties.city  + "
" + "Year: " + d.properties.year + "
" + "Center: " + d.properties.center )
	.style("left", (d3.event.pageX) + "px")
	.style("top", (d3.event.pageY - 50) + "px");
}

function mouseout(){
    div.transition()
	.duration(500)
	.style("opacity", 0);
}

//Création des boutons permettants d'afficher les stages par année.

var buttons_localisation = [[2013],[2014],[2015],[2016]]

var box = svg.selectAll(".rect")
    .data(buttons_localisation)
    .enter()
    .append("g")
    .attr("class", "button")
    .attr("transform", function(d, i) {
	var hauteur = 1200 ;
	var x = hauteur;
	var y = i * 30;
	return "translate(" + x + "," + y + ")";
 });;

box.append("rect")
    .attr("width", taille_rect)
    .attr("height", taille_rect)
    .attr("id", function(d) {return d[0];})
    .on("click", change);

box.append("text")
    .text (function(d) {return d[0];})
    .attr("x", taille_rect + legendSpacing)
    .attr("y", taille_rect - legendSpacing);

function change() {

    var button_id = this.id;
    console.log("tu viens de cliquer sur le bouton de "+ button_id);
    if (document.getElementById(button_id).style.fill !== "#ff0000"){
	document.getElementById(button_id).style.fill = "#ff0000";
	g.selectAll(".internshipFr")
	    .filter(function(d){return d.properties.year == button_id;})
	    .transition()
	    .attr("d", path.pointRadius(0))
	    .duration(0);

	g.selectAll(".internship")
	    .filter(function(d){return d.properties.year == button_id;})
	    .transition()
	    .attr("d", path.pointRadius(0))
	    .duration(0);

	return null;

    }
    if (document.getElementById(button_id).style.fill !== "#008000"){
	document.getElementById(button_id).style.fill = "#008000";
	g.selectAll(".internshipFr")
	    .filter(function(d){return d.properties.year == button_id;})
	    .transition()
	    .attr("d", path.pointRadius(0.2))
	    .duration(0);

	g.selectAll(".internship")
	    .filter(function(d){return d.properties.year == button_id;})
	    .transition()
	    .attr("d", path.pointRadius(1))
	    .duration(0);

	return null;
    }
}
<commit_msg>Delete mapLight.js<commit_after><|endoftext|>


<commit_before>'use strict';

angular.module('app')
    .controller('rgiContactTechCtrl', function (
        $scope,
        $location,
        rgiNotifier,
        rgiContactMethodSrvc,
        rgiIdentitySrvc,
        rgiAssessmentSrvc
    ) {
        $scope.request = {tool: 'rgi'};
        var criteria = {};

        $scope.issue_selection = [
            {name: 'Trouble logging in.', value: 'login'},
            {name: 'Parts of the site are down.', value: 'down'},
            {name: 'Visual components don\'t look correct', value: 'visual'},
            {name: 'Answers don\'t seem to be saving when completed', value: 'save'},
            {name: 'Documents cannot be saved', value: 'upload'},
            {name: 'Cannot edit comments/justification fields', value: 'justification'},
            //{name: '', value: ''},
            {name: 'Other', value: 'other'}
        ];
        $scope.os_selection = [
            {name: 'Android', value: 'android'},
            {name: 'Windows Phone', value: 'windows_ph'},
            {name: 'iOS', value: 'ios'},
            {name: 'Windows 10', value:'win10'},
            {name: 'Windows 8.1', value:'win8.1'},
            {name: 'Windows 8', value: 'win8'},
            {name: 'Windows 7', value: 'win7'},
            {name: 'Windows XP', value: 'winxp'},
            {name: 'OS X El Capitan', value: 'osx10.11'},
            {name: 'OS X Yosemite', value: 'osx10.10'},
            {name: 'OS X Mavericks', value: 'osx10.9'},
            {name: 'OS X Mountain Lion', value: 'osx10.8'},
            {name: 'OS X Lion', value: 'osx10.7'},
            {name: 'OS X Snow Leopard', value: 'osx10.6'},
            {name: 'Ubuntu', value: 'ubuntu'},
            {name: 'Other', value: 'other'}
        ];
        $scope.browser_selection = [
            {name: 'Internet Explorer', value: 'ie'},
            {name: 'Firefox', value: 'firefox'},
            {name: 'Chrome', value: 'chrome'},
            {name: 'Opera', value: 'opera'},
            {name: 'Yandex', value: 'yandex'},
            {name: 'Safari', value: 'safari'},
            {name: 'Other', value: 'other'}
        ];

        if(rgiIdentitySrvc.currentUser) {
            $scope.request.first_name = rgiIdentitySrvc.currentUser.firstName;
            $scope.request.last_name = rgiIdentitySrvc.currentUser.lastName;
            $scope.request.email = rgiIdentitySrvc.currentUser.email;
            var getAssessments = function(criteria) {
                rgiAssessmentSrvc.query(criteria, function (assessments) {
                    if (assessments.length > 1) {
                        $scope.assessments = assessments;
                    } else if (assessments.length > 0) {
                        $scope.request.assessment = assessments[0];
                    }

                });
            };
            criteria[rgiIdentitySrvc.currentUser.role + '_ID'] = rgiIdentitySrvc.currentUser._id;
            getAssessments(criteria);
        }

        $scope.sendRequest = function() {
            var contactInfo = $scope.request;
            if (!contactInfo.first_name || !contactInfo.first_name) {
                rgiNotifier.error('You must supply a name!');
            } else if (!contactInfo.email) {
                rgiNotifier.error('You must supply an email!');
            } else if (!contactInfo.issue) {
                rgiNotifier.error('You must select an issue!');
            } else {
                rgiContactMethodSrvc.contact(contactInfo).then(function () {
                    rgiNotifier.notify('Request sent.');
                    $location.path('/');
                }, function (reason) {
                    rgiNotifier.error(reason);
                });
            }
        };

        $scope.clearRequest = function () {
            $scope.request = {tool: 'rgi'};
        };
    });
<commit_msg>order the assessment list options on the page 'Contact Tech Support'<commit_after>'use strict';

angular.module('app')
    .controller('rgiContactTechCtrl', function (
        $scope,
        $location,
        rgiNotifier,
        rgiContactMethodSrvc,
        rgiIdentitySrvc,
        rgiAssessmentSrvc
    ) {
        $scope.request = {tool: 'rgi'};
        var criteria = {};

        $scope.issue_selection = [
            {name: 'Trouble logging in.', value: 'login'},
            {name: 'Parts of the site are down.', value: 'down'},
            {name: 'Visual components don\'t look correct', value: 'visual'},
            {name: 'Answers don\'t seem to be saving when completed', value: 'save'},
            {name: 'Documents cannot be saved', value: 'upload'},
            {name: 'Cannot edit comments/justification fields', value: 'justification'},
            //{name: '', value: ''},
            {name: 'Other', value: 'other'}
        ];
        $scope.os_selection = [
            {name: 'Android', value: 'android'},
            {name: 'Windows Phone', value: 'windows_ph'},
            {name: 'iOS', value: 'ios'},
            {name: 'Windows 10', value:'win10'},
            {name: 'Windows 8.1', value:'win8.1'},
            {name: 'Windows 8', value: 'win8'},
            {name: 'Windows 7', value: 'win7'},
            {name: 'Windows XP', value: 'winxp'},
            {name: 'OS X El Capitan', value: 'osx10.11'},
            {name: 'OS X Yosemite', value: 'osx10.10'},
            {name: 'OS X Mavericks', value: 'osx10.9'},
            {name: 'OS X Mountain Lion', value: 'osx10.8'},
            {name: 'OS X Lion', value: 'osx10.7'},
            {name: 'OS X Snow Leopard', value: 'osx10.6'},
            {name: 'Ubuntu', value: 'ubuntu'},
            {name: 'Other', value: 'other'}
        ];
        $scope.browser_selection = [
            {name: 'Internet Explorer', value: 'ie'},
            {name: 'Firefox', value: 'firefox'},
            {name: 'Chrome', value: 'chrome'},
            {name: 'Opera', value: 'opera'},
            {name: 'Yandex', value: 'yandex'},
            {name: 'Safari', value: 'safari'},
            {name: 'Other', value: 'other'}
        ];

        if(rgiIdentitySrvc.currentUser) {
            $scope.request.first_name = rgiIdentitySrvc.currentUser.firstName;
            $scope.request.last_name = rgiIdentitySrvc.currentUser.lastName;
            $scope.request.email = rgiIdentitySrvc.currentUser.email;
            var getAssessments = function(criteria) {
                rgiAssessmentSrvc.query(criteria, function (assessments) {
                    if (assessments.length > 1) {
                        assessments.sort(function(assessmentA, assessmentB) {
                            if(assessmentA.country !== assessmentB.country) {
                                return assessmentA.country > assessmentB.country;
                            }

                            if(assessmentA.year !== assessmentB.year) {
                                return assessmentA.year > assessmentB.year;
                            }

                            if(assessmentA.version !== assessmentB.version) {
                                return assessmentA.version > assessmentB.version;
                            }

                            return assessmentA.mineral > assessmentB.mineral;
                        });

                        $scope.assessments = assessments;
                    } else if (assessments.length > 0) {
                        $scope.request.assessment = assessments[0];
                    }

                });
            };
            criteria[rgiIdentitySrvc.currentUser.role + '_ID'] = rgiIdentitySrvc.currentUser._id;
            getAssessments(criteria);
        }

        $scope.sendRequest = function() {
            var contactInfo = $scope.request;
            if (!contactInfo.first_name || !contactInfo.first_name) {
                rgiNotifier.error('You must supply a name!');
            } else if (!contactInfo.email) {
                rgiNotifier.error('You must supply an email!');
            } else if (!contactInfo.issue) {
                rgiNotifier.error('You must select an issue!');
            } else {
                rgiContactMethodSrvc.contact(contactInfo).then(function () {
                    rgiNotifier.notify('Request sent.');
                    $location.path('/');
                }, function (reason) {
                    rgiNotifier.error(reason);
                });
            }
        };

        $scope.clearRequest = function () {
            $scope.request = {tool: 'rgi'};
        };
    });
<|endoftext|>


<commit_before>(function (window, undefined) {
    var MapsLib = function (options) {
        var self = this;

        options = options || {};

        this.recordName = options.recordName || "risultati"; //for showing a count of results
        this.recordNamePlural = options.recordNamePlural || "risultati";
        this.searchRadius = options.searchRadius || 805; //in meters ~ 1/2 mile

        // the encrypted Table ID of your Fusion Table (found under File => About)
        this.fusionTableId = options.fusionTableId || "",

        // Found at https://console.developers.google.com/
        // Important! this key is for demonstration purposes. please register your own.
        this.googleApiKey = options.googleApiKey || "",

        // name of the location column in your Fusion Table.
        // NOTE: if your location column name has spaces in it, surround it with single quotes
        // example: locationColumn:     "'my location'",
        this.locationColumn = options.locationColumn || "geometry";

        // appends to all address searches if not present
        this.locationScope = options.locationScope || "";

        // zoom level when map is loaded (bigger is more zoomed in)
        this.defaultZoom = options.defaultZoom || 13;

        // center that your map defaults to
        this.map_centroid = new google.maps.LatLng(options.map_center[0], options.map_center[1]);

        // marker image for your searched address
        if (typeof options.addrMarkerImage !== 'undefined') {
            if (options.addrMarkerImage != "")
                this.addrMarkerImage = options.addrMarkerImage;
            else
                this.addrMarkerImage = ""
        }
        else
            this.addrMarkerImage = "images/blue-pushpin.png"

    	this.currentPinpoint = null;
    	$("#result_count").html("");

        this.myOptions = {
            zoom: this.defaultZoom,
            center: this.map_centroid,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        this.geocoder = new google.maps.Geocoder();
        this.map = new google.maps.Map($("#map_canvas")[0], this.myOptions);

        // maintains map centerpoint for responsive design
        google.maps.event.addDomListener(self.map, 'idle', function () {
            self.calculateCenter();
        });
        google.maps.event.addDomListener(window, 'resize', function () {
            self.map.setCenter(self.map_centroid);
        });
        self.searchrecords = null;

        //reset filters
        $("#search_address").val(self.convertToPlainString($.address.parameter('address')));
        var loadRadius = self.convertToPlainString($.address.parameter('radius'));
        if (loadRadius != "")
            $("#search_radius").val(loadRadius);
        else
            $("#search_radius").val(self.searchRadius);

        $(":checkbox").prop("checked", "checked");
        $("#result_box").hide();

        //-----custom initializers-----
        //-----end of custom initializers-----

        //run the default search when page loads
        self.doSearch();
        if (options.callback) options.callback(self);
    };

    //-----custom functions-----
    //-----end of custom functions-----

    MapsLib.prototype.submitSearch = function (whereClause, map) {
        var self = this;
        //get using all filters
        //NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows
        //you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables
        //for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles
        self.searchrecords = new google.maps.FusionTablesLayer({
            query: {
                from: self.fusionTableId,
                select: self.locationColumn,
                where: whereClause
            },
            styleId: 2,
            templateId: 2
        });
        self.fusionTable = self.searchrecords;
        self.searchrecords.setMap(map);
        self.getCount(whereClause);
    };

    MapsLib.prototype.getgeoCondition = function (address, callback) {
        var self = this;
        if (address !== "") {
            if (address.toLowerCase().indexOf(self.locationScope) === -1) {
                address = address + " " + self.locationScope;
            }
            self.geocoder.geocode({
                'address': address
            }, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                    self.currentPinpoint = results[0].geometry.location;
                    var map = self.map;

                    $.address.parameter('address', encodeURIComponent(address));
                    $.address.parameter('radius', encodeURIComponent(self.searchRadius));
                    map.setCenter(self.currentPinpoint);
                    // set zoom level based on search radius
                    if (self.searchRadius >= 1610000) map.setZoom(4); // 1,000 miles
                    else if (self.searchRadius >= 805000) map.setZoom(5); // 500 miles
                    else if (self.searchRadius >= 402500) map.setZoom(6); // 250 miles
                    else if (self.searchRadius >= 161000) map.setZoom(7); // 100 miles
                    else if (self.searchRadius >= 80500) map.setZoom(8); // 100 miles
                    else if (self.searchRadius >= 40250) map.setZoom(9); // 100 miles
                    else if (self.searchRadius >= 16100) map.setZoom(11); // 10 miles
                    else if (self.searchRadius >= 8050) map.setZoom(12); // 5 miles
                    else if (self.searchRadius >= 3220) map.setZoom(13); // 2 miles
                    else if (self.searchRadius >= 1610) map.setZoom(14); // 1 mile
                    else if (self.searchRadius >= 805) map.setZoom(15); // 1/2 mile
                    else if (self.searchRadius >= 400) map.setZoom(16); // 1/4 mile
                    else self.map.setZoom(17);

                    if (self.addrMarkerImage != '') {
                        self.addrMarker = new google.maps.Marker({
                            position: self.currentPinpoint,
                            map: self.map,
                            icon: self.addrMarkerImage,
                            animation: google.maps.Animation.DROP,
                            title: address
                        });
                    }
                    var geoCondition = " AND ST_INTERSECTS(" + self.locationColumn + ", CIRCLE(LATLNG" + self.currentPinpoint.toString() + "," + self.searchRadius + "))";
                    callback(geoCondition);
                    self.drawSearchRadiusCircle(self.currentPinpoint);
                } else {
                    alert("We could not find your address: " + status);
                    callback('');
                }
            });
        } else {
            callback('');
        }
    };

    MapsLib.prototype.doSearch = function () {
        var self = this;
        self.clearSearch();
        var address = $("#search_address").val();
        self.searchRadius = $("#search_radius").val();
        self.whereClause = self.locationColumn + " not equal to ''";

        //-----custom filters-----
        //-----end of custom filters-----

        self.getgeoCondition(address, function (geoCondition) {
            self.whereClause += geoCondition;
            self.submitSearch(self.whereClause, self.map);
        });

    };

    MapsLib.prototype.reset = function () {
        $.address.parameter('address','');
        $.address.parameter('radius','');
        window.location.reload();
    };

    MapsLib.prototype.getInfo = function (callback) {
        var self = this;
        jQuery.ajax({
            url: 'https://www.googleapis.com/fusiontables/v1/tables/' + self.fusionTableId + '?key=' + self.googleApiKey,
            dataType: 'json'
        }).done(function (response) {
            if (callback) callback(response);
        });
    };

    MapsLib.prototype.addrFromLatLng = function (latLngPoint) {
        var self = this;
        self.geocoder.geocode({
            'latLng': latLngPoint
        }, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    $('#search_address').val(results[1].formatted_address);
                    $('.hint').focus();
                    self.doSearch();
                }
            } else {
                alert("Geocoder failed due to: " + status);
            }
        });
    };

    MapsLib.prototype.drawSearchRadiusCircle = function (point) {
        var self = this;
        var circleOptions = {
            strokeColor: "#4b58a6",
            strokeOpacity: 0.3,
            strokeWeight: 1,
            fillColor: "#4b58a6",
            fillOpacity: 0.05,
            map: self.map,
            center: point,
            clickable: false,
            zIndex: -1,
            radius: parseInt(self.searchRadius)
        };
        self.searchRadiusCircle = new google.maps.Circle(circleOptions);
    };

    MapsLib.prototype.query = function (query_opts, callback) {
        var queryStr = [],
            self = this;
        queryStr.push("SELECT " + query_opts.select);
        queryStr.push(" FROM " + self.fusionTableId);
        // where, group and order clauses are optional
        if (query_opts.where && query_opts.where != "") {
            queryStr.push(" WHERE " + query_opts.where);
        }
        if (query_opts.groupBy && query_opts.groupBy != "") {
            queryStr.push(" GROUP BY " + query_opts.groupBy);
        }
        if (query_opts.orderBy && query_opts.orderBy != "") {
            queryStr.push(" ORDER BY " + query_opts.orderBy);
        }
        if (query_opts.offset && query_opts.offset !== "") {
            queryStr.push(" OFFSET " + query_opts.offset);
        }
        if (query_opts.limit && query_opts.limit !== "") {
            queryStr.push(" LIMIT " + query_opts.limit);
        }
        var theurl = {
            base: "https://www.googleapis.com/fusiontables/v1/query?sql=",
            queryStr: queryStr,
            key: self.googleApiKey
        };
        $.ajax({
            url: [theurl.base, encodeURIComponent(theurl.queryStr.join(" ")), "&key=", theurl.key].join(''),
            dataType: "json"
        }).done(function (response) {
            //console.log(response);
            if (callback) callback(response);
        }).fail(function(response) {
            self.handleError(response);
        });
    };

    MapsLib.prototype.handleError = function (json) {
        if (json.error !== undefined) {
            var error = json.responseJSON.error.errors;
            console.log("Error in Fusion Table call!");
            for (var row in error) {
                console.log(" Domain: " + error[row].domain);
                console.log(" Reason: " + error[row].reason);
                console.log(" Message: " + error[row].message);
            }
        }
    };
    MapsLib.prototype.getCount = function (whereClause) {
        var self = this;
        var selectColumns = "Count()";
        self.query({
            select: selectColumns,
            where: whereClause
        }, function (json) {
            self.displaySearchCount(json);
        });
    };

    MapsLib.prototype.displaySearchCount = function (json) {
        var self = this;

        var numRows = 0;
        if (json["rows"] != null) {
            numRows = json["rows"][0];
        }
        var name = self.recordNamePlural;
        if (numRows == 1) {
            name = self.recordName;
        }
        $("#result_box").fadeOut(function () {
            $("#result_count").html(self.addCommas(numRows) + " " + name + " trovati");
        });
        $("#result_box").fadeIn();
    };

    MapsLib.prototype.addCommas = function (nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    };

    // maintains map centerpoint for responsive design
    MapsLib.prototype.calculateCenter = function () {
        var self = this;
        center = self.map.getCenter();
    };

    //converts a slug or query string in to readable text
    MapsLib.prototype.convertToPlainString = function (text) {
        if (text === undefined) return '';
        return decodeURIComponent(text);
    };

    MapsLib.prototype.clearSearch = function () {
        var self = this;
        if (self.searchrecords && self.searchrecords.getMap)
            self.searchrecords.setMap(null);
        if (self.addrMarker && self.addrMarker.getMap)
            self.addrMarker.setMap(null);
        if (self.searchRadiusCircle && self.searchRadiusCircle.getMap)
            self.searchRadiusCircle.setMap(null);
    };

    MapsLib.prototype.findMe = function () {
        var self = this;
        var foundLocation;
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                var accuracy = position.coords.accuracy;
                var coords = new google.maps.LatLng(latitude, longitude);
                self.map.panTo(coords);
                self.addrFromLatLng(coords);
                self.map.setZoom(14);
                jQuery('#map_canvas').append('

');
                setTimeout(function () {
                    jQuery('#myposition').remove();
                }, 3000);
            }, function error(msg) {
                alert('Please enable your GPS position future.');
            }, {
                //maximumAge: 600000,
                //timeout: 5000,
                enableHighAccuracy: true
            });
        } else {
            alert("Geolocation API is not supported in your browser.");
        }
    };
    if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
        module.exports = MapsLib;
    } else if (typeof define === 'function' && define.amd) {
        define(function () {
            return MapsLib;
        });
    } else {
        window.MapsLib = MapsLib;
    }

})(window);<commit_msg>zoom modificato<commit_after>(function (window, undefined) {
    var MapsLib = function (options) {
        var self = this;

        options = options || {};

        this.recordName = options.recordName || "risultati"; //for showing a count of results
        this.recordNamePlural = options.recordNamePlural || "risultati";
        this.searchRadius = options.searchRadius || 805; //in meters ~ 1/2 mile

        // the encrypted Table ID of your Fusion Table (found under File => About)
        this.fusionTableId = options.fusionTableId || "",

        // Found at https://console.developers.google.com/
        // Important! this key is for demonstration purposes. please register your own.
        this.googleApiKey = options.googleApiKey || "",

        // name of the location column in your Fusion Table.
        // NOTE: if your location column name has spaces in it, surround it with single quotes
        // example: locationColumn:     "'my location'",
        this.locationColumn = options.locationColumn || "geometry";

        // appends to all address searches if not present
        this.locationScope = options.locationScope || "";

        // zoom level when map is loaded (bigger is more zoomed in)
        this.defaultZoom = options.defaultZoom || 5;

        // center that your map defaults to
        this.map_centroid = new google.maps.LatLng(options.map_center[0], options.map_center[1]);

        // marker image for your searched address
        if (typeof options.addrMarkerImage !== 'undefined') {
            if (options.addrMarkerImage != "")
                this.addrMarkerImage = options.addrMarkerImage;
            else
                this.addrMarkerImage = ""
        }
        else
            this.addrMarkerImage = "images/blue-pushpin.png"

    	this.currentPinpoint = null;
    	$("#result_count").html("");

        this.myOptions = {
            zoom: this.defaultZoom,
            center: this.map_centroid,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        this.geocoder = new google.maps.Geocoder();
        this.map = new google.maps.Map($("#map_canvas")[0], this.myOptions);

        // maintains map centerpoint for responsive design
        google.maps.event.addDomListener(self.map, 'idle', function () {
            self.calculateCenter();
        });
        google.maps.event.addDomListener(window, 'resize', function () {
            self.map.setCenter(self.map_centroid);
        });
        self.searchrecords = null;

        //reset filters
        $("#search_address").val(self.convertToPlainString($.address.parameter('address')));
        var loadRadius = self.convertToPlainString($.address.parameter('radius'));
        if (loadRadius != "")
            $("#search_radius").val(loadRadius);
        else
            $("#search_radius").val(self.searchRadius);

        $(":checkbox").prop("checked", "checked");
        $("#result_box").hide();

        //-----custom initializers-----
        //-----end of custom initializers-----

        //run the default search when page loads
        self.doSearch();
        if (options.callback) options.callback(self);
    };

    //-----custom functions-----
    //-----end of custom functions-----

    MapsLib.prototype.submitSearch = function (whereClause, map) {
        var self = this;
        //get using all filters
        //NOTE: styleId and templateId are recently added attributes to load custom marker styles and info windows
        //you can find your Ids inside the link generated by the 'Publish' option in Fusion Tables
        //for more details, see https://developers.google.com/fusiontables/docs/v1/using#WorkingStyles
        self.searchrecords = new google.maps.FusionTablesLayer({
            query: {
                from: self.fusionTableId,
                select: self.locationColumn,
                where: whereClause
            },
            styleId: 2,
            templateId: 2
        });
        self.fusionTable = self.searchrecords;
        self.searchrecords.setMap(map);
        self.getCount(whereClause);
    };

    MapsLib.prototype.getgeoCondition = function (address, callback) {
        var self = this;
        if (address !== "") {
            if (address.toLowerCase().indexOf(self.locationScope) === -1) {
                address = address + " " + self.locationScope;
            }
            self.geocoder.geocode({
                'address': address
            }, function (results, status) {
                if (status === google.maps.GeocoderStatus.OK) {
                    self.currentPinpoint = results[0].geometry.location;
                    var map = self.map;

                    $.address.parameter('address', encodeURIComponent(address));
                    $.address.parameter('radius', encodeURIComponent(self.searchRadius));
                    map.setCenter(self.currentPinpoint);
                    // set zoom level based on search radius
                    if (self.searchRadius >= 1610000) map.setZoom(4); // 1,000 miles
                    else if (self.searchRadius >= 805000) map.setZoom(5); // 500 miles
                    else if (self.searchRadius >= 402500) map.setZoom(6); // 250 miles
                    else if (self.searchRadius >= 161000) map.setZoom(7); // 100 miles
                    else if (self.searchRadius >= 80500) map.setZoom(8); // 100 miles
                    else if (self.searchRadius >= 40250) map.setZoom(9); // 100 miles
                    else if (self.searchRadius >= 16100) map.setZoom(11); // 10 miles
                    else if (self.searchRadius >= 8050) map.setZoom(12); // 5 miles
                    else if (self.searchRadius >= 3220) map.setZoom(13); // 2 miles
                    else if (self.searchRadius >= 1610) map.setZoom(14); // 1 mile
                    else if (self.searchRadius >= 805) map.setZoom(15); // 1/2 mile
                    else if (self.searchRadius >= 400) map.setZoom(16); // 1/4 mile
                    else self.map.setZoom(17);

                    if (self.addrMarkerImage != '') {
                        self.addrMarker = new google.maps.Marker({
                            position: self.currentPinpoint,
                            map: self.map,
                            icon: self.addrMarkerImage,
                            animation: google.maps.Animation.DROP,
                            title: address
                        });
                    }
                    var geoCondition = " AND ST_INTERSECTS(" + self.locationColumn + ", CIRCLE(LATLNG" + self.currentPinpoint.toString() + "," + self.searchRadius + "))";
                    callback(geoCondition);
                    self.drawSearchRadiusCircle(self.currentPinpoint);
                } else {
                    alert("We could not find your address: " + status);
                    callback('');
                }
            });
        } else {
            callback('');
        }
    };

    MapsLib.prototype.doSearch = function () {
        var self = this;
        self.clearSearch();
        var address = $("#search_address").val();
        self.searchRadius = $("#search_radius").val();
        self.whereClause = self.locationColumn + " not equal to ''";

        //-----custom filters-----
        //-----end of custom filters-----

        self.getgeoCondition(address, function (geoCondition) {
            self.whereClause += geoCondition;
            self.submitSearch(self.whereClause, self.map);
        });

    };

    MapsLib.prototype.reset = function () {
        $.address.parameter('address','');
        $.address.parameter('radius','');
        window.location.reload();
    };

    MapsLib.prototype.getInfo = function (callback) {
        var self = this;
        jQuery.ajax({
            url: 'https://www.googleapis.com/fusiontables/v1/tables/' + self.fusionTableId + '?key=' + self.googleApiKey,
            dataType: 'json'
        }).done(function (response) {
            if (callback) callback(response);
        });
    };

    MapsLib.prototype.addrFromLatLng = function (latLngPoint) {
        var self = this;
        self.geocoder.geocode({
            'latLng': latLngPoint
        }, function (results, status) {
            if (status === google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    $('#search_address').val(results[1].formatted_address);
                    $('.hint').focus();
                    self.doSearch();
                }
            } else {
                alert("Geocoder failed due to: " + status);
            }
        });
    };

    MapsLib.prototype.drawSearchRadiusCircle = function (point) {
        var self = this;
        var circleOptions = {
            strokeColor: "#4b58a6",
            strokeOpacity: 0.3,
            strokeWeight: 1,
            fillColor: "#4b58a6",
            fillOpacity: 0.05,
            map: self.map,
            center: point,
            clickable: false,
            zIndex: -1,
            radius: parseInt(self.searchRadius)
        };
        self.searchRadiusCircle = new google.maps.Circle(circleOptions);
    };

    MapsLib.prototype.query = function (query_opts, callback) {
        var queryStr = [],
            self = this;
        queryStr.push("SELECT " + query_opts.select);
        queryStr.push(" FROM " + self.fusionTableId);
        // where, group and order clauses are optional
        if (query_opts.where && query_opts.where != "") {
            queryStr.push(" WHERE " + query_opts.where);
        }
        if (query_opts.groupBy && query_opts.groupBy != "") {
            queryStr.push(" GROUP BY " + query_opts.groupBy);
        }
        if (query_opts.orderBy && query_opts.orderBy != "") {
            queryStr.push(" ORDER BY " + query_opts.orderBy);
        }
        if (query_opts.offset && query_opts.offset !== "") {
            queryStr.push(" OFFSET " + query_opts.offset);
        }
        if (query_opts.limit && query_opts.limit !== "") {
            queryStr.push(" LIMIT " + query_opts.limit);
        }
        var theurl = {
            base: "https://www.googleapis.com/fusiontables/v1/query?sql=",
            queryStr: queryStr,
            key: self.googleApiKey
        };
        $.ajax({
            url: [theurl.base, encodeURIComponent(theurl.queryStr.join(" ")), "&key=", theurl.key].join(''),
            dataType: "json"
        }).done(function (response) {
            //console.log(response);
            if (callback) callback(response);
        }).fail(function(response) {
            self.handleError(response);
        });
    };

    MapsLib.prototype.handleError = function (json) {
        if (json.error !== undefined) {
            var error = json.responseJSON.error.errors;
            console.log("Error in Fusion Table call!");
            for (var row in error) {
                console.log(" Domain: " + error[row].domain);
                console.log(" Reason: " + error[row].reason);
                console.log(" Message: " + error[row].message);
            }
        }
    };
    MapsLib.prototype.getCount = function (whereClause) {
        var self = this;
        var selectColumns = "Count()";
        self.query({
            select: selectColumns,
            where: whereClause
        }, function (json) {
            self.displaySearchCount(json);
        });
    };

    MapsLib.prototype.displaySearchCount = function (json) {
        var self = this;

        var numRows = 0;
        if (json["rows"] != null) {
            numRows = json["rows"][0];
        }
        var name = self.recordNamePlural;
        if (numRows == 1) {
            name = self.recordName;
        }
        $("#result_box").fadeOut(function () {
            $("#result_count").html(self.addCommas(numRows) + " " + name + " trovati");
        });
        $("#result_box").fadeIn();
    };

    MapsLib.prototype.addCommas = function (nStr) {
        nStr += '';
        x = nStr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? '.' + x[1] : '';
        var rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1)) {
            x1 = x1.replace(rgx, '$1' + ',' + '$2');
        }
        return x1 + x2;
    };

    // maintains map centerpoint for responsive design
    MapsLib.prototype.calculateCenter = function () {
        var self = this;
        center = self.map.getCenter();
    };

    //converts a slug or query string in to readable text
    MapsLib.prototype.convertToPlainString = function (text) {
        if (text === undefined) return '';
        return decodeURIComponent(text);
    };

    MapsLib.prototype.clearSearch = function () {
        var self = this;
        if (self.searchrecords && self.searchrecords.getMap)
            self.searchrecords.setMap(null);
        if (self.addrMarker && self.addrMarker.getMap)
            self.addrMarker.setMap(null);
        if (self.searchRadiusCircle && self.searchRadiusCircle.getMap)
            self.searchRadiusCircle.setMap(null);
    };

    MapsLib.prototype.findMe = function () {
        var self = this;
        var foundLocation;
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                var accuracy = position.coords.accuracy;
                var coords = new google.maps.LatLng(latitude, longitude);
                self.map.panTo(coords);
                self.addrFromLatLng(coords);
                self.map.setZoom(14);
                jQuery('#map_canvas').append('

');
                setTimeout(function () {
                    jQuery('#myposition').remove();
                }, 3000);
            }, function error(msg) {
                alert('Please enable your GPS position future.');
            }, {
                //maximumAge: 600000,
                //timeout: 5000,
                enableHighAccuracy: true
            });
        } else {
            alert("Geolocation API is not supported in your browser.");
        }
    };
    if (typeof module !== 'undefined' && typeof module.exports !== 'undefined') {
        module.exports = MapsLib;
    } else if (typeof define === 'function' && define.amd) {
        define(function () {
            return MapsLib;
        });
    } else {
        window.MapsLib = MapsLib;
    }

})(window);<|endoftext|>