/*********** Sign up functions ***********/

/**
 * Initializes sign-up page.
 *
 * @param element The element the focus is placed on initially.
 */
function signUpInit(element) {
  document.getElementById(element).focus();
}

/**
 * Signs up the new user. This occurs right after
 * the email address was entered.
 *
 * @return Will always return false. The form does not need to be submitted.
 */
function signUp() {
  // Check email validity.
  var email = document.getElementById("loginemail").value;
  if(email.length == 0) {
    alert("Du musst eine gültige Email-Adresse angeben.");
    return false;
  }
  if(email.match(/^[a-zA-Z0-9\.\-+_]+@[äöüÄÖÜßa-zA-Z0-9\.\-_]+$/) == null) {
    alert("Diese Email-Adresse ist nicht gültig.");
    return false;
  }

  // Sign the user in.
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open("GET","signin.php?email="+encodeURIComponent(email),true);
  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4) {
      document.getElementById("signinform").innerHTML = xmlHttp.responseText;
    }
  }
  xmlHttp.send(null);
  var submitButton = document.getElementById("signin");
  submitButton.value = "Überprüfe Email-Adresse...";
  submitButton.disabled = true;

  return false;
}

/**
 * Initialization function for the profile activation page.
 *
 * @param otherCountry If true, "other country" is visible initially, if false,
 *                     postal code is visible initially.
 * @param focus The element which initially receives focus.
 */
function activateInit(otherCountry,focus) {
  if(otherCountry) {
    document.getElementById("liplz").style.display = "none";
    document.getElementById("liplzmsg").style.display = "none";
    document.getElementById("licountry").style.display = "block";
    document.getElementById("licountrymsg").style.display = "block";
  } else {
    document.getElementById("liplz").style.display = "block";
    document.getElementById("liplzmsg").style.display = "block";
    document.getElementById("licountry").style.display = "none";
    document.getElementById("licountrymsg").style.display = "none";
  }
  document.getElementById(focus).focus();
}

/**
 * Switches the possible user selection between
 * Germany and other countries.
 *
 * @param otherCountry If true, switch to "other country", if false, switch to "Germany".
 */
function switchNational(otherCountry) {
  if(otherCountry) {
    document.getElementById("liplz").style.display = "none";
    document.getElementById("liplzmsg").style.display = "none";
    document.getElementById("licountry").style.display = "block";
    document.getElementById("licountrymsg").style.display = "block";
    document.getElementById("country").focus();
    document.getElementById("foreign").value="1";
  } else {
    document.getElementById("liplz").style.display = "block";
    document.getElementById("liplzmsg").style.display = "block";
    document.getElementById("licountry").style.display = "none";
    document.getElementById("licountrymsg").style.display = "none";
    document.getElementById("plz").focus();
    document.getElementById("foreign").value="0";
    document.getElementById("country").value="DE";
  }
}

/**
 * Checks the user's input into the activation
 * form.
 *
 * @return true if the input is correct, false if not.
 */
function checkActivation() {
  // Use name.
  if(document.getElementById("user_name").value.length==0) {
    alert("Bitte einen Benutzernamen angeben.");
    document.getElementById("user_name").focus();
    return false;
  }

  // Gender.
  if(document.getElementById("gender").value=="") {
    alert("Bitte ein Geschlecht auswählen.");
    document.getElementById("gender").focus();
    return false;
  }

  // Postal code.
  if((document.getElementById("foreign").value=="0" || document.getElementById("country").value=="DE")
    && (document.getElementById("plz").value.length!=5 || document.getElementById("plz").value.match(/^[0-9]+$/)==null)) {
    alert("Bitte eine vollständige, gültige Postleitzahl angeben.");
    switchNational(false);
    return false;
  }

  // Password length.
  if(document.getElementById("actpassword").value.length<6) {
    alert("Dein Passwort muss mindestens 6 Zeichen lang sein.");
    document.getElementById("actpassword").focus();
    return false;
  }

  // Password characters.
  if(document.getElementById("actpassword").value.match(/^[a-zA-Z0-9]+$/)==null) {
    alert("Dein Passwort darf nur Buchstaben und Zahlen enthalten. (Keine Umlaute.)");
    document.getElementById("actpassword").focus();
    return false;
  }

  // Repeat match.
  if(document.getElementById("actpassword").value!=document.getElementById("repeat").value) {
    alert("Passwort und Wiederholung des Passworts stimmen nicht überein.");
    document.getElementById("actpassword").focus();
    return false;
  }

  return true;
}

