// Checks whether the current page must be reloaded.
// Also installs this function call for the window.onFocus event.
function checkTimestamp(timestamp) {
  if (getCookie('timestamp', 0) > timestamp) {
    this.status = 'Mise à jour de la page...';
    location.replace(location.href);
  }
  else if (this.onfocus == null)
    this.onfocus = new Function('checkTimestamp(' + timestamp + ')');
}

// Finalizes a page load (window.onLoad).
// Displays a message if one is pending.
// Sets the focus on a field, either a requested one or the first one if none is requested.
// Sets image.title to image.alt for all images (some browsers don't display alt messages,
// but title ones only).
function finalizePageLoad() {
  resetForms();
  if (document.forms[0] != null)
    for (var i = 0; i < document.forms[0].elements.length; i++)
      if (document.forms[0].elements[i].onchange != null)
	document.forms[0].elements[i].onchange();

  displayMessage();

  if (!setFieldFocus() && document.forms[0] != null)
    for (var i = 0; i < document.forms[0].elements.length; i++)
      if (document.forms[0].elements[i].type != 'hidden'
	  && document.forms[0].elements[i].tabIndex >= 0) {
	document.forms[0].elements[i].focus();
	if (document.forms[0].elements[i].select != null)
	  document.forms[0].elements[i].select();
	break;
      }

  for (var i = 0; i < document.images.length; i++)
    document.images[i].title = document.images[i].alt;

  // Install Opera work around.
  if (navigator.userAgent.indexOf('Opera') >= 0)
    setInterval('operaWorkAround()', 500);

  // Firefox since version 1.5 does not call any more the onLoad event when a page is
  // re-loaded from the cache (following a back command).
  this.onpageshow = operaWorkAround;
}

// Work around for Opera.
// Opera does not call any page scripts (as well as events, such as onLoad) when a page
// is displayed following a "back" command. So we get round by using a timer.
function operaWorkAround() {
  if (this.onfocus != null)
    this.onfocus(); // Check timestamp.
  displayMessage();
  setFieldFocus();
}

// Displays a message if one is pending (cookie "message").
function displayMessage() {
  var message = getCookie('message');
  if (message != null) {
    clearCookie('message');
    message += '.';
    if (message.charAt(0) != ' ') {
      alert(message);
      this.status = message;
    }
    else
      this.status = message.substr(1);
  }
}

// Resets the forms if requested.
function resetForms() {
  if (getCookie('dontResetForms') != null)
    clearCookie('dontResetForms');
  else
    for (var i = 0; i < document.forms.length; i++) {
      document.forms[i].reset();
      if (document.forms[i].onreset != null)
	document.forms[i].onreset();
    }
}

// Sets the focus to a field if requested.
// Returns true if a field has received the focus, false if not.
function setFieldFocus() {
  var field = getCookie('focus');
  if (field != null) {
    clearCookie('focus');
    for (var i = 0; i < document.forms.length; i++)
      for (var j = 0; j < document.forms[i].elements.length; j++)
	if (document.forms[i].elements[j].name == field) {
	  document.forms[i].elements[j].focus();
	  if (document.forms[i].elements[j].select != null)
	    document.forms[i].elements[j].select();
	  return true;
	}
  }
  return false;
}

// Gets a cookie value.
// If the cookie is not set, defaultValue is returned.
function getCookie(name, defaultValue) {
  var cookie = document.cookie;
  var start = cookie.indexOf('; ' + name + '=') + 2;
  if (start < 2) {
    if (cookie.indexOf(name + '=') != 0)
      return defaultValue;
    start = 0;
  }
  var end = cookie.indexOf(';', start);
  if (end < 0)
    end = cookie.length;
  return unescape(cookie.substring(start + name.length + 1, end));
}

// Sets a cookie.
// expiry and path are optional.
function setCookie(name, value, expiry, path) {
  document.cookie = name + '=' + escape(value)
    + (expiry != null ? '; expires=' + expiry.toGMTString() : '')
    + (path != null ? '; path=' + path : '');
}

// Deletes a cookie.
// path is optional.
function clearCookie(name, path) {
  document.cookie = name + '=; expires=Sat, 01 Jan 2000 00:00:00 GMT'
    + (path != null ? '; path=' + path : '');
}

// Returns true if cookies are enabled, false if not.
function areCookiesEnabled() {
  var date = new Date();
  setCookie('test', date.getTime());
  var test = getCookie('test') == date.getTime();
  clearCookie('test');
  return test;
}

// Validates a form.
// If a field named "_defaults_" exists (should be hidden), all default values are stored into it.
function validateForm(form) {
  if (form._defaults_ != null) {
    var defaults = [];
    for (var i = 0; form.elements[i] != null; i++) {
      var value = '';
      switch (form.elements[i].type) {
      case 'text':
      case 'textarea':
      case 'password':
      case 'hidden':
	value = form.elements[i].defaultValue;
	break;
      case 'checkbox':
      case 'radio':
	if (form.elements[i].defaultChecked)
	  value = form.elements[i].value;
	break;
      case 'select-one':
	var options = form.elements[i].options;
	if (options.length > 0) {
	  for (var j = 0; j < options.length; j++)
	    if (options[j].defaultSelected)
	      break;
	  if (j >= options.length)
	    j = 0;
	  value = options[j].value == '' ? options[j].text : options[j].value;
	}
	break;
      }
      if (value != '')
	defaults[defaults.length] = form.elements[i].name + '=' + value.replace(/&/g, '%26');
    }
    form._defaults_.value = defaults.join('&');
  }
  return true;
}

// Submits a form.
function submitForm(name) {
  var form = document.forms[name];
  if (form.onsubmit != null && form.onsubmit())
    form.submit();
}

// Resets a form.
function resetForm(name) {
  document.forms[name].reset();
  this.status = '';
}

// Opens a mail window.
function openMail(mailbox, server) {
  location.href = 'mailto:' + mailbox + '@' + server;
}

// Opens a URL contained in a field.
function openLink(field) {
  var url = field.value.replace(/^\s+|\s+$/g, '');
  if (url == '') {
    field.focus();
    alert('Ne doit pas être vide');
    return;
  }
  if (url.indexOf('http://') == 0)
    url = url.substr(7);
  else if (url.indexOf('//') == 0)
    url = url.substr(2);
  open('http://' + url);
}

// Prints the survey link if the user is connected.
function printSurvey() {
  if (getCookie('connected') && location.pathname != '/survey.php')
    document.write('<a href="survey.php" target="zerenard-survey">Sondage</a><br><br>');
/*      '<table border="0" cellpadding="0" cellspacing="0" width="100%">',
       '<tr>',
	'<td><a href="survey.php" target="zerenard-survey">Sondage</a></td>',
	'<td align="right" width="50%"><marquee scrollamount="2">',
	 '<font color="#FF0000"><b>Nouveau</b></font>',
	'</marquee></td>',
       '</tr>',
      '</table><br>);*/
}

// Flags (cookie)
var FLAG_FULL_HISTORY = 1;

// Toggles a flag.
function toggleFlag(flag, dontReloadPage) {
  setCookie('flags', getCookie('flags', 0) ^ flag);
  if (!dontReloadPage)
    location.replace(location.href);
}
