// javascript/ajax.jssp


function populateDropdownFromForm(formId, dropdownId, address)
{
  $.post(address, $(formId).serialize(), function(data){
    $(dropdownId).text("");
    $(dropdownId).append(data);
    $(dropdownId).trigger('liszt:updated');
  });
}

function postForm(address, formId)
{
  $.post(address, $(formId).serialize());
}

function post(address)
{
  $.post(address);
}

function post(address, parameters)
{
  $.post(address,parameters);
}

function postFormAndAlertReply(address, formId)
{
  $.post(address, $(formId).serialize(), function(data){
    showInfoAlert(data);
  });
}

function postAndAlertReply(address)
{
  $.post(address,function(data){
    showInfoAlert(data);
  });
}

function postAndAlertReply(address, parameters)
{
  $.post(address,parameters,function(data){
    showInfoAlert(data);
  });
}

function postFormAndCall(address, formId, callFunction)
{
  $.post(address, $(formId).serialize(), function(data){
    callFunction(data);
  });
}

function postAndPopupReply(address)
{
  $.post(address,function(data){
    showSystemPopup(data);
  });
}

function postAndPopupReply(address, parameters)
{
  $.post(address,parameters,function(data){
    showSystemPopup(data);
  });
}

function postFormAndPopupReply(address, formId)
{
  $.post(address, $(formId).serialize(), function(data){
    showSystemPopup(data);
  });
}

function postAndCall(address, callFunction)
{
  $.post(address,function(data){
    callFunction(data);
  });
}

function postAndCall(address, parameters, callFunction)
{
  $.post(address,parameters,function(data){
    callFunction(data);
  });
}

function showInfoAlert(message)
{
  var popup = document.getElementById('infoAlert');
  popup.style.left = ($(window).width()+$(window).scrollLeft() -310)+'px';
  popup.style.top = ($(window).height()+$(window).scrollTop() - 150)+'px';
  
  document.getElementById('infoAlertUserMessage').innerHTML=message;
  
  if(popup.style.display=='none')
  {
    $('#infoAlert').fadeIn('slow');
  }
  
  setTimeout('hideInfoAlert(false)',10000);
}

function hideInfoAlert()
{
  hideInfoAlert(false);
}

function hideInfoAlert(quick)
{
  var popup = document.getElementById('infoAlert');
  
  if(quick)
  {
    popup.style.display='none';
  }
  else
  {  
    $('#infoAlert').fadeOut('slow');
  }
}

function showSystemPopup(message)
{
  var popup = document.getElementById('systemPopup');
  popup.style.left = (($(window).width()/2)+$(window).scrollLeft() -300)+'px';
  
  document.getElementById('systemPopupUserMessage').innerHTML=message;
  
  if(popup.style.display=='none')
  {
    $('#systemPopup').fadeIn('slow');
  }
}

function hideSystemPopup()
{
  hideInfoAlert(false);
}

function hideSystemPopup(quick)
{
  var popup = document.getElementById('systemPopup');
  
  if(quick)
  {
    popup.style.display='none';
  }
  else
  {  
    $('#systemPopup').fadeOut('slow');
  }
}

function fillEmailField()
{
  var irmsVal = '';
  if($('#irmsGroup').size() > 0 && $('#irmsGroup').val() != "")
  {
    irmsVal = $('#irmsGroup').val();
  }
  else
  {
    irmsVal = $('#irms').val();
  }
  
  var facVal = '';
  if($('#homeSiisFacilityId').size() > 0 && $('#homeSiisFacilityId').val() != "")
  {
    facVal = $('#irmsGroup').val();
  }
  else
  {
    facVal = $('#siisFacilityId').val();
  }

  $.ajax({
      url: "irmsContactEmail.do2",
      type: "POST",
      data: {irms:  irmsVal, fac: facVal, vfc: $('#vfc_pin').val()},
      dataType: "text",
      success: function(data)
      {
        $('#email').val(data);
      }
  });
}

function convertToString(today)
{
  var dd = today.getDate();
  var mm = today.getMonth()+1; //January is 0!
  var yyyy = today.getFullYear();
  
  if(dd<10) {
      dd='0'+dd
  } 
  
  if(mm<10) {
      mm='0'+mm
  } 
  
  today = mm+'/'+dd+'/'+yyyy;
  return today;
}

