var singlePg = true;
var scor = 0, tmp = -1;
function initest(testype){
  scor = 0;
  tmp = -1;
  $('[name^="qo"]').each(function(){$(this).click(function(){ tmp = parseInt($(this).val(),10); });});
  $('button.startest').click(
    function(){
      if(singlePg) showAll($(this).parent());
      else showNext($(this).parent());
      return false;
    }
  );
  $('button.nextqs').each(
    function(){
      $(this).click(
        function(){
          if(tmp >= 0){
            scor = scor + tmp;
            tmp = -1;
            $('span#re').html(scor);
            showNext($(this).parent());
          }
          return false;
        }
      )
    }
  );
  $('button.showscore').click(
    function(){
      if(singlePg) {
        $('[name^="qo"]:checked').each(function(){ scor += parseInt($(this).val(),10); });
        $('span#re').html(scor);
      }
      var em = $.trim($('#em').val());
      var strsend = testype+","+scor+","+((em=="")?"email not entered":em);
      $.post("test/savetest.php", { myres: strsend } );
      if(singlePg) hideAll($(this).parent());
      else showNext($(this).parent());
      return false;
    }
  );
}

function showNext(currDiv){
  currDiv.fadeTo('fast',0,function(){
    $(this).hide("fast", function(){ $(this).next().fadeTo("slow",1); });
  });
}

function showTest(ttype,testformat){
  singlePg = !(testformat=='multipage');
  $('#lightbox').fadeTo(2000,0.5);        
  $.post("test/test.php",{ testype: ttype}, function(data){
    if(parseInt(data,10) != 0){
      $("#showtest").html('<img id="btncl" src="images/cross.png" alt="Close" /><div id="testqs">'+data+'</div>');
      initest(ttype);
    }else{
      $("#showtest").html('<img id="btncl" src="images/cross.png" alt="Close" /><div class="inf"><h3>Sorry, there was an error loading the test, please try again later.</h3></div>');
    }
    $('img#btncl').click(function(){ hideTest(); });
    $('div.inf').first().fadeTo('slow',1);
    $('#wait').fadeTo('fast',0);
    $.jcorners("#showtest",{radius:10});
    $("#showtest").fadeTo('fast',1);
    //$("#lightbox").click(function(){ hideTest(); });
  });
}

function hideTest(){
  $("#showtest").fadeTo('fast',0, function(){
    $("#lightbox").unbind('click');
    $("#lightbox").fadeTo('slow',0, function(){
      $("#lightbox").hide('fast');
      $('#wait').fadeTo('fast',1);
    });
    $("#showtest").hide('fast');                
  });
}

function showAll(currDiv){
  currDiv.hide('fast');
  $('button.nextqs').each(
    function(){
      $(this).css('display','none');
      $(this).parent().show('fast');
    }
  );
  $('button.showscore').parent().show('fast');
}

function hideAll(currDiv){
  $('button.nextqs').each(
    function(){
      $(this).parent().hide('fast');
    }
  );
  currDiv.hide('fast');
  currDiv.next().fadeTo('slow',1);
}
