senseForm = {
  newUberlabels : 0,
  
  checkLogin: function(){
    if (sense.showSpinner){
      return false;
    }
    
    // clear old error messages
    $('span.error').remove();
    $('p.error').removeClass('error');
    
    var minUsernameLength = 3;
    var minPasswordLength = 3;
    
    // We do some basic syntax checking on the data first, no need to go to server
    // if we can dismiss the data right here.
    var syntaxErrorFound = false;
    var username = $('#username').val();
    var password = $('#password').val();
    if (username.length < minUsernameLength){
      senseFormLib.setInputError('username', sprintf(_('Your username must be at least %s characters long'), minUsernameLength));
      syntaxErrorFound = true;
    }
    else if (password.length < minPasswordLength){
      senseFormLib.setInputError('password', sprintf(_('Your password must be at least %s characters long'), minPasswordLength));
      syntaxErrorFound = true;
    }
    
    if (syntaxErrorFound){
      return false;
    }
    
    sense.showSpinner = true;
    $.getJSON("/auth/json_check_login/" + encodeURIComponent(username) + '/' + encodeURIComponent(password),
      function(response){
        if (response.status != true){
          senseFormLib.setInputError('password', _('This combination of username and password is unknown.'));
          return false;
        }
        else {
          if (sense.loginRedirect){
            sense.loginRedirect();
          }
          location.href = '/';
        }
      }
    );
    
  },
  
  checkAccount: function(){
    if (sense.showSpinner){
      return false;
    }
    
    var foundError = false;
    // clear old error messages
    $('span.error').remove();
    $('p.error').removeClass('error');
    
    var emailAddress = $.trim(senseFormLib.getInputValue('email_address'));
    var oldPass = $.trim(senseFormLib.getInputValue('old_pass'));
    var pass1 = $.trim(senseFormLib.getInputValue('pass_1'));
    var pass2 = $.trim(senseFormLib.getInputValue('pass_2'));
    
    if (emailAddress == ''){
      senseFormLib.setInputError('email_address', _('The email address cannot be empty.'));
      foundError = true;
    }
    
    if(oldPasswordNeeded == true && (oldPass != '' || pass1 != '' || pass2 != '')){
      if (oldPass == '' || pass1 == '' || pass2 == ''){
        senseFormLib.setInputError('pass_2', _('Please fill in all the password fields.'));
        foundError = true;
      }
    }
    else{
      if (pass1 == '' || pass2 == ''){
        senseFormLib.setInputError('pass_2', _('Please fill in all the password fields.'));
        foundError = true;
      }
    }
    if (pass1 != pass2){
      senseFormLib.setInputError('pass_2', _('The two new passwords do not match.'));
      foundError = true;
    }

    
    if (foundError){
      return false;
    }
    
    senseFormLib.removeDefaultValues('accountForm');
    
    sense.showSpinner = true;
    $.post('/user/json_process_update_account/', $('#accountForm').serialize(),
      function(result){
        if (result.status == false){
          sense.showDialog(result.message);
        }
        else {
          sense.closePopup();
        }
      }, 'json');
  },
  
  checkRegister: function(){
    if (sense.showSpinner){
      return false;
    }
    
    var foundError = false;
    // clear old error messages
    $('span.error').remove();
    $('p.error').removeClass('error');
    
    var emailAddress = $.trim(senseFormLib.getInputValue('email_address'));
    var pass1 = $.trim(senseFormLib.getInputValue('pass_1'));
    var pass2 = $.trim(senseFormLib.getInputValue('pass_2'));
  
    if (emailAddress == ''){
      senseFormLib.setInputError('email_address', _('The email address cannot be empty.'));
      foundError = true;
    }
    if (emailAddress.indexOf('@') == -1){
      senseFormLib.setInputError('email_address', _('Please provide a valid email address.'));
      foundError = true;
    }
    if (pass1 == '' || pass2 == ''){
      senseFormLib.setInputError('pass_2', _('Please fill in all the password fields.'));
      foundError = true;
    }
    if (pass1 != pass2){
      senseFormLib.setInputError('pass_2', _('The two new passwords do not match.'));
      foundError = true;
    }
    
    
    if (foundError){
      return false;
    }
    
    
    sense.showSpinner = true;
    $.post('/user/json_process_register/', $('#registerForm').serialize(),
      function(result){
        if (result.status == false){
          sense.showDialog(result.message);
        }
        else {
          sense.showPopup('/linked_in/explain_popup');
        }
      }, 'json');
  },
  
  checkResetPassword: function(){
    if (sense.showSpinner){
      return false;
    }
    
    var foundError = false;
    // clear old error messages
    $('span.error').remove();
    $('p.error').removeClass('error');
    
    var emailAddress = $.trim(senseFormLib.getInputValue('email_address'));
    if (emailAddress == ''){
      senseFormLib.setInputError('email_address', _('The email address cannot be empty.'));
      foundError = true;
    }
    
    if (foundError){
      return false;
    }
    
    sense.showSpinner = true;
    $.getJSON("/user/json_send_reset/" + encodeURIComponent(emailAddress),
      function(result){
        if (result.status == false){
          sense.showDialog(result.message);
        }
        else {
          sense.closePopup();
          sense.showDialog(_('A one-time login has been sent to your e-mail address'), _('Please check your mail'));
        }
    });
  },
  
  checkLinkedInCode: function(){
    if (sense.showSpinner){
      return false;
    }
    
    var foundError = false;
    // clear old error messages
    $('span.error').remove();
    $('p.error').removeClass('error');
    
    var code = $.trim(senseFormLib.getInputValue('linked_in_code'));
    if (code == ''){
      senseFormLib.setInputError('linked_in_code', _('Please fill in the code you got at LinkedIn.'));
      foundError = true;
    }
    
    if (foundError){
      return false;
    }
    
    sense.showSpinner = true;
    $.getJSON("/linked_in/json_check_code/" + encodeURIComponent(code),
      function(result){
        if (result.status == false){
          sense.closePopup();
          if (result.code == 'KNOWN_ACCOUNT'){
            sense.dialogCallback = function(){location.href = '/logout';};
          }
          sense.showDialog(result.message);
        }
        else {
          sense.showPopup('/linked_in/rss_key_form_popup');
        }
    });
  },
  
  checkLinkedInRss: function(){
    if (sense.showSpinner){
      return false;
    }
    
    var foundError = false;
    // clear old error messages
    $('span.error').remove();
    $('p.error').removeClass('error');
    
    var rssUrl = $.trim(senseFormLib.getInputValue('rss_url'));
    if (rssUrl == ''){
      senseFormLib.setInputError('rss_url', _('Please fill in the rss link you got at LinkedIn.'));
      foundError = true;
    }
    if (rssUrl.indexOf('http://www.linkedin.com/rss/') == -1){
      senseFormLib.setInputError('rss_url', _('This does not look like a valid rss link from LinkedIn. It should start with \'http://www.linkedin.com/rss/\''));
      foundError = true;
    }
    if (foundError){
      return false;
    }
    
    sense.showSpinner = true;
    $.post('/linked_in/json_check_rss/', $('#linkedin_rss_form').serialize(),
      function(result){
        if (result.status == false){
          sense.closePopup();
          sense.showDialog(_('Something went wrong while we tried to read your RSS. We have stored the link and will try later.'));
        }
        else {
          location.href = '/';
        }
    }, 'json');
  },
  
  
  addLabel: function(){
    labelValue = $('#new_label_input').val();
    
    if (labelValue == ''){
      sense.showDialog(_('Please give the label a name.'));
      return false;
    }
    
    if (labelValue.length > 20){
      sense.showDialog(_('Please give the label a name with a maximum of 20 characters.'));
      return false;
    }
    
    // check for double values
    $('.edit_labels ul li input').each(function(){
      if ($(this).val() == $('#new_label_input').val()){
        sense.showDialog(_('There is already a label with this name.'));
        return false;
      }
    });
    $('.edit_labels ul').append('<li><span class="btn delete">Delete</span><input type="text" name="new_label[]" value="'+labelValue+'" /></li>');
    
    $('#new_label_input').val('');
  },
  
  
  addUberlabel: function(){
    
    labelValue = $('#new_uberlabel_input').val();
    
    if (labelValue == ''){
      sense.showDialog(_('Please give the &uuml;berlabel a name.'));
      return false;
    }
    
    if (labelValue.length > 20){
      sense.showDialog(_('Please give the &uuml;berlabel a name with a maximum of 20 characters.'));
      return false;
    }
    
    // check for double values
    $('.edit_uberlabels div.left .uberlabelname').each(function(){
      if ($(this).val() == $('#new_uberlabel_input').val()){
        sense.showDialog(_('There is already an &uuml;berlabel with this name.'));
        return false;
      }
    });
    
    $('.edit_uberlabels ul.editable_labels').append('<li><span class="btn delete" onclick="$(this).parent().fadeOut().remove();">Delete</span><span class="uberlabel_name" onclick="senseForm.activateUberlabelTab(\'' + senseForm.newUberlabels + '\'); return false;">' + labelValue + '</span><input type="hidden" name="new_uberlabel[]" id="new_uberlabel[]" value="'+ senseForm.newUberlabels +'" /></li>');
    var newDiv = $('#inputs_prototype').clone();
    newDiv.attr('id', 'inputs_' + senseForm.newUberlabels);
    newDiv.children(':text').attr('id', 'new_uberlabel_name[' + senseForm.newUberlabels + ']');
    newDiv.children(':text').attr('name', 'new_uberlabel_name[' + senseForm.newUberlabels + ']');
    newDiv.children(':text').val(labelValue);
    newDiv.find('li :checkbox').each(function (){
      var name = 'new_uberlabel_label['+ senseForm.newUberlabels + '][' + $(this).attr('rel') + ']';
      $(this).attr('id', name);
      $(this).attr('name', name);
      $(this).next().attr('for', name);
    });
    
    newDiv.appendTo('.right.column');
    $('.uberlabel_inputs').hide();
    newDiv.show();
    newDiv.children(':text').focus();
    
    $('#new_uberlabel_input').val('');
    
    senseForm.newUberlabels += 1;
  },

  
  
  checkLabelForm: function(){
    if (sense.showSpinner){
      return false;
    }
    
    sense.showSpinner = true;
    $.post('/label/json_update_labels/', $('#edit_labels_form').serialize(),
      function(result){
        if (result.status == false){
          sense.showDialog(_('Something went wrong while we tried to store your labels, please try again later.'));
        }
        else {
          sense.closePopup();
        }
    }, 'json');
  },  
  
  checkUberlabelForm: function(){
    if (sense.showSpinner){
      return false;
    }
    
    sense.showSpinner = true;
    $.post('/label/json_update_Uberlabels/', $('#edit_uberlabels_form').serialize(),
      function(result){
        if (result.status == false){
          sense.showDialog(_('Something went wrong while we tried to store your uberlabels, please try again later.'));
        }
        else {
          sense.closePopup();
        }
    }, 'json');
  },
  
  checkPersonLabelForm: function(){
    if (sense.showSpinner){
      return false;
    }
    
    sense.showSpinner = true;
    $.post('/label/json_update_person_labels/', $('#edit_person_labels_form').serialize(),
      function(result){
        if (result.status == false){
          sense.showDialog(_('Something went wrong while we tried to store your labels, please try again later.'));
        }
        else {
          sense.closePopup();
          location.reload();
        }
    }, 'json');
  },
  
  
  activateUberlabelTab: function(stringUuid){
    $('.uberlabel_inputs').hide();
    $('#inputs_' + stringUuid).show();
  },
  
  
  addSavedSearch: function(query){
    if (sense.showSpinner){
      return false;
    }
    
    if ($.trim(query) == ''){
      sense.showDialog(_('You cannot store an empty search.'));
      return false;
    }
    
    sense.showSpinner = true;
    var searchGrade = 1;
    if ($('#second').is(':checked')){
      searchGrade = 2;
    }
    
      $.post('/search/json_add_saved_search/', {query_string: query, grade: searchGrade},
      function(result){
        if (result.status == false){
          sense.showDialog(_('Something went wrong while we tried to save your search, please try again later.'));
        }
        else {
          sense.showPopup('/search/edit_form/?from_add=1');
        }
    }, 'json');
  },
  
  queueDeleteSearch: function (element, stringUuid){
    $(element).parent().fadeOut().remove();
    $('#delete_searches').val($('#delete_searches').val() + ',' + stringUuid);
  },
  
  
  checkSearchesForm: function(){
    if (sense.showSpinner){
      return false;
    }
    
    sense.showSpinner = true;
    $.post('/search/json_update_searches/', $('#edit_searches_form').serialize(),
      function(result){
        if (result.status == false){
          sense.showDialog(_('Something went wrong while we tried to store your searches, please try again later.'));
        }
        else {
          location.reload();
        }
    }, 'json');
  },  

} // end class senseForm

