$(document).ready(function(){
  for (var i=1; i<=10; i++){

      $("#a"+i).change(function (){
        if ($(this).val().length > 0){
          if (validateQs($(this))){
            if (allQs()){
              sendForm();
            } else {
              //seperate action just to get university scholarships
              if ($(this).attr('id')=="a1" || $(this).attr('id')=="a3"){
                sendQ1();
              }
            }
          }
        }
        })
        .change();
        
  //  }
  }    
});

function submitForm(){
  if (allQs()){
    sendForm(true);
  }
  else{
    if (validateQs($("#a1"))){
      sendQ1(true);
    }
  }
}

function moreScholarships(){
  if (allQs()){
    sendForm(true);
  }
  else{
    if (validateQs($("#a1"))){
      sendQ1(true);
    }
  }
}

function lessScholarships(){
  if (allQs()){
    sendForm(false);
  }
  else{
    if (validateQs($("#a1"))){
      sendQ1(false);
    }
  }
}

var more = true;
function sendQ1(m){
  if (m != undefined)
    more = m;
  
  $.ajax({
      type: "POST",
      url: ".",
      data: {
          action: 'process',
          answers: $("#a1").serialize() + '&' + $("#a3").serialize(),
          more: more
      },
      success: function(msg){
        $("#results").html(msg);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        if ($("#debug")){
          $("#debug").html(XMLHttpRequest.responseText);
        }
        // typically only one of textStatus or errorThrown 
        // will have info
        this; // the options for this ajax request
      }   
    });
  
}

var sent = false;

function sendForm(m){
  if (m != undefined)
    more = m;

  if (!sent){
    sent = true;
    window.setTimeout('sent=false', 1000);
    
    $.ajax({
      type: "POST",
      url: ".",
      data: {
          action: 'process',
          answers: $("#questions form").serialize(),
          more: more
      },
      success: function(msg){
        $("#results").html(msg);
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        // typically only one of textStatus or errorThrown 
        // will have info
        this; // the options for this ajax request
        $("#ajaxError").html(XMLHttpRequest.responseText);
      }   
    });
    
  }
}
function validateQs(q){
  try{
    switch(parseInt($(q).attr('id').substr(1))){
    case 1:
      if (!($("#a1").val() > 0 && $("#a1").val() < 100)){
        var e = [];
        e['element'] = q;
        e['message'] = "Invalid high school average entered";
        throw e;
      }
      break;
    case 2:
      if (($("#a2").val() == '' || $("#a2").val() == null || $("#a2").val() == 'undefined')){
        var e = [];
        e['element'] = q;
        e['message'] = "Invalid choice of province";
        throw e;
      }
      break;
    case 3:
      if (($("#a3").val() == '' || $("#a3").val() == null || $("#a3").val() == 'undefined')){
        var e = [];
        e['element'] = q;
        e['message'] = "Invalid choice of province";
        throw e;
      }
      break;
    case 4:
      if (($("#a4").val() == '' || $("#a4").val() == null || $("#a4").val() == 'undefined')){
        var e = [];
        e['element'] = q;
        e['message'] = "Invalid field of study chosen";
        throw e;
      }
      break;
    case 5:
      if (($("#a5").val() == '' || $("#a5").val() == null || $("#a5").val() == 'undefined')){
        var e = [];
        e['element'] = q;
        e['message'] = "Invalid answer, please select yes or no";
        throw e;
      }
      break;
    case 6:
      if (!($("#a6").val() > 0 && $("#a6").val() <= 20)){
        var e = [];
        e['element'] = q;
        e['message'] = 'Invalid number of family members';
        throw e;
      }
      break;
    case 7:
      if (!($("#a7").val() >= 0 && $("#a7").val() <= 20)){
        var e = [];
        e['element'] = q;
        e['message'] = 'Invalid number of siblings';
        throw e;
      }
      break;
    case 8:
      if (!($("#a8").val() >= 0 && $("#a8").val() <= 250000)){
         var e = [];
        e['element'] = q;
        e['message'] = 'Invalid amount of savings, please enter a value between 0-250000'; 
        throw e;
      }
      break;
    case 9:
      if (!($("#a9").val() >= 0 && $("#a9").val() <= 250000)){
        var e = [];
        e['element'] = q;
        e['message'] = 'Invalid amount of income, please enter a value between 0-250000'; 
        throw e;
      }
      break;
    case 10:
      if (!($("#a10").val() >= 0 && $("#a10").val() <= 250000)){
        var e = [];
        e['element'] = q;
        e['message'] = 'Invalid amount of income, please enter a value between 0-250000'; 
        throw e;
      }
      break;
    default:
      clearError(q);
      return true;
    }
    clearError(q);
    return true;
  }
  catch(err){
    showError(e['element'], e['message']);
    return false;
  }
}

function clearError(e){
  $(e).parent('li').children('span.error').html('');
}
function showError(e, msg){
  if ($(e).parent('li').children('span.error').length == 0){
    $(e).parent('li').append('<span class="error">'+msg+'</span>');
  } else {
    $(e).parent('li').children('span.error').html(msg);
  }
}
 
function allQs(){
  var allQs = true;
  for (var i=1; i<=10; i++){
    if ($("#a"+i).val().length <= 0 || !validateQs($("#a"+i))){
      allQs = false;
      //exit loop
      i = 20;
    }
  }
  return allQs;
}

