/* Form validation
 */ 
function validateForm (jQueryForm, notEmpty, selected, emails, passwords) {
  // optional parameter handling
  if (!notEmpty) { notEmpty = null; }
  if (!selected) { selected = null; }
  if (!emails) { emails = null; }
  if (!passwords) { passwords = null; }
  //cleanup
  $('span.error', jQueryForm).remove ();
  $('.invalid', jQueryForm).removeClass ('invalid');
  
  var isValid = true;
  var emptyMessage = '<span class="error">Ovo polje mora biti ispunjeno!</span>';
  var selectMessageOne = '<span class="error">Ovo polje mora biti označeno!</span>';
  var selectMessageMultiple = '<span class="error">Ova polja moraju biti označena!</span>';
  var errorMessage = '<span class="error">Ovo polje nije pravilno ispunjeno!</span>';
  var passwordMessage = '<span class="error">Ponovljena lozinka je krivo unesena!</span>';
 
  // Check if non empty elmeents are empty
  if (notEmpty !== null) {
    for (var i in notEmpty) {
      if (notEmpty[i].val() === '' || notEmpty[i].val() === notEmpty[i].data ('default').value) {
        notEmpty[i]
          .before (emptyMessage)
          .val (notEmpty[i].data ('default').value)
          .markAsInvalid ();
        isValid = false;
      }
    }
  }
  // Check if select elements are properly selcted
  if (selected !== null) {
    var messageShown = false;
    i = 0;
    for (i in selected) {
      if (isArray(selected[i])) {
        for (var j in selected[i]) {
          if (selected[i][j].val() === '0') {
            if (!messageShown) {
              selected[i][0].before (selectMessageMultiple);
              messageShown = true;
            }
            selected[i][j].markAsInvalid ();
            isValid = false;
          }
        }
      }
      else {
        if (selected[i].val() === '0') {
          selected[i]
            .before (selectMessageOne)
            .markAsInvalid ();
          isValid = false;
        }
      }
    }
  }
  // Check if email elements are correctly inputed
  if (emails !== null) {
    i = 0;
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    for (i in emails) {
      if (!filter.test (emails[i].val())) {
        emails[i]
          .before (errorMessage)
          .markAsInvalid ();
        isValid = false;
      }
    }
  }
  // Check if passwords are inputed correctly
  if (passwords !== null) {
    i = 0;
    for (i in passwords) {
      if (passwords[i].password.val() !== passwords[i].confirmation.val()) {
        passwords[i].confirmation
          .before (passwordMessage)
          .markAsInvalid ();
        isValid = false;
      }
    }
  }
  return isValid;
}

/* Avatar validation - dedicated custom function
 */
function validateAvatar (avatar) {
   var avatarMessage = '<span class="error">Nisi odabrao/la avatara!</span>';
  // Check if avatar has been chosen
  if (avatar.attr ('src') === '/img/avatar.jpg') {
    avatar.before (avatarMessage);
    return false;
  }
  else {
    return true;
  }
}
