var QUIZ_INSIGHT = 1;
var QUIZ_THERAPY = 2;
var QUIZ_CHALLENGE = 3;
var QUIZ_INKBLOTS = 4;

$().ready(function () {
  var el;
  if (el = document.getElementById('order-btn')) {
    el.onclick = function (e) {
      return pop(this, '', 'width=800,height=600,location,menubar,resizable,scrollbars,status,toolbar');
    };
  }
});

function Quizzer (type, url, callback, parentEl) {
  this.callback = callback;
  this.parentEl = parentEl;
  this.type = type;
  
  this.index = -1;
  this.answers = {};
  this.currentPage = null;
  
  var o = this;
  
  if (url) {
    var query = null;
    if (url.split('?')[1]) {
      query = url.split('?')[1];
    }
    $.getJSON(url, query, function (json) { o.parseJSON(json); });
  }
}

var proto = Quizzer.prototype;

proto.parseJSON = function (json) {
  if (json && (json.length || json.questions.length)) {
    if (QUIZ_CHALLENGE === this.type) {
      this.quiz = json.questions;
      this.name = json.name;
      this.email = json.email;
    }
    else {
      this.quiz = json;
    }
    this.showNext();
  }
}

proto.getScore = function() {
  var score = 0;
  var quiz = this.quiz;
  
  $.each(this.answers, function(i, n) {
    if (n == quiz[i].answer) score++;
  });
  return score;
}

proto.getLength = function() {
  var i = 0;
  $.each(this.answers, function(_i, n) {
    i++;
  });
  return i;
}
proto.showNext = function () {
  this.index++;
  
  if (this.index + 1 > this.quiz.length) {
    this.callback(this.answers);
    return;
  }
  
  var o = this;
  var newPage = new QuizPage(
    this.quiz[this.index], function (answer) { o.pushAnswer(answer); }, this
  );
  
  if (this.currentPage) {
    this.currentPage.hide();
  }
  this.parentEl.appendChild(newPage.page);
  newPage.show();
  this.currentPage = newPage;
}

proto.pushAnswer = function (answer) {
  this.answers[this.index] = answer;
  this.showNext();
}

function QuizPage (quizItem, callback, _quizzer) {
  this.item = quizItem;
  this.callback = callback;
  this.quizzer = _quizzer;
  
  var o = this;
  
  var outer = document.createElement('div');
  outer.className = 'page page-quiz page-quiz-'+ this.getColor();
  outer.style.display = 'none';
  
  var inner = document.createElement('div');
  inner.className = 'page-inner';
  outer.appendChild(inner);
  
  var h1 = document.createElement('h1');
  h1.innerHTML = this.item.category.toUpperCase();
  //h1.style.display = 'none';
  outer.appendChild(h1);
  
  if (QUIZ_INKBLOTS == this.quizzer.type) {
    var inkblot = document.createElement('div');
    inkblot.innerHTML = '<img src="inkblots/'+ this.item.inkblotPath +'">';
    inkblot.className = 'inkblot';
    inner.appendChild(inkblot);
  }
  else {
    var dropCap = document.createElement('div');
    dropCap.innerHTML = 'Q.';
    dropCap.className = 'dropcap';
    inner.appendChild(dropCap);
    //inner.style.display = 'none';
  }
  
  var col = this.col = document.createElement('div');
  col.className = 'column';
  inner.appendChild(col);
  
  var q = document.createElement('p');
  q.className = 'question';
  if (QUIZ_INSIGHT === this.quizzer.type || QUIZ_INKBLOTS == this.quizzer.type) {
    q.innerHTML = this.item.question;
  }
  else if (QUIZ_THERAPY === this.quizzer.type) {
    q.innerHTML = this.item.question.replace(/%s/, form1.name.value.split(' ')[0]);
  }
  else {
    q.innerHTML = this.item.question.replace(/%s/, this.quizzer.name.split(' ')[0]);
  }
  
  if (QUIZ_CHALLENGE === this.quizzer.type) {
    var p = document.createElement('p');
    p.className = 'preq';
    p.innerHTML = 'Guess how %s answered this question:'.replace(/%s/, this.quizzer.name.split(' ')[0]);
    col.appendChild(p);
  }
  col.appendChild(q);
  
  var choices = document.createElement('ol');
  var madeChoice = false;
  $.each(this.item.choices, function(i, choice) {
    var a = document.createElement('a');
    a.href = '#';
    
    if (QUIZ_THERAPY !== o.quizzer.type) {
      a.onclick = function(e) { return o.setAnswer(i) }
    }
    else {
      a.onclick = function(e) {
        if (!madeChoice) {
          this.style.fontWeight = 'bold';
          madeChoice = true;
        }
        return o.setAnswer(i);
      }
    }
    
    a.innerHTML = choice;
    
    var li = document.createElement('li');
    li.appendChild(a);
    if (quizItem.notes) {
      var span = document.createElement('span');
      span.className = 'note';
      span.innerHTML = ' ('+ quizItem.notes[i] +')';
      li.appendChild(span);
      span.style.display = 'none';
    }
    choices.appendChild(li);
  });
  col.appendChild(choices);
  
  this.page = outer;
}

