function validate(form) {
  
  $('#valid').hide();
  $('#errors').empty();
  
  var ok = true;
  
  var errors = new Array();
  
  var inputs = form.getElementsByTagName('input');
  for (var i=0;i<inputs.length;i++) {
    inputs[i].className = '';
    if (inputs[i].type=='submit') continue;
    if (inputs[i].name=='dic') continue;
    if (inputs[i].type=='checkbox') {
      if (inputs[i].checked==false) {
        inputs[i].className = 'error';
        inputs[i].parentNode.className = 'error';
        errors[errors.length] = 'Musí být udělen souhlas s podmínkami poskytování Služby CRIBIS.cz.';
        ok = false;
      } else {
        inputs[i].parentNode.className = '';
      }
    }
    if (inputs[i].type=='text' && (inputs[i].value=='' || /^\s*$/.test(inputs[i].value))) {
      inputs[i].className = 'error';
      label = $('label[for="'+inputs[i].id+'"]').text();
      label = label.replace(':','');
      errors[errors.length] = "Položka "+label+" nebyla vyplněna.";
      ok = false;
    }
    if (inputs[i].name=='email' && !(/^[_a-zA-Z0-9\.\-]+@[_a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,6}$/.test(inputs[i].value))) {
      inputs[i].value = '';
      inputs[i].className = 'error';
      errors[errors.length] = "E-mail nemá správný tvar.";
      ok = false;
    }
    if (inputs[i].name=='ic' && !validateIc(inputs[i].value)) {
      inputs[i].value = '';
      inputs[i].className = 'error';
      errors[errors.length] = "IČ nemá správný tvar.";
      ok = false;
    }
    if (inputs[i].name=='telefon' && !validateTel(inputs[i].value)) {
      inputs[i].value = '+420';
      inputs[i].className = 'error';
      errors[errors.length] = "Telefon nemá správný tvar.";
      ok = false;
    }
  }
  
  if (ok) {
    $('#submit').hide();
    $('#thanks').show();
  } else {
    for (i=0;i<errors.length;i++) {
      $('#errors').append('<li>'+errors[i]+'</li>');
    }
    $('#valid').show();
  }
  
  return ok;
}

function validateTel(tel) {
  if (tel=='' || /^\s*$/.test(tel)) {
    return true;
  }
  return /^\+[0-9 ]{10,}$/.test(tel);
}

function validateIc(ic) {
    if (ic=='' || /^\s*$/.test(ic)) {
      return true;
    }
    
    ic = ic.replace(/\s+/g, '');

    // má požadovaný tvar?
    if (!ic.match(/^[0-9]{8}$/)) {
        return false;
    }

    // kontrolní součet
    a = 0;
    for (i = 0; i < 7; i++) {
        a += ic[i] * (8 - i);
    }

    a = a % 11;

    if (a == 0) c = 1;
    else if (a == 10) c = 1;
    else if (a == 1) c = 0;
    else c = 11 - a;

    return ic[7] == c;
}