function checkReportingMonth(noswitch)
{
  //if the following variable is 1 the toDate will be populateed.
  var populateToDate = 0;
  //Get today's date
  var today = new Date();

  var irmsVal = '';
  if($('#irmsGroup').size() > 0 && $('#irmsGroup').val() != "")
  {
    irmsVal = $('#irmsGroup').val();
  }
  else
  {
    irmsVal = $('#irms').val();
  }
  
  var facVal = '';
  if($('#homeSiisFacilityId').size() > 0 && $('#homeSiisFacilityId').val() != "" && $('#facilityGroup').is(':checked'))
  {
    facVal = $('#homeSiisFacilityId').val();
  }
  else
  {
    facVal = $('#siisFacilityId').val();
  }

  if(irmsVal == '' || $('select[name=reportingMonth]').val() == '-1')
  {
    return;
  }
  $.ajax({
    url: "vaccAdminCheckReportingMonth.do2",
    type: "POST",
    data: {irms:  irmsVal, fac: facVal, vfc: $('#vfc_pin').val(), month: $('select[name=reportingMonth]').val()},
    dataType: "text",
    success: function(data)
    {
      if(data == '')
      {
        $('#fromVaccDate').removeAttr("readonly");
        $('#fromVaccDate').css("backgroundColor", "white");
        $('#toVaccDate').removeAttr("readonly");
        $('#toVaccDate').css("backgroundColor", "white");
        $('#selectedReport').val('');
        
        var irmsVal = '';
        if($('#irmsGroup').size() > 0 && $('#irmsGroup').val() != "")
        {
          irmsVal = $('#irmsGroup').val();
        }
        else
        {
          irmsVal = $('#irms').val();
        }
        
        var facVal = '';
        if($('#homeSiisFacilityId').size() > 0 && $('#homeSiisFacilityId').val() != "" && $('#facilityGroup').is(':checked'))
        {
          facVal = $('#homeSiisFacilityId').val();
        }
        else
        {
          facVal = $('#siisFacilityId').val();
        }
        checkDateBox();
        
        $.ajax({
          url: "irmsLastSubmitDate.do2",
          type: "POST",
          data: {irms:  irmsVal, fac: facVal, vfc: $('#vfc_pin').val()},
          dataType: "text",
          success: function(data)
          {
            if(data == '')
            {
              $('#fromVaccDate').removeAttr("readonly");
            }
            else
            {
              var returnValues = data.split(",");
              $('#fromVaccDate').val(returnValues[0]);

              // split the date in array
              var lastToDateArray = returnValues[0].split('/');
              //Create a date obj
              var lastToDate = new Date(lastToDateArray[2], lastToDateArray[0]-1, lastToDateArray[1]);
              //add 45 days to the from date
              lastToDate.setDate(lastToDate.getDate() + 45);
              // if current date is less than the from date+45 then populate the current date.
              $('#toVaccDate').val(convertToString(lastToDate));
              if(!(today > lastToDate))
              {
                $('#toVaccDate').val(convertToString(today));
              }

              if(returnValues[1] != '') 
              {
                $('#fromVaccDate').attr("readonly", "readonly");
              }
              else
              {
                $('#fromVaccDate').removeAttr("readonly");
              }
            }
          }
        });
      }
      else
      {
        var returnValues = data.split(",");
      
        $('#fromVaccDate').val(returnValues[1]);
        $('#toVaccDate').val(returnValues[2]);
        
        if(returnValues[3] != '') 
        {
          $('#fromVaccDate').css("backgroundColor", "gray");
          $('#fromVaccDate').prop("readonly", true);
          $('#toVaccDate').css("backgroundColor", "gray");
          $('#toVaccDate').prop("readonly", true);
        }
        else
        {
          $('#fromVaccDate').removeAttr("readonly")
          $('#fromVaccDate').css("backgroundColor", "white");
          $('#toVaccDate').removeAttr("readonly");
          $('#toVaccDate').css("backgroundColor", "white");
        }

        $('#selectedReport').val(returnValues[0]);
        $('#vaccDateRangeCheckBox').prop('checked', true);
        checkDateBox();
        if(returnValues[3] != '')
        { 
          if(returnValues[4] == 'Y')
          {
            alert("A Vaccine Administered Report was already submitted for this Reporting Month. You can edit this report and resubmit if needed.");
          }
          else
          {
            alert("The Vaccine Administered Report was already submitted for this Reporting Month. You can no longer edit this report because more than 30 days have past since you last submitted or you have already submitted for next reporting month. Please submit for a new reporting month.");
          }
        }
      }
    }
  });
}