/**
 * Checks the user's input into the log-in
 * form.
 *
 * @return true if the input is correct, false if not.
 */
function checkLogIn() {
  // Check email validity.
  var email = document.getElementById("email").value;
  if(email.length == 0) {
    alert("Du musst eine gültige Email-Adresse angeben.");
    document.getElementById("email").focus();
    return false;
  }
  if(email.match(/^[a-zA-Z0-9\.\-+_]+@[äöüÄÖÜßa-zA-Z0-9\.\-_]+$/) == null) {
    alert("Diese Email-Adresse ist nicht gültig.");
    document.getElementById("email").focus();
    return false;
  }

  // Password length.
  if(document.getElementById("password").value.length<6) {
    alert("Dein Passwort muss mindestens 6 Zeichen lang sein.");
    document.getElementById("password").focus();
    return false;
  }

  // Password characters.
  if(document.getElementById("password").value.match(/^[a-zA-Z0-9]+$/)==null) {
    alert("Dein Passwort darf nur Buchstaben und Zahlen enthalten. (Keine Umlaute.)");
    document.getElementById("password").focus();
    return false;
  }

  return true;
}

/**
 * Initialize the details page.
 *
 * @param focus The element initial focus is placed on.
 */
function initDetails(focus) {
  document.getElementById(focus).focus();
  parseArtists();
}

/**
 * Parses the user's entry into the artist box and provides some
 * feedback below it.
 */
function parseArtists() {
  var artists = document.getElementById("artists").value;
  var message,artistcount;
  // Allow commas.
  artists = artists.replace(/,/g,"\n");
  lines = artists.match(/[^\n\r]+/g);
  if(lines==null) {
    // Nothing entered.
    message = "Du hast noch keine Bands eingegeben.";
  } else {
    // Count valid bands.
    artistcount = 0;
    var index;
    for(index=0;index<lines.length;index++) {
       if(boilToShortName(lines[index]).length>0)
         artistcount++;
       if(lines[index].length>40) {
         message = "Mindestens ein Bandname is zu lang. Bitte die Bandnamen per Komma trennen.";
         artistcount = -1;
         break;
       }
    }
    if(artistcount==0)
      message = "Du hast noch keinen gültigen Bandnamen eingegeben.";
    else if(artistcount==1)
      message = "Du hast bisher nur eine Band eingegeben.";
    else if(artistcount>1)
      message = "Bisher " + artistcount + " Bands eingegeben";
  }
  document.getElementById("artistcount").innerHTML = message;
  setTimeout("parseArtists()",1000);
}

/**
 * Makes a short artist name out of the full name.
 *
 * @param name The full name of the artist.
 * @return The short artist name consisting only of alphanumeric characters or
 *         an empty string if the name does not contain any valid characters.
 */
function boilToShortName(name) {
  if(!name)
    return "";
  var segments = name.match(/[a-zA-Z0-9]+/g);
  if(segments==null)
    return "";
  var shortName = "";
  var index;
  for(index=0;index<segments.length;index++)
    shortName += segments[index];
  return shortName.toLowerCase();
}

/**
 * Deletes a picture.
 *
 * @param code The picture code.
 */
function deletePicture(code) {
  if(!confirm("Willst Du dieses Bild wirklich löschen?"))
    return;
  location.href = "bilder.php?delete&picture_code="+code;
}

/**
 * Sets the default profile picture.
 *
 * @param code The picture code.
 */
function setDefaultPicture(code) {
  location.href = "bilder.php?default&picture_code="+code;
}

/**
 * Applies this picture for a band/fan photo.
 *
 * @param code The picture code.
 */
function setGroupPhoto(code) {
  if(!confirm("Ist dies ein Bild von Dir zusammen mit RIVO DREI?"))
    return;
  location.href = "bilder.php?groupphoto&picture_code="+code;
}

/**
 * Removes this group photo from the pictures page.
 *
 * @param code The picture code.
 */
function deleteGroupPhoto(code) {
  if(!confirm("Bist Du sicher, dass dieses Bild nicht mehr auf der Bilder-Seite erscheinen soll?"))
    return;
  location.href = "bilder.php?nogroupphoto&picture_code="+code;
}

