// General utilities for QuizBang
// April 2009

function formtag(scriptName) {
  document.write('<form method="post" action="' + cgiroot + scriptName + '">');
}

function formtagGET(scriptName) {
  document.write('<form method="get" target="_top"  action="' + cgiroot + scriptName + '">');
}

function cgiLink(scriptName) {
  document.write('<a href="' + cgiroot + scriptName + '">');
}

function cgiLinkNew(scriptName) {
  document.write('<a href="' + cgiroot + scriptName + '" target=_blank>');
}

function redLink(scriptName) {
  location.replace(cgiroot + scriptName);
}

function setDefDate(obj) {
  if (obj.value == "dd/mm") {
    today = new Date();
    obj.value = today.getDate() + "/" + (today.getMonth() + 1);
  }
}

function anchortag(scriptName, parameters) {
  document.write('<a href="' + cgiroot + scriptName + '?' + parameters + '">');
}

function anchortaghtml(docName) {
  document.write('<a href="' + htmlroot + docName + '">');
}

function putDate() {
  today = new Date();
  fullDate = today.toLocaleString();
  dateOnly = fullDate.slice(0, fullDate.lastIndexOf(" "));
  document.write(dateOnly);
}

function makeEmail(name, host, text) {
  var addy = name + '@' + host;
  if (text == null) { text = addy; }
  document.write('<a href="mailto:' + addy + '">' + text + '</a>');
}

function gup(name)
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return null;
  else
    return results[1];
}

function doLogin() {
  // encrypt the password
  $('password').value = hex_md5($('password').value, 'QuizBang');
  // submit the form
  $('loginForm').submit();
}

function doRegister() {
  // check that the passwords are long enough
  // the rest of the error checking will be done on the server but the plaintext passwords will not be sent
  if ($('password1').value.length < 6) {
    alert("Your password must be at least six characters long.");
    return;
  }
  // submit the form
  new Ajax.Updater('responsePanel', '/cgi-bin/register.pl',
                   { evalScripts: true,
                     parameters: {
                       username:  $('username').value,
                       password1: hex_md5($('password1').value, 'QuizBang'),
                       password2: hex_md5($('password2').value, 'QuizBang'),
                       email:     $('email').value,
                       terms:     $('terms').checked
                     }
                   }
                  );
}

function yabbRegister(username, email, password) {

  var cp = $('yabbRegPanel');

  cp.update('Registering with the forums...');

  new Ajax.Request('/yabb/YaBB.pl?action=register2', {
    method: 'post',
    parameters: {
      username: username,
      passwrd1: password,
      passwrd2: password,
      email:    email,
      regagree: 'yes'
    },
    onSuccess: function(transport) {
      if (transport.responseText.indexOf("Success! You are now a member of the Forum.") != -1) {
        cp.update('You are also registered with the QuizBang forums');
      } else {
        cp.update('There was a problem registering you with the QuizBang forums');
      }
    }
  });

}

function loadQuestions() {
  new Ajax.Updater('quizContainer', '/cgi-bin/showQuiz.pl', { evalScripts: true });
}

function loadQuestionEditor() {
  new Ajax.Updater('editorContainer', '/cgi-bin/editQuestion.pl',
                   { evalScripts: true,
                     parameters: { qid: gup('qid') }
                   }
                  );
}

function loadAccData(doHighlight) {
  new Ajax.Updater('accData', '/cgi-bin/accountBanner.pl',
                   {
                     onComplete: function(transport) {
                        if (doHighlight) { new Effect.Highlight('score'); }
                     }
                   }
  );
}

function loadRecentActivity() {
  new Ajax.PeriodicalUpdater('recentActivity', '/cgi-bin/recentActivity.pl', { frequency: 5, decay: 2 });
}

function loadLeaderBoard() {
  new Ajax.PeriodicalUpdater('leaderBoard', '/cgi-bin/leaderBoard.pl', { frequency: 5, decay: 2 });
}

function loadTagCloud(style) {
  new Ajax.Updater('tagCloud', '/cgi-bin/tagCloud.pl',
                   {
                     parameters: { style: style }
                   }
  );
}

function loadBodyIndex() {
  loadAccData();
  loadRecentActivity();
  loadLeaderBoard();
  loadTagCloud('default');
}

function loadBodyEditQuestion() {
  loadAccData();
}

function loadBodyQuestionHistory() {
  loadAccData();
}

function setAnswer(qnum, i, aid) {
  $('ans' + qnum).value = aid;
  for (var j = 1; j <= 4; j++) {
    if ($('ans' + qnum + '_' + j)) {
      $('ans' + qnum + '_' + j).className = (i == j ? 'answerTextSelected' : 'answerTextUnselected');
    }
  }
  // call check here - answer will be checked as soon as user clicks an answer
  check(qnum);
}

function setHover(qnum, i) {
  var e = $('ans' + qnum + '_' + i);
  e.className += ' answerTextHover';
}

function clearHover(qnum, i) {
  var e = $('ans' + qnum + '_' + i);
  e.className = e.className.replace(/answerTextHover/, '');
}

function check(qnum) {
  var cp = $('qstat' + qnum);

  // show a loading message
  cp.update("<img src='/images/spinner.gif'>Checking...");

  // make the answers non-selectable and disable the hover feedback
  for (var j = 1; j <= 4; j++) {
    if ($('ans' + qnum + '_' + j)) {
      $('ans' + qnum + '_' + j).onclick = null;
      $('ans' + qnum + '_' + j).onmouseover = null;
      $('ans' + qnum + '_' + j).onmouseout = null;
    }
  }

  // check the answer with the server
  new Ajax.Request('/cgi-bin/checkAnswer.pl', {
    method: 'post',
    parameters: { qid: $('qst' + qnum).value, aid: $('ans' + qnum).value },
    onSuccess: function(transport) {
      var parts = transport.responseText.split("--");
      cp.update(parts[1]);
      cp.onclick = null;
      for (var j = 1; j <= 4; j++) {
        if ($('ans' + qnum + '_' + j)) {
          var e = $('ans' + qnum + '_' + j);
          var eid = $('ansID' + qnum + '_' + j);
          e.className += (eid.value == parts[0] ? ' answerTextCorrect' : ' answerTextIncorrect');
        }
      }
      // refresh the account data to show latest score
      loadAccData(true);
      // refresh the recent activity and leader board boxes to reflect this answer
      loadRecentActivity();
      loadLeaderBoard();

    }
  });
}

function addTag(tag) {
  // check for this tag already being in use
  var found = false;
  for (i in tags) { found = found || (tags[i] == tag); }
  if (!found) tags.push(tag);
  moreQuestions();
}

function removeTag(tag) {
  // loop through the tags array and remove the argument if found
  var i;
  for (i=0; i < tags.length; i++) {
    if (tags[i] == tag) tags.splice(i, 1);
  }
  moreQuestions();
}

function removeAllTags() {
  // truncate the tags array
  tags.length = 0;
  moreQuestions();
}

function moreQuestions() {
  if (tags.length > 0) {
    window.location = "/cgi-bin/showQuiz.pl?tags=" + tags.sort().join('.');
  } else {
    window.location = "/cgi-bin/showQuiz.pl";
  }
}

