/*******************************************************************************
 * An audio interval quiz.
 ******************************************************************************/

function sortNumber(a, b)
{
return a - b
}

function AudioIntervalQuiz()
{
  this.nNotes = 48; // Number of possible notes.
  this.enabledIntervals = [maj3, p5, octave];
  this.nTries = 0;
  this.nCorrect = 0;

  this.UpdateEnabledIntervals = function() {
    this.enabledIntervals.sort(sortNumber);
    var choicesText = '';
    choicesText += '<ul class="aiqChoicesList">';
    for (var i = 0; i < this.enabledIntervals.length; i++) {
      choicesText += '<li><a href="#" onClick="return aiq.Guess(this)">' + IntervalToLongName(this.enabledIntervals[i]) +
	'</a></li>';
    }
    choicesText += '</ul>';
    choicesText += '<p><a href="javascript:playAgain()" class="aiqActionButton">' +
    '<img src="../images/listen.gif"> Play again</a><p>';
    document.getElementById('aiqChoices').style.display = 'none';
    document.getElementById('aiqChoices').innerHTML = choicesText;

    choicesText = '<ul id="aiqAllIntervalsList">';
    for (var i = 1; i <= 12; i++) {
      var isEnabled = (ArrayIndexOf(this.enabledIntervals, i) != -1);
      var theClass = isEnabled ? 'aiqEnabledInterval' : 'aiqDisabledInterval';
      var checked = isEnabled ? ' CHECKED' : '';
      var actionString = isEnabled ? 'disable' : 'enable';
      var longName = IntervalToLongName(i);
      choicesText += '<li class="' + theClass + '" title="' + longName + '">' +
	'<a href="#" id="aiqInterval' + i +
	'" onClick="return aiq.ToggleInterval(this)" class="' + theClass + '">' +
	'<input type="checkbox"' + checked + '/>' +
	 longName +
	'</a>' +
	'<a href="#" onClick="return aiq.PreviewInterval('+i+')" title="Hear a ' + longName + '">' +
	'<img src="../images/listen.gif"/>' +
	'</a></li>';
    }
    choicesText += '</ul>';
    document.getElementById('aiqChooseIntervals').innerHTML = choicesText;
  }

  this.ToggleInterval = function(el) {
    interval = parseInt(el.id.replace('aiqInterval', ''));
    if (el.className == 'aiqEnabledInterval') {
      ArrayRemove(this.enabledIntervals, interval);
      el.className = 'aiqDisabledInterval';
    } else {
      this.enabledIntervals.push(interval);
      el.className = 'aiqEnabledInterval';
    }
    el.getElementsByTagName('input')[0].checked = true;
    el.parentNode.className = el.className;
    this.UpdateEnabledIntervals();
    this.RemoveOptions();
    return false;
  }

  this.MakeInterval = function () {
    var interval = RandomChoice(this.enabledIntervals);
    var direction = RandomChoice([-1, 1]);
    var harmonic = (this.intervalType.value.indexOf('Harmonic') != -1);

    if (this.intervalDirection.value == 'Up' || harmonic) {
      direction = 1;
    } else if (this.intervalDirection.value == 'Down') {
      direction = -1;
    }

    // ES: Get rid of that 8 when have better samples!
    var startingNoteNum = (direction == 1) ? RandomInt(8, this.nNotes - 1 - interval) :
    RandomInt(8 + interval, this.nNotes - 1);

    var startingNote = NoteNumToName(startingNoteNum, '#', true);
    var secondNote = NoteNumToName(startingNoteNum + interval * direction, '#', true);

    this.answer = IntervalToLongName(interval);
    playInterval(startingNote, secondNote, harmonic);
  }

  this.Guess = function(el) {
    if (el.innerHTML == this.answer) {
      document.getElementById('aiqLastResult').innerHTML = ['Correct!', 'Good job!', 'That\'s right!',
							    'Nice one!', 'Yup!', 'You got it!'][this.nCorrect % 6];
      document.getElementById('aiqLastResult').style.color = 'blue';
      this.nCorrect++;
    } else {
      document.getElementById('aiqLastResult').innerHTML = ['Incorrect', 'Wrong', 'Sorry',
							    'No', 'That\'s not it', 'Nope'][this.nTries % 6] +
      '. Correct answer was ' + this.answer + '.';
      document.getElementById('aiqLastResult').style.color = 'red';
    }
    this.nTries++;
    percentage = Math.round(this.nCorrect / this.nTries * 100);
    document.getElementById('aiqScore').innerHTML = this.nCorrect + ' out of ' + this.nTries + ' (' + percentage + '%)';
    document.getElementById('aiqScore').style.display = 'block';
    this.MakeInterval();
    return false;
  }

  this.EmbedMe = function() {
    loadPlayer();
    this.UpdateEnabledIntervals();
    return false;
  }

  this.FirstInterval = function() {
    this.MakeInterval();
    document.getElementById('aiqQuestion').innerHTML = 'Name the interval:';
    document.getElementById('aiqChoices').style.display = 'block';
    return false;
  }

  // Option class. Potentially reusable in the future.
  function Option(question, choices, inputName) {
    this.GetHtml = function() {
      var ret = '<div class="aiqOption" id="id_' + inputName + '">' +
      '<p>' + this.question + '</p>' +
      '<ul>';

      for (var i = 0; i < this.choices.length; i++) {
	ret += '<li><input type="radio" name="' + this.inputName +
	  '" value="' + this.choices[i] +
	  '" onClick="aiq.SetOption(this)"' +
	  ((i == 0) ? ' CHECKED' : '') +
	  '/>' + this.choices[i] +
	  '</li>';
      }
      ret += '</ul></div>';
      return ret;
    }

    this.question = question;
    this.choices = choices;
    this.value = this.choices[0];
    this.inputName = inputName;

    document.getElementById('aiqOptionsForm').innerHTML += this.GetHtml();
  }

  this.RemoveOptions = function() {
    document.getElementById('aiqChoices').style.display = 'none';
    document.getElementById('aiqLastResult').innerHTML = '';
    document.getElementById('aiqQuestion').innerHTML = '<a href="#" onClick="return aiq.FirstInterval()" class="aiqActionButton"><img src="../images/listen.gif" style="border-style:none"/> Hear interval.</a>';
  }

  this.PreviewInterval = function(interval) {
    // Starting point is arbitrary.
    var harmonic = (this.intervalType.value.indexOf('Harmonic') != -1);
    this.RemoveOptions();
    playInterval(27, 27 + interval, harmonic);
    return false;
  }

  this.SetOption = function(el) {
    for (var i = 0; i < this.options.length; i++) {
      if (el.name == this.options[i].inputName) {
	this.options[i].value = el.value;
	if (this.options[i] == this.intervalType) {
	  if (this.options[i].value.indexOf('Harmonic') != -1) {
	    document.getElementById('id_aiqIntervalDirection').style.display = 'none';
	  } else {
	    document.getElementById('id_aiqIntervalDirection').style.display = 'block';
	  }
	}
	break;
      }
    }
    this.RemoveOptions()
  }


  this.intervalType = new Option('Interval type:', ['Melodic (one note at a time)',
						    'Harmonic (both notes at the same time)'],
				 'aiqIntervalType');
  this.intervalDirection = new Option('Interval direction (only matters when melodic):', [
							      'Up and down (random)',
							      'Up',
							      'Down'
							      ],
				      'aiqIntervalDirection');
  this.options = [this.intervalType, this.intervalDirection];
}