/**
 * Applies this picture for the casting.
 *
 * @param code The picture code.
 */
function setCasting(code) {
  if(!confirm("Willst Du mit diesem Bild am Casting teilnehmen?"))
    return;
  location.href = "bilder.php?casting&picture_code="+code;
}

/**
 * Removes this group photo from the casting.
 *
 * @param code The picture code.
 */
function deleteCasting(code) {
  location.href = "bilder.php?nocasting&picture_code="+code;
}

/**
 * Changes the description of the picture.
 *
 * @param code The picture code.
 */
function changeDescription(code) {
  var element = document.getElementById("desc"+code);
  var text = element.innerHTML;
  text = text.substr(0,text.indexOf("<"));
  text = text.replace('"','&quot;');
  element.innerHTML = '<input id="newdesc'+code+'" value="'+text+'" size="14" maxlength="120"/>'
                      +'<br/><input type="button" id="savedesc'+code+'" value="Text speichern" onclick="saveDescription('+"'"+code+"'"+')"/>';
  document.getElementById("newdesc"+code).focus();
}

/**
 * Saves the newly entered picture description
 * to the database via server request.
 *
 * @param code The picture code.
 */
function saveDescription(code) {
  // Compose URL.
  var url = "savedescription.php?picture_code="+code+"&description=";
  url += encodeURIComponent(document.getElementById("newdesc"+code).value);

  // Perform server request.
  document.getElementById("savedesc"+code).disabled = true;
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open("GET",url,true);
  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4) {
      if(xmlHttp.responseText.charAt(0)==">") {
        alert(xmlHttp.responseText.substr(1,xmlHttp.responseText.length-1));
        document.getElementById("savedesc"+code).disabled = false;
      } else
        document.getElementById("desc"+code).innerHTML = xmlHttp.responseText;
    }
  }
  xmlHttp.send(null);
}

/**
 * Initialization function for the basic setup page.
 *
 * @param otherCountry If true, "other country" is visible initially, if false,
 *                     postal code is visible initially.
 * @param focus The element which initially receives focus.
 */
function basicsInit(otherCountry,focus) {
  if(otherCountry) {
    document.getElementById("liplz").style.display = "none";
    document.getElementById("liplzmsg").style.display = "none";
    document.getElementById("licountry").style.display = "block";
    document.getElementById("licountrymsg").style.display = "block";
  } else {
    document.getElementById("liplz").style.display = "block";
    document.getElementById("liplzmsg").style.display = "block";
    document.getElementById("licountry").style.display = "none";
    document.getElementById("licountrymsg").style.display = "none";
  }
  document.getElementById(focus).focus();
}

/**
 * Checks the user's input into the basic data
 * form.
 *
 * @return true if the input is correct, false if not.
 */
function checkBasics() {
  // Use name.
  if(document.getElementById("user_name").value.length==0) {
    alert("Bitte einen Benutzernamen angeben.");
    document.getElementById("user_name").focus();
    return false;
  }

  // Gender.
  if(document.getElementById("gender").value=="") {
    alert("Bitte ein Geschlecht auswählen.");
    document.getElementById("gender").focus();
    return false;
  }

  // Postal code.
  if((document.getElementById("foreign").value=="0" || document.getElementById("country").value=="DE")
    && (document.getElementById("plz").value.length!=5 || document.getElementById("plz").value.match(/^[0-9]+$/)==null)) {
    alert("Bitte eine vollständige, gültige Postleitzahl angeben.");
    switchNational(false);
    return false;
  }

  if(document.getElementById("password").value.length>0) {
    // Old password length.
    if(document.getElementById("oldpassword").value.length<6) {
      alert("Dein altes Passwort muss mindestens 6 Zeichen lang sein.");
      document.getElementById("oldpassword").focus();
      return false;
    }

    // Old password characters.
    if(document.getElementById("oldpassword").value.match(/^[a-zA-Z0-9]+$/)==null) {
      alert("Dein altes Passwort darf nur Buchstaben und Zahlen enthalten. (Keine Umlaute.)");
      document.getElementById("oldpassword").focus();
      return false;
    }

    // Password length.
    if(document.getElementById("password").value.length<6) {
      alert("Dein neues Passwort muss mindestens 6 Zeichen lang sein.");
      document.getElementById("password").focus();
      return false;
    }

    // Password characters.
    if(document.getElementById("password").value.match(/^[a-zA-Z0-9]+$/)==null) {
      alert("Dein neues Passwort darf nur Buchstaben und Zahlen enthalten. (Keine Umlaute.)");
      document.getElementById("password").focus();
      return false;
    }

    // Repeat match.
    if(document.getElementById("password").value!=document.getElementById("repeat").value) {
      alert("Passwort und Wiederholung des Passworts stimmen nicht überein.");
      document.getElementById("password").focus();
      return false;
    }
  }

  return true;
}

