﻿var quizItems = [];
var item = null;
var correctAnswers = 0;

function getJsPath() {
  var script = $$('script').filter(function(script) {
    return script.get('src') && script.get('src').split('/').getLast() == 'quiz.js';
  })[0]
  
  if(script) {
    var path = script.get('src').split('/')
    return path.slice(0, path.length-1).join('/');
  }
  
  return '';
}

var Quiz = new Class({
  initialize: function(element) {
    this.element = $(element);
    this.showLoader();
    this.requestQuizItems();
  },
  
  clear: function() {
    this.element.innerHTML = '';
  },
  
  showLoader: function() {
    this.clear();
    
    var size = this.element.getSize();
    var img = new Element('div').inject(this.element);
    img.setStyles({'width': size.x + 'px', 'height': size.y + 'px', 'position': 'absolute', 'left': '0px', 'top': '0px'});
    img.setStyle('background', 'transparent url(\'' + getJsPath() + '/../images/loader.gif\') center center no-repeat');
  },
  
  requestQuizItems: function() {
	
		var myURI = new URI();
		quiz_id = myURI.get('file');

    var jsonRemote = new Request.JSON({
      url: '/quiz_items/'+quiz_id,
      onSuccess: this.loadQuizItems.bind(this)
    });
    jsonRemote.get();
  },
  
  loadQuizItems: function(response, status) {
    this.questions = response;
    this.questions.each(function(question) {
      question['answers'] = [];
      for(var i = 1; i < 5; i++) {
        if(question['field_text_' + i + '_value']) {
          question['answers'].push(question['field_text_' + i + '_value']);
          if(question['field_correct_' + i + '_value'] == 'Correct')
            question['correct'] = i-1;
        }
      }
    });
        
    // fisherYates(this.questions);
    this.nextQuestion();
  },
  
  nextQuestion: function() {
    if(!this.question) {
      this.question = this.questions[0];
    } else {
      this.question = this.questions[this.questions.indexOf(this.question)+1];
    }
    
    if(!this.question) this.question = this.questions[0];

    this.displayQuestion();
  },

	showScore: function()
	{
		this.clear();
		
		if (correctAnswers >= 0 && correctAnswers <= 4)
		{
			scoreElement = new Element('h3', {'html': '0-4: Could do better!'});
			scoreHint = new Element('h3', {'class': 'wide', 'html': 'Build your Asia awareness by regularly visiting <a href="http://www.asianz.org.nz">www.asianz.org.nz</a>'});
		}
		if (correctAnswers >= 5 && correctAnswers <= 7)
		{
			scoreElement = new Element('h3', {'html': '5-7: A good effort! '});
			scoreHint = new Element('h3', {'class': 'wide', 'html': 'Improve your Asia awareness by regularly visiting <a href="http://www.asianz.org.nz">www.asianz.org.nz</a>'});
		}
		if (correctAnswers >= 8)
		{
			scoreElement = new Element('h3', {'html': '8-10: Congratulations, you are Asia Aware! '});
			scoreHint = new Element('h3', {'class': 'wide', 'html': 'Keep your Asia awareness honed by regularly visiting <a href="http://www.asianz.org.nz">www.asianz.org.nz</a>'});
		}
		scoreElement.inject(this.element);
		scoreHint.inject(this.element);
	},
  
  displayQuestion: function() {
    this.clear();
		
    this.setQuestion(this.question['title']);    
    this.questionList = new Element('ul').inject(this.element);
    
    this.question.answers.each(function(answer, index) {
      this.addAnswer(answer, index);
    }.bind(this));

		if (this.question['field_question_image_fid'] != '')
		{
			imageElement = new Element('img', {'src': '/'+this.question['field_question_image_fid']});
			imageElement.inject(this.element);
		}
		
		questionElement = new Element('p', {'html': 'Question ', 'class': 'counter'});
		questionCountElement = new Element('span', {'html': this.questions.indexOf(this.question) + 1 + ' '});
		questionOfElement = new Element('span', {'html': 'of ' + this.questions.length});
		questionCountElement.inject(questionElement);
		questionOfElement.inject(questionElement);
		questionElement.inject(this.element);
		
		correct = new Element('p', {'html': 'Score: '+correctAnswers+' / '+this.questions.length, 'class':'correct'})
		correct.inject(this.element);
  },
  
  setQuestion: function(text) {
    (new Element('h3', {'html': text})).inject(this.element);
  },
  
  addAnswer: function(answer, index) {
    var li = new Element('li', {'class': 'answer'}).inject(this.questionList);
    var as = new Element('a', {'href': '#'}).inject(li);
		var aspan = new Element('span', {'html': answer}).inject(as);
    as.addEvent('click', function(event) {
      $(event.target).addClass('clicked');
      
      setTimeout(function() {
        this.answerClicked(index);
      }.bind(this), 500);
      
      return false;
    }.bind(this));
  },

  addNoLinkAnswer: function(answer, index) {
    var li = new Element('li', {'class': 'answer'}).inject(this.questionList);
		var span = new Element('span', {'html': answer}).inject(li);

  },
  
  answerClicked: function(index) {

    this.clear();


    if(index == this.question.correct) {
			correctAnswers++;
      this.displayCorrect(index);
    } else {
      this.displayIncorrect(index);
    }

		if(this.questions.indexOf(this.question) + 1 < this.questions.length)
		{
	    this.displayNextButton();
		}
		else
		{
	    this.displayScoreButton();    
		}
  },
    
  displayCorrect: function(index) {
		
    this.setQuestion(this.question['title']);    

    this.questionList = new Element('ul').inject(this.element);
    		
    this.question.answers.each(function(answer, index) {
      this.addNoLinkAnswer(answer, index);
    }.bind(this));

		answers = $$('li.answer');
		selected = index;
		correctElement = this.question.correct;
		
		answers.each(function(answer, index) {
		
			if (index != correctElement)
			{
				answer.addClass('incorrect');
			}
			else
			{
				answer.addClass('correct');
			}
			
			if (selected == index)
			{
				answer.addClass('selected');
			}
		});

		responseMsg = this.question['field_correct_response_value'];
		responseElem = new Element('div', {'html': responseMsg, 'class': 'response'});
		responseElem.inject(this.element);

		questionElement = new Element('p', {'html': 'Question ', 'class': 'counter'});
		questionCountElement = new Element('span', {'html': this.questions.indexOf(this.question) + 1 + ' '});
		questionOfElement = new Element('span', {'html': 'of ' + this.questions.length});
		questionCountElement.inject(questionElement);
		questionOfElement.inject(questionElement);
		questionElement.inject(this.element);

		correct = new Element('p', {'html': 'Score: '+correctAnswers+' / '+this.questions.length, 'class':'correct'});
		correct.inject(this.element);

  },
  
  displayIncorrect: function(index) {
    this.setQuestion(this.question['title']);    

    this.questionList = new Element('ul').inject(this.element);
    
    this.question.answers.each(function(answer, index) {
      this.addNoLinkAnswer(answer, index);
    }.bind(this));

		answers = $$('li.answer');
		selected = index;
		correctElement = this.question.correct;
		
		answers.each(function(answer, index) {

			if (index != correctElement)
			{
				answer.addClass('incorrect');
			}
			else
			{
				answer.addClass('correct');
			}
			
			if (selected == index)
			{
				answer.addClass('selected');
			}
		});

		responseMsg = this.question['field_incorrect_response_value'];
		responseElem = new Element('div', {'html': responseMsg, 'class': 'response'});
		responseElem.inject(this.element);

		questionElement = new Element('p', {'html': 'Question ', 'class': 'counter'});
		questionCountElement = new Element('span', {'html': this.questions.indexOf(this.question) + 1 + ' '});
		questionOfElement = new Element('span', {'html': 'of ' + this.questions.length});
		questionCountElement.inject(questionElement);
		questionOfElement.inject(questionElement);
		questionElement.inject(this.element);
		
		correct = new Element('p', {'html': 'Score: '+correctAnswers+' / '+this.questions.length, 'class':'correct'})
		correct.inject(this.element);

  },
  
  displayNextButton: function() {
		var nextBtn = new Element('a', {'class': 'next button', 'href': '#'});
		var spanNext = new Element('span', {'html': 'Next'});
		spanNext.inject(nextBtn);
		
    nextBtn.inject(this.element);
    nextBtn.addEvent('click', function(event) {
      this.nextQuestion();
      return false;
    }.bind(this));
  },

  displayScoreButton: function() {
		var resultBtn = new Element('a', {'class': 'result button', 'href': '#'});
		var spanResult = new Element('span', {'html': 'Result'});
		spanResult.inject(resultBtn);
		
    resultBtn.inject(this.element);
    resultBtn.addEvent('click', function(event) {
      this.showScore();
      return false;
    }.bind(this));
  }

});

function fisherYates ( myArray ) {
  var i = myArray.length;
  if ( i == 0 ) return false;
  while ( --i ) {
     var j = Math.floor( Math.random() * ( i + 1 ) );
     var tempi = myArray[i];
     var tempj = myArray[j];
     myArray[i] = tempj;
     myArray[j] = tempi;
   }
}

function initQuiz() {
  var elements = $$('div.quiz');
  
  if(elements.length > 0)
    new Element('link', {'rel': 'stylesheet', 'href':getJsPath()+'/../css/quiz.css','type':'text/css','media':'screen','charset':'utf-8'}).inject($$('head')[0]);
  
  elements.each(function(element) {
    var quiz = new Quiz(element);
  });
}

window.addEvent('domready', initQuiz);
