// this is awful code that should be server side anyway ugh.
function validate(data,form,options)
{
  var res = true;
  id = $(form).attr('id');
  $('.alert').removeClass('alert');
  $('.alertmsg').remove();
  
  $('.datepicker,.time').each(function()
  {
    var label = $('#label_'+$(this).attr('id'));
    var val = $(this).val();
    var msg = false;

    if(val == "") return;
    
    if($(this).hasClass('datepicker'))
    {
      if(!valid_date(val))
      {
        label.addClass('alert');
        $(this).before('<div class="alertmsg">Invalid date, please use YYYY-MM-DD.</div>');
        res = false;
      }
    }
    else
    if($(this).hasClass('time'))
    {
      if(!valid_time(val))
      {
        label.addClass('alert');
        $(this).before('<div class="alertmsg">Invalid time, please use HH:MM (AM/PM).</div>');
        res = false;
      }
    }
  });

  $('.validate_'+id).each(function()
  {
    var label = $('#label_'+$(this).attr('id'));
    var val = $(this).val();
    var msg = false;
    
    if(!val) msg = $(this).attr('notnull');

    if(msg != "")
    {
      res = false;
      label.addClass('alert');
      $(this).before('<div class="alertmsg">'+msg+'</div>');
    }

  });
  if(window.custom_validate) res = custom_validate();
  if(res) $('#'+id+' input[type=submit]').not('.nodisable').attr('disabled',true);
  return res;
}

function capture_submit(form,ajax)
{
  var response = "#response_"+form.id;
  if(!ajax) return validate(false,form,false);
  else
  {
    if(window.completed) $(form).ajaxSubmit({ target: response, beforeSubmit: validate, success: completed });
    else
    $(form).ajaxSubmit({ target: response, beforeSubmit: validate });
  }
  return false;
}

function date_allow(e)
{
  var code = (e.which) ? e.which : event.keyCode;
  if(code != 45 && code > 31 && (code < 48 || code > 57)) return false;
  return true;
}

function valid_time(time) { return time.match(/^([1-9]|0[1-9]|1[0-2]):([0-5][0-9]) ([AaPp][Mm])$/); }
function valid_date(date) { return date.match(/\d\d\d\d-\d\d-\d\d/); }