/**
 * Checks the picture upload form.
 *
 * @return true.
 */
function checkPictureUploadForm() {
  // Avoid double uploads.
  setTimeout('document.getElementById("submit").value="Bild wird hochgeladen, Geduld...";document.getElementById("submit").disabled = true;',100);

  return true;
}

/**
 * Checks the new discussion form.
 *
 * @return Whether (true) or not (false) the entries were correct.
 */
function checkNewDiscussion() {
  if(document.getElementById("title").value=="") {
    alert("Bitte eine Überschrift eingeben.");
    document.getElementById("title").focus();
    return false;
  }

  if(document.getElementById("discussion").value=="") {
    alert("Bitte einen Beitragstext eingeben.");
    document.getElementById("discussion").focus();
    return false;
  }

  setTimeout('document.getElementById("submit").disabled=true;document.getElementById("submit").value="Senden...";',50);

  return true;
}

/**
 * Adds an attended concert to the user.
 *
 * @param concertKey The concert to be added.
 */
function addConcert(concertKey) {
  setTimeout("document.getElementById('addbutton"+concertKey+"').disabled = true",50);
  location.href = "konzerte.php?action=add&key=" + concertKey;
}

/**
 * Deletes a concert from the user's attendance list.
 *
 * @param concertKey The concert to be deleted.
 */
function deleteConcert(concertKey) {
  setTimeout("document.getElementById('deletebutton"+concertKey+"').disabled = true",50);
  location.href = "konzerte.php?action=delete&key=" + concertKey;
}

/**
 * Shows all users which went to this concert.
 *
 * @param concertKey The selected concert.
 */
function atConcert(concertKey) {
  setTimeout("document.getElementById('othersbutton"+concertKey+"').disabled = true",50);
  location.href = "../konzerte/anwesenheit.php?key=" + concertKey;
}

/**
 * Redirects the user to the "become friends" page.
 * Used for buttons with ID "befriend<user_id>". Current
 * URL is the second level (e.g. "/profil/konzerte").
 *
 * @param userId The user which should be added to your friends list.
 */
function addToFriends(userId) {
  setTimeout("document.getElementById('befriend"+userId+"').disabled = true",50);
  location.href = "../freunde/anfreunden.php?id="+userId;
}

/**
 * Accepts the friendship request.
 *
 * @param userId The user which should be added to your friends list.
 */
function acceptFriendship(userId) {
  setTimeout("document.getElementById('accept"+userId+"').disabled = true",50);
  location.href = "?action=accept&id="+userId;
}

/**
 * Rejects the friendship request.
 *
 * @param userId The user which should not be added to your friends list.
 */
function rejectFriendship(userId) {
  setTimeout("document.getElementById('reject"+userId+"').disabled = true",50);
  location.href = "?action=reject&id="+userId;
}

/**
 * Loads the previous mail in the conversation.
 *
 * @param mailId The ID of the mail to be loaded.
 */
function loadPreviousMail(mailId) {
  // Sign the user in.
  var xmlHttp = new XMLHttpRequest();
  xmlHttp.open("GET","previous.php?id="+mailId,true);
  xmlHttp.onreadystatechange = function() {
    if(xmlHttp.readyState == 4) {
      document.getElementById("previousmail").innerHTML = xmlHttp.responseText;
    }
  }
  xmlHttp.send(null);
  document.getElementById("previousmail").innerHTML = "Wird geladen...";
}

/**
 * Checks the validity of the mail form.
 *
 * @return true if the mail form was filled in correctly, false if not.
 */
function checkMail() {
  if(document.getElementById("mailtext").value=="") {
    alert("Bitte einen Nachrichtentext eingeben.");
    document.getElementById("mailtext").focus();
    return false;
  }

  setTimeout("document.getElementById('submit').disabled = true;document.getElementById('submit').value = 'Wird geschickt...';",50);
  return true;
}