var proto = QuizPage.prototype;

proto.show = function (cb) {
  if (!cb) cb = function() {};
  $(this.page).fadeIn('slow', cb);
}

proto.hide = function (cb) {
  if (!cb) cb = function() {}
  var o = this;
  $(this.page).fadeOut('slow', function () {
    cb();
  });
}

proto.setAnswer = function(answer) {
  var isCorrect = (this.item.answer == answer);
  var o = this;
  
  if (undefined !== this.answer) {
    alert('Click "next question".');
    return false;
  }
  this.answer = answer;
  
  if (QUIZ_THERAPY !== this.quizzer.type) {
    var p = document.createElement('p');
    p.className = 'answer';
    p.style.display = 'none';
    $(p).append('<span class="'+ (isCorrect? 'correct': 'incorrect') +'">'+ (isCorrect? 'Correct!': 'Incorrect.') +'</span>');
    if (QUIZ_CHALLENGE == this.quizzer.type) {
      $(p).append('<br />'+ this.quizzer.name.split(' ')[0] +' answered: <em>'+ this.item.choices[this.item.answer] +'</em>');
    }
    else {
      $(p).append('<br />Answer: <em>'+ this.item.choices[this.item.answer] +'</em>');
    }
    if (this.item.note) {
      $(p).append('&nbsp;('+ this.item.note +')');
    }
    this.col.appendChild(p);
    
    if (this.item.ref) {
      var p3 = document.createElement('p');
      p3.className = 'ref';
      p3.style.display = 'none';
      $(p3).append('<strong>ref:</strong> <span>'+ this.item.ref +'</span>');
      this.col.appendChild(p3);
    }
  }
  
  if (QUIZ_INKBLOTS === this.quizzer.type) {
    $(".page-quiz ol li span.note").each(function(i, span) { span.style.display = 'inline'; });
  }
  
  var a = document.createElement('a');
  a.className = 'next';
  a.href = '#';
  $(a).text('next question '+ String.fromCharCode(187));
  a.onclick = function(e) { return o.callback(answer) }
  
  var p2 = document.createElement('p');
  p2.className = 'next'
  p2.style.display = 'none';
  p2.appendChild(a);
  this.col.appendChild(p2);
  
  if (QUIZ_THERAPY !== this.quizzer.type) {
    $(p).show('slow', function() {
      $(p2).fadeIn('slow');
    });
    if (p3) $(p3).show('slow');
  }
  else {
    $(p2).show();
  }
  
  return false;
}

proto.getColor = function() {
  var cat = this.item.category.toLowerCase();
  var color;
  if (QuizPage._categoryColors[cat]) {
    color = QuizPage._categoryColors[cat];
  }
  else color = 'yellow';
  return color;
}

QuizPage._categoryColors = {
  infancy: 'yellow',
  childhood: 'blue',
  adolescence: 'red',
  adulthood: 'green',
  seniority: 'orange',
  cosmos: 'purple',
  therapy: 'maroon'
};

Array.prototype.shuffle = function( b ) {
 var i = this.length, j, t;
 while( i ) {
  j = Math.floor( ( i-- ) * Math.random() );
  t = b && typeof this[i].shuffle!=='undefined' ? this[i].shuffle() : this[i];
  this[i] = this[j];
  this[j] = t;
 }
 return this;
};

