
// Preload quiz images
var imgArr = new Array(20);
$(window).bind("load", function()
{

  var img = $("#quiz form img");

  for (var i = 0; i < img.length; i++)
  {

    imgArr[i] = new Array(new Image(), new Image());
    // all thumb images
    imgArr[i][0].src = img[i].src;
    // all large images
    imgArr[i][1].src = img[i].src.replace("/thumbs/", "/large/");

  }

});

$(document).ready(function()
{
  // add the getResults() function when the quiz is submitted
  $("#quiz form").submit(function() { return getResults(); });

  // apply hover behaviour to each li
  $("#quiz form ul li").hover(
    function()
    {
      $(this).addClass("hover");
    },
    function()
    {
      $(this).removeClass("hover");
    }
  );

  // find all checkboxes
  $("#quiz form ul li input").each(function()
  {

    // apply the selected class to any checked elements (in case page is reloaded)
    var img = $(this).parent("li").find("img");
    if ($(this).attr("checked") == true)
      img.addClass("selected");

    // hide all checkboxes
    $(this).hide();

  });

  // apply hover behaviour to each img
  $("#quiz form ul li img").hover(
    function()
    {
      this.src = this.src.replace("/thumbs/", "/large/");
    },
    function()
    {
      this.src = this.src.replace("/large/", "/thumbs/");
    }
  // override the default click behaviour
  ).click(function()
  {

    // get the associated checkbox with the image
    var input = $(this).parents("li").find("input");

    if (input.attr("checked") == true)
    {
      $(this).removeClass("selected");
      input.attr("checked", false);
    }
    else
    {
      $(this).addClass("selected");
      input.attr("checked", true);
    }

    // make sure the normal click event does not happen
    return false;

  });

});

function getResults()
{

  var len = $("#quiz form input:checked").length;
  var errorMsg;

  if (len == 5)
    return true;
  else
  {
    if (len < 5)
      errorMsg = "Please select 5 images.";
    else
      errorMsg = "Please select only 5 images. Click an image again to un-select it.";

    // append an error message if it doesn't exist
    if ($("#quiz form:has(p#error)").length == 0)
      $("#quiz form").append("<p id='error'>" + errorMsg + "</p>");
    // otherwise just overwrite the text
    else
      $("#quiz form p#error").text(errorMsg);

    return false;
  }

}