senseFormLib = {
  getInputValue: function(formElementId){
    escapedFormElementId = senseFormLib.escapeBrackets(formElementId);
    var value = $('#' + escapedFormElementId).val();
    if(typeof(inputDefaults) == 'undefined'){
      return value;
    }
    
    var elementBaseId = senseFormLib.getBaseId(formElementId);
    if (inputDefaults[elementBaseId]){
      if ($('#' + escapedFormElementId).val() == inputDefaults[elementBaseId]){
        value = '';
      }
    }
    
    return value;
  },  
  
  removeDefaultValues: function(formElementId){
    if(!inputDefaults){
      return false;
    }
    
    $('#'+ formElementId + ' input[type=text], #'+ formElementId + ' textarea').each(function (key, e){
      var elementId = $(e).attr('id');
      var elementBaseId = senseFormLib.getBaseId(elementId);
      elementId = senseFormLib.escapeBrackets(elementId);
      if (inputDefaults[elementBaseId]){
        if ($('#' + elementId).val() == inputDefaults[elementBaseId]){
          $('#' + elementId).val('');
        }
      }
    
    
    });
    
    $.each(inputDefaults, function (key, val){
      key = senseFormLib.escapeBrackets(key);
      if ($('#' + key).val() == val){
        $('#' + key).val('');
      }
    });
  },
  
  
  escapeBrackets: function (text){
    return text.replace('[', '\\[').replace(']', '\\]');
  },
  
  
  // ids might contain brackets, get rid of them
  getBaseId: function (objId){
    var lastBeforeBracket = objId.indexOf('[');
    if (lastBeforeBracket != -1){
      objId = objId.substr(0, lastBeforeBracket);
    }
    return objId;
  },
  
  
  setInputError: function(elementId, message){
    var input = $('#' + elementId);
    input.closest('p').addClass('error');
    input.after('<span class="error">' + message + '</span>');
  }
} // end class