<?php

/*
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You can get a copy of this license at http://www.gnu.org/licenses/gpl.txt.
*/



function get_pref_language_array($str_http_languages)
{
  $langs = explode(',',$str_http_languages);
  $qcandidat = 0;
  $nblang = count($langs);

  for ($i=0; $i<$nblang; $i++)
  {
    for ($j=0; $j<count($langs); $j++) {
      $lang = trim($langs[$j]); // Suprime les espaces avant et après $lang
      // Lang est de la forme langue;q=valeur

      if (!strstr($lang, ';') && $qcandidat != 1) {
        // Si la chaine ne contient pas de valeur de préférence q
        $candidat = $lang;
        $qcandidat = 1;
        $indicecandidat = $j;
      }
      else {
        // On récupère l'indice q
        $q = ereg_replace('.*;q=(.*)', '\\1', $lang);

        if ($q > $qcandidat) {
          $candidat = ereg_replace('(.*);.*', '\\1', $lang); ;
          $qcandidat = $q;
          $indicecandidat = $j;
        }
      }
    }

    $resultat[$i] = $candidat;

    $qcandidat=0;
    // On supprime la valeur du tableau
    unset($langs[$indicecandidat]);
    $langs = array_values($langs);
  }
  return $resultat;
}

if ($_COOKIE['prefslanguageselection'])
  $language = $_COOKIE['prefslanguageselection'];
else if (isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])) {
  $preflang = get_pref_language_array($_SERVER["HTTP_ACCEPT_LANGUAGE"]);
  $availablelang = array('fr', 'en', 'es', 'nl');
  $result = array_intersect($preflang, $availablelang);
  if (count($result) != 0)
    $language = $result[0];
  else
    $language = 'en';

}
else
  $language = 'en';


$lang_association = array('fr' => 'fr_FR', 'en' => 'en_EN', 'en-gb' => 'en_EN', 'en-us' => 'en_EN', 'nl' => 'nl_NL', 'es' => 'es_ES');
$language = $lang_association[$language];

putenv("LANG=$language");
setlocale(LC_ALL, $language);

$domain = 'messages';

bindtextdomain("$domain", "/space_3/mandragor/www/docs/lang/locale");
textdomain("$domain");

?>