use strict;

sub PreCreateForm ()
{
   my $cLastBtn   = &GetAttr("LastBtn");

   &SetField("lang", &GetAttr("Lang"));
   &SetField("base_lang", &GetAttr("BaseLang"));

   # in QRY-mode leave everything untouched
   unless ($cLastBtn eq "BtnQry")
   {

      # read the text from the db
      if (&GetField("id_text"))
      {
         my $cTransTextBaseLang;
         my $cLastChangeBaseLang;

         my $plResult = $oDbSessionGL->SqlSelect
             ("SELECT
                   trans_text,
                   last_change
               FROM
                   wwwdb_translation
               WHERE
                   id_text  = ? AND
                   lang     = ?",
              &GetField("id_text"),
              &GetAttr("BaseLang"))->[0];

         ($cTransTextBaseLang,
          $cLastChangeBaseLang) = @$plResult;

         &SetField("trans_text_base_lang", $cTransTextBaseLang);
         &SetField("last_change_base_lang", $cLastChangeBaseLang);

         &SetField("trans_text", "")
             if (((&GetAttr("Lang") ne &GetAttr("BaseLang")) &&
                  (&GetField("trans_text") eq
                   &SetField("trans_text_base_lang"))) ||
                 (!&GetField("last_change")));

      }
      else
      {
         &SetField("trans_text_base_lang", "");
         &FetchNextTransText();
      }
   }
}


sub FetchNextTransText ()
{
   my $cNextIdTransText = $oDbSessionGL->SqlSelect
       ("SELECT
            MIN(tt1.id_text)
         FROM
            wwwdb_translation tt1,
            wwwdb_translation tt2
         WHERE
            tt1.lang    = ?           AND
            tt2.lang    = ?           AND
            tt1.id_text = tt2.id_text AND
            tt1.id_text > 0           AND
            (tt2.last_change IS NULL OR
             tt2.last_change < tt1.last_change)",
        &GetAttr("BaseLang"),
        &GetAttr("Lang"))->[0]->[0];

   if(defined $cNextIdTransText)
   {
      print &Redirect(&GetAttr("SessionId"),
                      (&GetAttr("ConfigFile") .
                       ";id=" .
                       $cNextIdTransText .
                       "," .
                       (&GetAttr("Lang"))));
      &MyExit();
   }
   else
   {
      &SetField("trans_text_base_lang",
                i18n("<No text to translate>"));
   }
}

sub PreBtnUpd()
{
   # Set time-stamp
   &SetField("last_change_base_lang",
             $oDbSessionGL->DateToDb(scalar(localtime())))
       unless(&GetField("last_change_base_lang"));

   &SetField("last_change",
             &GetField("last_change_base_lang"));
}


1;


