"use strict";
var levelManager = function() {
	var levels = [];
	var alreadyPassedLevels = [];
	for ( var i = 0; i < config.levels.length - 1; i += 2) {
		var nextLevel = new Level(config.levels[i + 1]);
		nextLevel.num = i + 2;
		var thisLevel = new Level(config.levels[i]);
		thisLevel.num = i + 1;
		thisLevel.options.nextLevel = nextLevel;
		if (levels[i - 1])
			levels[i - 1].options.nextLevel = thisLevel;
		levels.push(thisLevel);
		levels.push(nextLevel);
	}

	return {

		init : function() {
			if (localStorage.getItem('levels')) {
				alreadyPassedLevels = $.parseJSON(localStorage.getItem('levels'));
			}
		},

		/**
		 * Starts given level
		 * 
		 * @param {Number} number
		 * @returns {Boolean} true in case of success
		 */
		start : function(number) {
			if (typeof levels[number - 1] === "undefined") {
				game.log("ERROR: Unable to find level " + number);
				return false;
			} else {
				var currLevel = this.getCurrentLevel();
				if (currLevel)
					currLevel.stop(true);
				levels[number - 1].start();
				return true;
			}
		},
		/**
		 * Returns all levels
		 * 
		 * @returns
		 */
		getLevels : function() {
			return levels;
		},
		/**
		 * Returns current active level
		 * 
		 * @returns
		 */
		getCurrentLevel : function() {
			for ( var i = 0; i < levels.length; i++) {
				if (levels[i].isRunning())
					return levels[i];
			}
			return false;
		},
		/**
		 * Method to force stop current level
		 * 
		 * @returns
		 */
		stopCurrentLevel : function() {
			var cl = levelManager.getCurrentLevel();
			if (cl) {
				cl.stop(true);
			}
		},

		/**
		 * Stores already passed level in localStorage
		 * 
		 * @param level
		 * @returns
		 */
		storePassedLevel : function(level) {
			if (alreadyPassedLevels.indexOf(level.num) === -1) {
				alreadyPassedLevels.push(level.num);
				localStorage.setItem('levels', JSON.stringify(alreadyPassedLevels));
				game.log("adding level");
			} else {
				game.log("not adding level");
			}
		},

		/**
		 * Gets the levels that the player has already passed during previous games.
		 * 
		 * @returns {Array} numbers of already passed levels
		 */
		getAlreadyPassedLevels : function() {
			var alreadyPassed = $.parseJSON(localStorage.getItem('levels'));
			if (!alreadyPassed)
				alreadyPassed = [];
			if (config.allLevelsVisible) {
				var alreadyPassed = [];
				for ( var i = 1; i <= this.getLevels().length; i++) {
					alreadyPassed.push(i);
				}
			}

			return alreadyPassed;
		}
	}
}();