"use strict";
var highScores = (function() {
	// Check browser support for local storage => Moved to game.checkEnviroment
	
	return {
		/**
		 * Display window to type player's nickname.
		 * 
		 * @returns
		 */
		add : function() {
			menu.closeAll(function() {
				menu.open('gameover');
			});
		},
		/**
		 * Add nick and score to the high score table.
		 * 
		 * @param {String} nick Player's nick.
		 * @param {Number} score Player's score.
		 * @returns 
		 */
		insert: function(nick, score) {

			if (typeof nick == 'undefined') return;
			if (typeof score == 'undefined') return;
			
			// Read local storage data and add new value to it.
			var data = window.localStorage.hasOwnProperty('highScores') ? JSON.parse(window.localStorage.getItem('highScores')) : {};
			if (data.hasOwnProperty(score)) {
				data[score].push(nick);
			} else {
				data[score] = [nick];
			}
			// Save updated data in local storage.
			window.localStorage.setItem('highScores', JSON.stringify(data));
		},
		
		/**
		 * Clear all the high scores data stored in local storage.
		 */
		clear: function() {
			
			window.localStorage.setItem('highScores', JSON.stringify({}));
		},
		
		/**
		 * Get all the players list with scores.
		 * Returned object is as follows:
		 * {
		 *   '1': {score: 50, players: ['player1', 'player2']},
		 *   '2': {score: 35, players: ['player31']},
		 *   '3': {score: 12, players: ['player12', 'player3423']}
		 * }
		 * @returns {Object}
		 */
		getAll: function() {

			
			// Get high scores data from local storage.
			var data = JSON.parse(window.localStorage.getItem('highScores'));
			
			// Get keys (scores) from data object and sort it descending.
			var scores = new Array();
			for (var score in data) scores.push(score);
			var scores = scores.sort(function(a, b) {
				return parseInt(b) - parseInt(a);
			});
			
			//Generate high scores table.
			var highScores = {};
			// Limit high scores to 10 places.
			for(var i = 0, cnt = Math.min(scores.length, 10); i < cnt; i++) {
				var score = scores[i];
				
				// Add dot every three digits.
				var scoreString = score;
				var tokens = new Array();
				while (scoreString.length > 3) {
					tokens.push(scoreString.substr(-3));
					scoreString = scoreString.substr(0, scoreString.length - 3);
				}
				if (tokens.length) {
					scoreString = scoreString +'.'+ tokens.reverse().join('.');
				}
				
				highScores[(i + 1)] = {
					'score': scoreString,
					'players': data[score]
				};
			}
			return highScores;
		}
	};
})();