AnimalsGame.Level = new Class({
	
	initialize: function(opts) {
		var this_ = this;
		
		this.section = opts['section'];
		
		this.questionType = opts['questionType'];
		this.sectionName  = opts['sectionName'];
		this.difficulty   = opts['difficulty'];
		this.number       = opts['levelNumber'];
		this.timerUnitDuration = opts['timerUnitDuration'];
		
		this.animals =
			Config.ANIMALS[ this.sectionName ][ this.difficulty ]
				.shuffle()
				.filter(function(a) { return a && a.image })
				.clone();
		
		this.stageElements = [
			// progress UI
			new AnimalsGame.Actor({
				filename: 'progress-panel',
				path: 'assets/images/ui',
				interactive: false
			}),
			// level-number
			new AnimalsGame.StageElement({
				element:  $E('p').html(this.number)._,
				className: 'level-number',
				interactive: false
			})
		];
		
		this.timeLeft = 10;
		
		var goodAnswers = Progress.sections[ this.sectionName ].goodAnswers;
		this.progressStars = new AnimalsGame.StageElement({
			element: (function() {
				var $ul = $E('ul').insert(
					'<li class="done"><span></span></li>'.repeat(goodAnswers) +
					'<li><span></span></li>'.repeat(10 - goodAnswers)
				);
				$ul.children('li.done').each(function(li) {
					li.children('span')[0]._.style.display = 'block';
				});
				return $ul._;
			})(),
			className: 'progress-stars',
			interactive: false
		});
		this.timer = new AnimalsGame.StageElement({
			element:  $E('p').html( this.timeLeft )._,
			className: 'time-left',
			interactive: false
		});
		
		this.timeGauge = new AnimalsGame.StageElement({
			element:  $E('div').html('<span></span>')._,
			className: 'time-gauge',
			interactive: false
		});
		$(this_.timeGauge.element).first('span').setStyle('width', '100%');
		
		this.stageElements.push( this.progressStars );
		this.stageElements.push( this.timer );
		this.stageElements.push( this.timeGauge );
	},
	
	createQuestion: function() {
		var this_ = this;
		
		// reset the list of right answers if we asked each of them once
		if ( this.rightAnimals.length < 1 ) {
			this.rightAnimals = this.animals.clone();
		}
		this.rightAnswer = this.rightAnimals.shift();
		
		this.timeLeft = 10;
		$(this_.timer.element).html( this_.timeLeft );
		$(this_.timeGauge.element).first('span').setStyle('width', '100%');
	},
	
	createTimer: function() {
		// queue the timer start until everything on the page is loaded
		AnimalsGame.OnloadObserver.queueHandler((function() {
			this.questionStageElements.each(function(el) { $(el.element).show() });
			
			this.interval = setInterval((function() {
				this.timeLeft--;
				$(this.timer.element).html( this.timeLeft.padLeft(2) );
				$(this.timeGauge.element).first('span').setStyle('width', (this.timeLeft * 10) + '%');
				
				if (this.timeLeft === 0) {
					this.killInterval();
					this.triggerWrongAnswer();
				}
			}).bind(this), 1000 * this.timerUnitDuration);
		}).bind(this));
	},
	
	killInterval: function() {
		var this_ = this;
		
		clearInterval(this_.interval);
		this_.interval = null;
	},
	
	triggerRightAnswer: function() {
		var this_ = this;
		
		this_.killInterval();
		
		Progress.sections[ this.sectionName ].goodAnswers++;
		
		game.soundEffect.play('ting');
		
		this.questionStageElements.each('deactivate');
		
		$(this.progressStars.element).first('li:not(.done)').addClass('done').children('span')[0].fade('in', { duration: 'short' });
		
		this.dialog = new AnimalsGame.Actor({
			filename: 'right-answer',
			path: 'assets/images/dialogs',
			className: 'dialog right-answer-dialog',
			click: this.handleNextQuestion.bind(this),
			autoAppend: false,
			children: [
				new AnimalsGame.Actor({
					filename: 'continue',
					path: 'assets/images/buttons',
					filenameHover: 'continue-hover',
					className: 'dialog-button right-answer-dialog-button',
					interactive: false,
					autoAppend: false
				})
			]
		});
		
		AnimalsGame.OnloadObserver.queueHandler((function() {
			$(AnimalsGame.STAGE).append(this.dialog.element);
		}).bind(this));
		
		this.stageElements.push(this.dialog);
	},
	
	handleNextQuestion: function() {
		this.questionStageElements.each('destroy');
		this.dialog.destroy();
		this.nextQuestion();
	},
	
	triggerWrongAnswer: function() {
		var this_ = this;
		
		this_.killInterval();
		
		Progress.sections[ this.sectionName ].goodAnswers && Progress.sections[ this.sectionName ].goodAnswers--;
		
		game.soundEffect.play('try-again');
		
		var $lastDoneStar;
		if ($lastDoneStar = $(this.progressStars.element).first('li:not(.done)').prev()) {
			$lastDoneStar.removeClass('done').children('span')[0].fade('out', { duration: 'short' });
		}
		
		this.questionStageElements.each('deactivate');
		
		this.dialog = new AnimalsGame.Actor({
			filename: 'wrong-answer',
			path: 'assets/images/dialogs',
			className: 'dialog wrong-answer-dialog',
			click: this.handleNextQuestion.bind(this),
			autoAppend: false,
			children: [
				new AnimalsGame.Actor({
					filename: 'continue',
					path: 'assets/images/buttons',
					filenameHover: 'continue-hover',
					className: 'dialog-button wrong-answer-dialog-button',
					click: this.handleNextQuestion.bind(this),
					interactive: false,
					autoAppend: false
				})
			]
		});
		
		AnimalsGame.OnloadObserver.queueHandler((function() {
			$(AnimalsGame.STAGE).append(this.dialog.element);
		}).bind(this));
		
		this.stageElements.push(this.dialog);
	},
	
	nextQuestion: function() {
		if (Progress.sections[ this.sectionName ].goodAnswers < 10) {
			Progress.sections[ this.sectionName ].currentQuestion++;
			
			this.createQuestion();
		} else {
			Progress.sections[ this.sectionName ].currentQuestion = 1;
			Progress.sections[ this.sectionName ].goodAnswers = 0;
			this.section.triggerLevelFinish();
		}
	},
	
	computeTextSize: function(string) {
		if (string.length > 11)
			return ' smallest-text';
		
		if (string.length > 9)
			return ' smaller-text';
		
		if (string.length > 7)
			return ' small-text';
		
		return '';
	},
	
	destroy: function() {
		this.questionStageElements.each('destroy');
		// this.questionStageElements = null;
		
		this.stageElements.each('destroy');
		// this.stageElements = null;
		
		clearTimeout(this.interval);
		this.interval = null;
	}
	
});