function checkDateBox()
{
  $('#vaccDateRangeCheckBox').prop('checked', true);
}

 function populateInsuredInfo()
{
  
  var ageIndexVal = $(this).attr('id').split('_')[1];
  var numOfPatVal = $.trim($(this).text());
  var irmsVal = '';
  var self = this;
  var incAdults = $('#includeAdults').val();
  var includeLtOneVal = $('#includeLtOne').val();
  var include1To2Val = $('#include1To2').val();
  var include3To6Val = $('#include3To6').val();
  var include7To18Val = $('#include7To18').val();
  var limitByVaccDateVal = $('#limitByVaccDate').val();
  var vaccFromDateVal = $('#vaccFromDate').val();
  var vaccToDateVal =  $('#vaccToDate').val();
  var wyVipVal =  $('#wyVip').val();
  
  if($('#irmsGroupId').size() > 0 && $('#irmsGroupId').val() != "")
  {
    irmsVal = $('#irmsGroupId').val();
  }
  else
  {
    irmsVal = $('#irmsId').val();
  }
  var facVal = '';
  if($('#homeSiisFacilityId').size() > 0 && $('#homeSiisFacilityId').val() != "")
  {
    facVal = $('#homeSiisFacilityId').val();
  }
  else
  {
    facVal = $('#siisFacilityId').val();
  }
  $.ajax({
      url: "retrieveInsuredInfo.do2",
      type: "POST",
      data: {irmsId:  irmsVal, facId: facVal, ageIndex: ageIndexVal, numOfPatients: numOfPatVal, includeAdults: incAdults, 
            includeLtOne: includeLtOneVal, include1To2: include1To2Val, include3To6: include3To6Val, include7To18: include7To18Val, 
            limitByVaccDate: limitByVaccDateVal, vaccFromDate: vaccFromDateVal, vaccToDate: vaccToDateVal, wyVip: wyVipVal},
      dataType: "text",
      success: function(data)
      {
        if(data == '')
        {
          data == "<Strong>N/A</Strong>";
        }
        else
        {
          $(self).attr('title',data);
          $(self).stop().tooltip({ position: { my: "left", at: "top", of:$(self)}}).stop();
        }
      }
  }); 
}

function multiEmailAddressValidator(element)
{
    var prefix = "/iweb/";
    var imgSrc = $("#multiValidateSpinner img").attr("src");
    var spinnerSrc = imgSrc.substring(0, imgSrc.lastIndexOf('/') + 1) + "ajax-loader.gif";
    var checkSrc = imgSrc.substring(0, imgSrc.lastIndexOf('/') + 1) + "Yes_check.png";
    $("#multiValidateSpinner img").attr("src", spinnerSrc);
    if (element.value)
    {
      $("#multiValidateSpinner img").show();
      handleMultiValidationReply(element.value, checkSrc, element);
      return false;
    }
    else
    {
      $("#multiValidateSpinner img").hide();
      alert("Please enter one or more email addresses before pressing Validate");
    }
}

function handleMultiValidationReply(emails, checkmarkSrc, element)
{
    var badEmailsString = validateMultipleEmail(emails);
    if (badEmailsString == "")
    {
      $("#multiValidateSpinner img").attr("src", checkmarkSrc);
      return;
    }
    // Otherwise we need to alert the user of the error
    $("#multiValidateSpinner img").hide();
    element.focus();

    alert("The following email addresses are invalid:\n" + badEmailsString +
          "A correct email format is: username@domain.org with max length 64 for username, 255 for domain name.");
}

function retrieveAlbertaReturnDepots(type, orig, init)
{
  if($('#stateCode').val() != 'AB')
  {
    return;
  }

  $('#origValue').val(type);
  if(type == orig && type != '')
  {
    return;
  }
  else if(type != 'AHSDEPOT' && orig !='AHSDEPOT' && init == '')
  {
    return;
  }
  else if(type == 'AHSDEPOT' && orig =='AHSDEPOT' && init == '')
  {
    return;
  }
  $.ajax({
      url: "albertaReturnDepotSelection.do2",
      type: "POST",
      data: {type:  type},
      dataType: "text",
      success: function(data)
      {
        $("#lhzPvdReturnDepotsSelection").empty();
        var selectVal = '<option value="-1">--select--</option>';
        $("#lhzPvdReturnDepotsSelection").append(selectVal);
        var valueList = data.split(';');
        for(var i = 0; i < valueList.length; i++)
        {
          if(valueList[i] == '')
          {
            break;
          }
          var subValues = valueList[i].split(',');
          var value = subValues[0];
          var label = subValues[1];
          if(init == value && init != '')
          {
            $("#lhzPvdReturnDepotsSelection").append('<option value="' + value + '" selected="true" >' + label + '</option>');
          }
          else
          {
            $("#lhzPvdReturnDepotsSelection").append('<option value="' + value + '" >' + label + '</option>');
          }
        }
        $("#lhzPvdReturnDepotsSelection").trigger('liszt:updated');
        
        if(init == '')
        {
          $("#assignedReturnDepotIrmsSysId").val('');
          $("#assignedReturnDepotAsiisFacId").val('');
        }
      }
  }); 
}

function createNewCohort()
{
  if ($("#cohortName").val() == '')
  {
   $(".dialogErrorMsg").html("Error: New Cohort requires name"); 
  }
  else
  {
    $.ajax({
           url: "newCohortCreation.do2",
           type: "POST",
           data: {cohortName: $("#cohortName").val()},
           dataType: "text",
           success: function(data)
           {
             if (data.indexOf("Success") > -1)
             {
               $('.outputmsg').html('<ul><li><span class="redalert">New Cohort created</span></li></ul>');
             }
             else
             {
               $('.outputmsg').html('<ul><li><span class="redalert">Error while creating new Cohort</span></li></ul>');
             }
             $('#reminderRecallScheduler').dialog('close');
             $('html,body').scrollTop(0); 
           }
    });
  }
}