
$(function(){

  var sliderTime = 300;

  // let's attach some event handlers
  $("div.hidden").hide();
  
  $("#youNo").click(function(){
    $("#nonPatientSection").slideDown(sliderTime);
  });

  $("#youYes").click(function(){
    $("#nonPatientSection").slideUp(sliderTime);
  });
  
  $("#contactMethod").change(function(){
    if ($(this).val() == "phone"){
      $("#emailSection").slideUp(sliderTime);
      $("#phoneSection").slideDown(sliderTime)
    }

    if ($(this).val() == "email"){
      $("#phoneSection").slideUp(sliderTime)
      $("#emailSection").slideDown(sliderTime);
    }

    if ($(this).val() == "both"){
      $("#phoneSection").slideDown(sliderTime)
      $("#emailSection").slideDown(sliderTime);
    }

    if ($(this).val() == ""){
      $("#phoneSection").slideUp(sliderTime)
      $("#emailSection").slideUp(sliderTime);
    }
  });
	
  $("#doctorName").click(function(){
    if ($(this).val() == "Name") $(this).val("");
  });
  
  $("#referralYes").click(function(){
    $("#referralInfo").slideDown(sliderTime)
  });

  $("#referralNo").click(function(){
    $("#referralInfo").slideUp(sliderTime)
  });
  
  $("#doctorName").focus(function(){
    $(this).val("").removeClass("dim");
  });
  
  // select all checkboxes
  $("span#selectAll").click(function(){
    $("#appointments input").each(function(){
      this.checked = "checked";
      SetAppointmentLinks();
    });
  });

  // clear all checkboxes
  $("span#clearAll").click(function(){
    $("#appointments input").each(function(){
      this.checked = "";
      SetAppointmentLinks();
    });
  });
  
  // appointment checkboxes
  $("table#appointments input").click(function(){
    SetAppointmentLinks();
  });

  // show questionnaires
  $("#appointmentReason").change(function(){
    $(".reasonQuestionnaire").slideUp(sliderTime); // clear previous questionnaires
    if ($(this).val() != ""){
      $("#" + $(this).val()).slideDown(sliderTime); // show questionnaire. assumes id of questionnaire = value of option chosen
    }
  });
  
  $("#appointmentType").change(function(){
    if ($(this).val() == "endocrinology"){
      $("#endocrinologySection").slideDown(sliderTime);
	  $("#pulmonologySection").slideUp(sliderTime);
    }
	
	if ($(this).val() == "dialysis"){
      $("#endocrinologySection").slideUp(sliderTime);
	  $("#pulmonologySection").slideUp(sliderTime);
    }
	
    if ($(this).val() == "pulmonology"){
      $("#pulmonologySection").slideDown(sliderTime);
      $("#endocrinologySection").slideUp(sliderTime);
    }
  });

  // validate onblur
  $("form#patientInfo input[validate!=false], form#patientInfo select[validate!=false], form#patientInfo textarea[validate!=false]").each(function(){
    $(this).blur(function(){
      if ($.Form.Validate.IsEmpty($(this))){
        $(this).next().filter(".validationError").remove();
        var label = $(this).prev().filter("label").text();
        var errorMessage = $("<div class=\"validationError\">" + label + " field cannot be empty</div>").hide();
        errorMessage.insertAfter($(this)).slideDown(300);
        retVal = false;
      }
      else{
        $(this).next().filter(".validationError").remove();
      }
    });
  });
  
  $("#email").blur(function(){
    try
    {
      if (!$.Form.Validate.IsEmpty($(this))){
        if(!$.Form.Validate.Email($("#email").val())){
          //$("#email").next().filter("span.validationError").html("We are unable to recognize this email address. Please format like yourname@example.com");
          
          $(this).next().filter(".validationError").remove();
          var label = $(this).prev().filter("label").text();
          var errorMessage = $("<div class=\"validationError\">We are unable to recognize this email address. Please format like yourname@example.com</div>").hide();
          errorMessage.insertAfter($(this)).slideDown(300);

          retVal = false;
        }
        else{
          $(this).next().filter(".validationError").remove();
        }
      }
    }
    catch(e){}
  });
 
  $("#birthDate").blur(function(){
    if ($(this).val() == "__/__/____"){
      $(this).next().filter(".validationError").remove();
      var label = $(this).prev().filter("label").text();
      var errorMessage = $("<div class=\"validationError\">" + label + " field cannot be empty</div>").hide();
      errorMessage.insertAfter($(this)).slideDown(300);
      $(this).val("");
      retVal = false;
    }
  });

  // validate form
  //$("button#bttnSend").click(function(){
  // validate form on submit
  //$("button#bttnSend").click(function(){
  $("form#patientInfo").submit(function(){
    var retVal = true;
    $("form#patientInfo input[validate!=false], form#patientInfo select[validate!=false], form#patientInfo textarea[validate!=false]").each(function(){
      $(this).next().filter("span.validationError").html("");
      if ($.Form.Validate.IsEmpty($(this))){
        $(this).next().filter(".validationError").remove();
        var label = $(this).prev().filter("label").text();
        var errorMessage = $("<div class=\"validationError\">" + label + " field cannot be empty</div>").hide();
        errorMessage.insertAfter($(this)).slideDown(300);
        retVal = false;
      }
      else{
        $(this).next().filter(".validationError").remove();
      }
    });
    if (!IsAppointmentTimeValid()) retVal = false;
    //if (!IsRadioValid()) retVal = false;
    //if (!IsValidDate($("#dobYear"), $("#dobMonth").val(), $("#dobDate").val(), $("#dobYear").val())) retVal = false;
    if ($("#birthDate").val() == "__/__/____"){
      //$("#birthDate").next().filter("span.validationError").html("Field cannot be empty");
      $("#birthDate").next().filter(".validationError").remove();
      var label = $("#birthDate").prev().filter("label").text();
      var errorMessage = $("<div class=\"validationError\">" + label + " field cannot be empty</div>").hide();
      errorMessage.insertAfter($("#birthDate")).slideDown(300);
      $("#birthDate").val("");
      retVal = false;
    }

//    if ($("#doctorName").val() == "Name"){
      //$("#doctorName").next().filter("span.validationError").html("Field cannot be empty");
//      $("#doctorName").next().filter(".validationError").remove();
//      var label = $("#doctorName").prev().filter("label").text();
//      var errorMessage = $("<div class=\"validationError\">" + label + " field cannot be empty</div>").hide();
//      errorMessage.insertAfter($("#doctorName")).slideDown(300);
//      $("#doctorName").val("");
//      retVal = false;
//    }

    // redo the email format validation since the blur event is failing in this case
    if (!$.Form.Validate.IsEmpty($("#email"))){
      if (!$.Form.Validate.IsEmpty($(this))){
        if(!$.Form.Validate.Email($("#email").val())){
          //$("#email").next().filter("span.validationError").html("We are unable to recognize this email address. Please format like yourname@example.com");
          
          $("#email").next().filter(".validationError").remove();
          var label = $("#email").prev().filter("label").text();
          var errorMessage = $("<div class=\"validationError\">We are unable to recognize this email address. Please format like yourname@example.com</div>").hide();
          errorMessage.insertAfter($("#email")).slideDown(300);

          retVal = false;
        }
        else{
          $("#email").next().filter(".validationError").remove();
        }
      }
    }
    return retVal;
  });
  // end events
  
  // initialize year dropdown
  var date = new Date();
  var year = date.getFullYear();
  for (var i = 1905; i < year; i++){
    $('<option value="' + i + '">' + i + '</option>').appendTo("select#dobYear");
  }
  $("select#dobYear option:first").attr("selected", "selected");

  // initialize select all/clear all states
  SetAppointmentLinks();

  function SetAppointmentLinks(){
    // if nothing is checked, hide "clear all"
    if ($("table#appointments input:checked").length == 0) $("span#clearAll").hide();
    
    // if all boxes are checked, hide "select all"
    if ($("table#appointments input:checked").length == 10) $("span#selectAll").hide();

    // reset clear all
    if ($("table#appointments input:checked").length > 0) $("span#clearAll").show();

    // reset select all
    if ($("table#appointments input:checked").length < 10) $("span#selectAll").show();
  }  
  // validate appointment time checkboxes -- at least one checked
  function IsAppointmentTimeValid(){
     $("table#appointments").next().filter("span.validationError").html("");
    var retVal = false;
    $("table#appointments input").each(function(){
      if (this.checked){
        retVal = true;
      }
    });
    
    if (!retVal){
     $("table#appointments").next().filter("span.validationError").html("Please select an appointment time");
    }
    return retVal;
  }
  
  function IsRadioValid(){
    var retVal = false;
    $("form#patientInfo div.radios").each(function(){
      if ($(this).children().filter("input[validate!=false]")[0].checked || $(this).children().filter("input[validate!=false]")[1].checked){
        $(this).next().filter(".validationError").remove();
        retVal = true;
      }
      else {
        var errorMessage = $("<div class=\"validationError\">Please select one option</div>").hide();
        errorMessage.insertAfter($(this)).slideDown(300);

       }
    });
    return retVal;
  }

  function IsValidDate(obj, mm, dd, yy){
    if (isNaN(mm) || mm == "mm"){
      $(obj).next().filter("span.validationError").html("Month must be a number (1 through 12)");
      return false;
    }
    if (mm < 1 || mm > 12){
      $(obj).next().filter("span.validationError").html("Month must be a number (1 through 12)");
      return false;
    }
    if (isNaN(dd) || dd == "dd"){
      $(obj).next().filter("span.validationError").html("Date must be a number (1 through 31)");
      return false;
    }
    if (dd < 1 || dd > 31){
      $(obj).next().filter("span.validationError").html("Date must be a number (1 through 31)");
      return false;
    }
    if (isNaN(yy) || yy == "yyyy"){
      $(obj).next().filter("span.validationError").html("Year must be a number (four digits)");
      return false;
    }
    var date = new Date();
    var year = date.getFullYear();
    if (yy > year){
      $(obj).next().filter("span.validationError").html("Invalid year");
      return false;
    }
  }
});
