#!/usr/bin/perl
use CGI qw(:standard);
use CGI::Carp qw/fatalsToBrowser/;

$action = param('action');

  %credentials = cookie('splitreffile');
    $the_cookie = cookie(-name=>"splitreffile",
                     -path=>"/",
                     -value=>\%credentials,
                     -expires=>"+4h",
                     -secure=>"secure");

  open PASSWD, '/usr/local/apache/passwd.txt';
  @password = <PASSWD>;
  close PASSWD;

  $uname = $pword = '%%%%%%%%%%%%%';

  $authenticated="0";

  auth: until ($uname eq $credentials{'name'} && $pword eq $credentials{'pass'}) {
    $line;
    if(!($line = pop @password) || $credentials{'name'}.$credentials{'pass'} eq "") {
      $services = "";
      last 'auth';
    }
    $line =~ s/[\r\n]//g;
    ($uname, $pword, $services) = split ":", $line;
  }
  $credentials{'services'} = $services;
  my @list = split ";", $services;
  grep {
    my $key = my $value = $_;
    $key =~ s/=.*$//g;
    $value =~ s/^.*=//g;
    $credentials{$key} = $value;
  } @list;

  if($credentials{'file'}) { $authenticated = "yes"; }
#  if($credentials{'file'} =~ /(.*)/) { $credentials{'file'} = $1; }
  
  if($action ne "getimage") {
    if($authenticated eq "yes") {
      print header(-cookie=>$the_cookie);
    }
    else {
      print header();
    }
  }

  undef @password;
if($authenticated ne 'yes'){$action = "badauth";}
######################
#print "<br>\n";
#while((my $key, my $value) = each %ENV) {
#  print "$key = $value<br>\n";
#}
#print "action = $action<br><br>\n";

%page;


if($action eq "new") {
  $srcdir = param('srcdir');
  open SRC, "</usr/local/apache/gallery.xml";
  $source = join "", <SRC>;
  close SRC;
  $source =~ s/srcdir=''/srcdir='$srcdir'/;
  $action = "edit";
}
elsif($action eq "load") {
  $filename = param('filename');
  open SRC, "<$credentials{'file'}$filename";
  $source = join "", <SRC>;
  close SRC;
  $action = "edit";
}
elsif($action =~ /^edit/ || $action eq "view" || $action =~ /^save/) {
  $source = param('source');
}
if($action =~ /^edit/) {
  while ($source ne "") {
    $source = &docmd(\%page, $source);
  }
  $html = &gethtml(\%page);
  print
  $html;
#  print STDERR &getxml(\%page);
}
if($action eq "view") {
  while ($source ne "") {
    $source = &docmd(\%page, $source);
  }
  $html = &gethtml(\%page);
  print
  $html;
#  print STDERR &getxml(\%page);
}
if($action eq "save" || $action eq "savetop") {
  while ($source ne "") {
    $source = &docmd(\%page, $source);
  }
  $html = &gethtml(\%page);

  my $basedir;
  my $srcdir;
  $basedir = $credentials{'file'};
  $srcdir = $page{'options'}{'srcdir'};

  if($action eq "savetop"){
    open TMP, ">".$basedir.$srcdir."gallery.xml";
    print TMP &getxml(\%page) or die $!;
    close TMP;

    opendir DIR, $basedir.$srcdir."gallery";
    my @dirs = readdir DIR;
    @dirs = grep($_ =~ /^[^.]/, @dirs);
    print "<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"0; URL=".$srcdir."gallery/index.html\">";

    grep{
      unlink $basedir.$srcdir."gallery/".$_;
    } @dirs;

    close DIR;
    mkdir $basedir.$srcdir."gallery";
    open HTM, ">".$basedir.$srcdir."gallery/index.html";
  }
  else {
    open HTM, ">".$basedir.$srcdir."gallery/".param('filename');
  }

  my $previous = my $current = my $next = '';
  $previous = (rand time).".html";

  while($html =~ /href=.gallery.pl/gi || $html =~ /src=.gallery.pl/gi){
    my $text = $html;
    $text =~ s/>/ /g;
    my @lines = split " ", $text;
    save: while(my $line = pop @lines) {
      if($line =~ /href=['"]gallery.pl?[^'"]*(source=[^'"]+)['"]/){
        my $src = $1;
        $next = $current;
        $current = $previous;
        $html =~ s/gallery.pl[^'"]+$src/$current/g;
        if($html =~ /href=.gallery.pl/gi){$previous = (rand time).".html";}
        else {$previous = '';}

        $ENV{'QUERY_STRING'} = "action=save&previous=".$previous."&next=".$next."&filename=".$current."&".$src;
        $ENV{'REQUEST_METHOD'} = 'GET';
        open TMP, "/usr/local/apache/cgi-bin/gallery.pl |";
#        $html =~ s/gallery.pl[^'"]+$1/$current/g;
        close TMP;
        last 'save';
      }
      if($line =~ /src=['"]gallery.pl?[^'"]*(source=[^'"]+)['"]/){
        my $src = $1;
        my $current = (rand time);
        if($1 =~ /gif/){$current .= ".gif";}
        else {$current .= ".jpg"; }
        $ENV{'QUERY_STRING'} = "action=saveimage&filename=$current&srcdir=$srcdir&$src";
        $ENV{'REQUEST_METHOD'} = 'GET';
        open TMP, "/usr/local/apache/cgi-bin/gallery.pl |";

        $html =~ s/gallery.pl[^'"]+$src/$current/g;
        close TMP;
        last 'save';
      }
    }
  }
  print HTM $html;
  close HTM;

#  print
#  $html;
#  print STDERR &getxml(\%page);
}
if($action eq "saveimage") {
  my $basedir;
  my $srcdir;
  my $filename;
  $basedir = $credentials{'file'};
  $srcdir = param('srcdir');
  $filename = param('filename');
  if($filename =~ /(.*)/){ $filename = $1; }

  $source = param('source');
  while ($source ne "") {
    $source = &docmd(\%page, $source);
  }
  $html = &getimage(\%page);
  print "\n<br>>".$basedir.$srcdir."gallery/".$filename;
  open HTM, ">".$basedir.$srcdir."gallery/".$filename or die $!;
  print HTM $html or die $!;
  close HTM;
}

if($action eq "getimage") {
  $source = param('source');
  while ($source ne "") {
    $source = &docmd(\%page, $source);
  }
  my @tmp = stat($credentials{'file'}.$page{'options'}{'filename'});
  my $lastmod = $tmp[9];

  $ifnone = $ENV{'HTTP_IF_NONE_MATCH'};
  $ifnone =~ s/[" \r\n\t]*//g;
  if($lastmod eq $ifnone) {
    print "Status: 304 Not Modified\n".
    "Etag: \"$lastmod\"\n".
    "Cache-Control: public\n\n";
    exit;
  }

  $html = &getimage(\%page);
  my $type;
  if($page{'options'}{'filename'} =~ /\.([^.]+)$/) {
    $type = $1;
  }
  print
  "Etag: \"$lastmod\"\n".
  "Cache-Control: public\n".
  "Content-type: image/$type\n".
  "Cache-Control: no-cache\n\n".$html;
}

if($action eq "badauth") {
  print
  "<META HTTP-EQUIV=\"REFRESH\" CONTENT=\"0; URL=/new.html\">".
  "<body text=#ffffff bgcolor=#000080 link=#FFFF00 vlink=#C0C000 alink=#FFFF88>\n\n".
  "You must log in first.".
  "</body>";
}

exit;

sub getimage {
  my $size;
  my $crop;
    $size = $_[0]{'options'}{'size'};
    if($_[0]{'options'}{'cropstart'}) {
      $crop = $_[0]{'options'}{'cropstart'};
      $crop =~ s/x/+/;
      $crop = $_[0]{'options'}{'cropsize'}.
      "+".$crop;
    }

  if($_[0]{'options'}{'size'} =~ /<([0-9]+)x([0-9]+)/)
  {
    my $maxx = $1;
    my $maxy = $2;
    my $sizey, $sizex;

    open TMP, "/usr/local/bin/identify \"".
     $credentials{'file'}.$_[0]{'options'}{'filename'}."\" |";
    $sizex = join "", <TMP>;
    close TMP;
    if($sizex =~ / ([0-9]+)x([0-9]+) /)
    {
      $sizex = $1;
      $sizey = $2;
    }
    else
    {
      $sizex = 0;
      $sizey = 0;
    }
    if($sizex > $maxx) {
      $sizey = int(($maxx / $sizex) * $sizey);
      $sizex = $maxx;
    }
    if($sizey > $maxy) {
      $sizex = int(($maxy / $sizey) * $sizex);
      $sizey = $maxy;
    }
    $size = $sizex.'x'.$sizey;
  }

  $convstring = "/usr/local/bin/convert ";
  if($_[0]{'options'}{'filter'}) {
    $convstring = $convstring."-filter ".$_[0]{'options'}{'filter'}." ";
  }
  if($_[0]{'options'}{'quality'}) {
    $convstring = $convstring."-quality ".$_[0]{'options'}{'quality'}." ";
  }
  if($size) {
    $convstring = $convstring."-size ".$size." ";
  }
  if($size) {
    $convstring = $convstring."-resize ".$size."! ";
  }
  if($crop) {
    $convstring = $convstring."-crop ".$crop." ";
  }
  if($_[0]{'options'}{'flip'} eq 'yes') {
    $convstring = $convstring."-flip ";
  }
  if($_[0]{'options'}{'rotate'}) {
    $convstring = $convstring."-rotate ".$_[0]{'options'}{'rotate'}." ";
  }
  $convstring = $convstring."\"".
            $credentials{'file'}.$_[0]{'options'}{'filename'}."\" ";
  $convstring = $convstring."-page +0+0 - |";

  open IMG, $convstring;
  my $imgdata = join "", <IMG>;
  close IMG;

  return $imgdata;
}

sub gethtml {
  my $html;
  if($_[0]{'tag'} =~ /^page$/i) { $html = &page2html($_[0]); }
  elsif($_[0]{'tag'} =~ /^gallery$/i) { $html = &gallery2html($_[0]); }
  elsif($_[0]{'tag'} =~ /^image$/i) { $html = &image2html($_[0]); }
  elsif($_[0]{'tag'} =~ /^caption$/i) { $html = &caption2html($_[0]); }
  return $html;
}

sub caption2html {
  my $html;
  if($_[0]{'options'}{'placement'} eq "left" ||
    $_[0]{'options'}{'placement'} eq "right") {
    $html = $html."<td";

    captionoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
      if($key eq "placement" || $key eq "value") {
        next captionoptions;
      }
      $html = $html." $key='$value'";
    }
    $html = $html.">\n";
    if($action =~ /^edit/) {
      $html = $html.
      "<input type='hidden' name='tag' value='caption' />\n".
      "<input type='hidden' name='placement' value='".
      $_[0]{'options'}{'placement'}."' />\n".
      "<input type='hidden' name='value' value='".
      $_[0]{'options'}{'value'}."' />\n".
      "<input type='hidden' name='otherparams' value='";

    editcaptionoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
      if($key eq "placement" || $key eq "value") {
        next editcaptionoptions;
      }
      $html = $html." $key=\"$value\"";
    }

    $html = $html.
    "'>\n";
  }

    $html = $html.
    "  ".&href2text($_[0]{'options'}{'value'})."\n";

    if($action =~ /^edit/) {
      $html = $html.
      "<br><input type='button' value='Edit' onClick='edit(this);' />\n".
      "<input type='button' onClick='del(this);' value='Del'/>\n".
      "<input type='hidden' name='/tag' value='caption' />\n";
    }

    $html = $html.
    "</td>\n";

  }
  else {
    $html = $html."<p";

    captionoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
      if($key eq "placement" || $key eq "value") {
        next captionoptions;
      }
      $html = $html." $key='$value'";
    }
    $html = $html.">\n";

    if($action =~ /^edit/) {
      $html = $html.
      "<input type='hidden' name='tag' value='caption' />\n".
      "<input type='hidden' name='placement' value='".
      $_[0]{'options'}{'placement'}."' />\n".
      "<input type='hidden' name='value' value='".
      $_[0]{'options'}{'value'}."' />\n".
      "<input type='hidden' name='otherparams' value='";

    editcaptionoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
      if($key eq "placement" || $key eq "value") {
        next editcaptionoptions;
      }
      $html = $html." $key=\"$value\"";
    }

    $html = $html.
    "'>\n";
  }

    $html = $html.
    "  ".&href2text($_[0]{'options'}{'value'})."\n";

    if($action =~ /^edit/) {
      $html = $html.
      "<br><input type='button' value='Edit' onClick='edit(this);' />\n".
      "<input type='button' onClick='del(this);' value='Del'/>\n".
      "<input type='hidden' name='/tag' value='caption' />\n";
    }

    $html = $html.
    "</p>\n";
  }

  return $html;
}

sub image2html {
  my $html;

  $html = $html."<td";

  my $cols;
  foreach my $obj (@{$page{'children'}}) {
    if($$obj{'tag'} eq "gallery") {
      $cols = $$obj{'options'}{'cols'};
      last;
    }
  }

  imageoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
    if($key eq "filename" || $key eq "size" ||
       $key =~ /^crop/ || $key eq "quality" ||
       $key eq "filter" || $key eq "position" ||
       $key eq "flip" || $key eq "rotate") {
      next imageoptions;
    }
    $html = $html." $key='$value'";
  }
  $html = $html.">";

  if($action =~ /^edit/ && $_[0]{'options'}{'position'} >= $cols) {
    $html = $html."<a href='javascript:swap(".
        $_[0]{'options'}{'position'}.",".
       ($_[0]{'options'}{'position'} - $cols).");' title='Swap Images'>\n".
     "<img src='/img/web/v-arrow.gif' border=0 /></a>";
  }

  $html = $html."<table><tr>\n";

  if($action =~ /^edit/) {
    $html = $html.
    "<font size='2'>\n".
    "<input type='hidden' name='tag' value='image'>\n".
    "<input type='hidden' name='filename' value='".
    $_[0]{'options'}{'filename'}."'>\n".
    "<input size='2' type='hidden' name='position' value='".
    $_[0]{'options'}{'position'}.
    "'>\n<input type='hidden' name='size' value='".
    $_[0]{'options'}{'size'}.
    "'>\n<input type='hidden' name='cropstart' value='".
    $_[0]{'options'}{'cropstart'}.
    "'>\n<input type='hidden' name='cropsize' value='".
    $_[0]{'options'}{'cropsize'}.
    "'>\n<input type='hidden' name='filter' value='".
    $_[0]{'options'}{'filter'}.
    "'>\n<input type='hidden' name='quality' value='".
    $_[0]{'options'}{'quality'}.
    "'>\n<input type='hidden' name='flip' value='".
    $_[0]{'options'}{'flip'}.
    "'>\n<input type='hidden' name='rotate' value='".
    $_[0]{'options'}{'rotate'}.
    "'>\n".
    "<input type='hidden' name='otherparams' value='";

    editimageoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
      if($key eq "filename" || $key eq "position" ||
         $key =~ /^crop/ || $key eq "size" ||
         $key eq "quality" || $key eq "filter" ||
         $key eq "flip" || $key eq "rotate") {
        next editimageoptions;
      }
      $html = $html." $key=\"$value\"";
    }

    $html = $html.
    "'></font>\n";
  }

  foreach my $obj (@{$_[0]{'children'}}) {
    if($$obj{'tag'} eq "caption" && $$obj{'options'}{'placement'} eq "left") {
      $html = $html.&gethtml($obj);
      last;
    }
  }

  $html = $html."<td";

  imageoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
    if($key eq "filename" || $key eq "size" ||
       $key =~ /^crop/ || $key eq "quality" ||
       $key eq "filter" || $key eq "position" ||
       $key eq "flip" || $key eq "rotate") {
      next imageoptions;
    }
    $html = $html." $key='$value'";
  }
  $html = $html.">";

  my $caps = 15;
  my $link;
  foreach my $obj (@{$_[0]{'children'}}) {
    if($$obj{'tag'} eq "caption") {
      if($$obj{'options'}{'placement'} eq "top") {$caps = ($caps & 14);}
      if($$obj{'options'}{'placement'} eq "bottom") {$caps = ($caps & 13);}
      if($$obj{'options'}{'placement'} eq "left") {$caps = ($caps & 11);}
      if($$obj{'options'}{'placement'} eq "right") {$caps = ($caps & 7);}
    }
    if($$obj{'tag'} eq "caption" && $$obj{'options'}{'placement'} eq "top") {
      $html = $html.&gethtml($obj);
    }
    if($$obj{'tag'} eq "image") {
      $link = &getxml($obj);
      $fulllink = 
        "<page ";
        pageopt: while ((my $key, my $value) = each %{$page{'options'}}) {
          if($key eq "name" || $key eq "sync" ||
            $key eq "imgsize" || $key eq "quality" ||
            $key eq "filter" || $key =~ /^crop/) {
            next pageopt;
          }
          $fulllink = $fulllink." $key='$value'";
        }
        $fulllink = $fulllink.">".
        "<gallery cols='1' ".
        "bgcolor='".$page{'children'}[0]{'options'}{'bgcolor'}."'>\n".
        $link.
        "</gallery></page>";
      $fulllink =~ s/\/>/position=0 \/>/;
      if($action =~ /^edit/){$html = $html."<input type='hidden' name='plain' value='".&text2href($link)."' />";}
    }
  }

  my $size;
  my $sizex;
  my $sizey;
  if($_[0]{'options'}{'size'} =~ /(.+)/){ $size = $1; }
  else {
    open TMP, "/usr/local/bin/identify \"$credentials{'file'}$_[0]{'options'}{'filename'}\" |";
    $size = join "", <TMP>;
    close TMP;
    if($size =~ / ([0-9]+x[0-9]+) /){ $size = $1; }
  }
  if($size =~ /([0-9]*)x([0-9]*)/) { $sizex = $1; $sizey = $2; }
  (my $cropsx, my $cropsy) = split "x", $_[0]{'options'}{'cropstart'};
  (my $cropx, my $cropy) = split "x", $_[0]{'options'}{'cropsize'};
  if($cropx) {
    if($cropx + $cropsx < $sizex) {$sizex = $cropx; }
    else{$sizex = $sizex - $cropsx;}
    if($cropy + $cropsy < $sizey) {$sizey = $cropy; }
    else{$sizey = $sizey - $cropsy;}
  }

  my $imgsrc = "<image filename='".$_[0]{'options'}{'filename'}.
    "' size='".$_[0]{'options'}{'size'}.
    "' cropstart='".$_[0]{'options'}{'cropstart'}.
    "' cropsize='".$_[0]{'options'}{'cropsize'}.
    "' filter='".$_[0]{'options'}{'filter'}.
    "' quality='".$_[0]{'options'}{'quality'}.
    "' flip='".$_[0]{'options'}{'flip'}.
    "' rotate='".$_[0]{'options'}{'rotate'}.
    "' />";
  if(param('displayimages') || $action !~ /^edit/)
  {
    if($link) {
     if($action =~ /^edit/) {
      $html = $html."<a href=\"javascript:editlink('$_[0]{'options'}{'position'}');\" title='Edit linked image'>";
     }
     else {
      $html .= "<a href=\"gallery.pl?action=view&source=".text2href($fulllink)."\">\n";
     }
    }
    $html = $html."<img border=0 width=$sizex height=$sizey ".
      "src='gallery.pl?action=getimage&source=".
       &text2href($imgsrc)."'";
    $html = $html."/>";
    if($link)
    {
      $html = $html."</a>";
    }
  }
  else
  {
    my $filename;
    if($_[0]{'options'}{'filename'} =~ /.*\/(.+)/)
    {
      $filename = $1;
    }
    $html .= "<table><tr><td width=$sizex height=$sizey bgcolor='#444444' align='center'>".
             "<font face='verdana' size='2'>";
    if($link)
    {
      $html = $html."<a href=\"javascript:editlink('$_[0]{'options'}{'position'}');\" title='Edit linked image'>";
    }
    $html .= $filename;
    if($link)
    {
      $html = $html."</a>";
    }
    $html .= "<br />".
             "<font size='1'>".
             "<a href='javascript:showinsidebar(\"".$_[0]{'options'}{'filename'}.
             "\")' title='View image in side bar.'>view</a>".
             "</font></font>".
             "</td></tr></table>";
  }
  $html = $html."<br/>\n";
  if($action =~ /^edit/) {
    $html = $html."<font face='verdana' size=1>";
    if($caps & 15){ $html .=
      "Add caption: ";
    }
    if($caps & 4){ $html .=
      "<a href='javascript:addcaption($_[0]{'options'}{'position'},\"left\");' title='Add caption on the left of image'>&lt;</a> ";
    }
    if($caps & 1){ $html .=
      "<a href='javascript:addcaption($_[0]{'options'}{'position'},\"top\");' title='Add caption above image'>^</a> ";
    }
    if($caps & 2){ $html .=
      "<a href='javascript:addcaption($_[0]{'options'}{'position'},\"bottom\");' title='Add caption below image'>V</a> ";
    }
    if($caps & 8){ $html .=
    "<a href='javascript:addcaption($_[0]{'options'}{'position'},\"right\");' title='Add caption to the right of image'>&gt;</a>";
    }
    $html .= "<br />\n";
    if($action ne "editlink") {
     if(!$link) {
      $html = $html."<a href='javascript:addlink($_[0]{'options'}{'position'});' title='Add link to larger image'>Add Link</a><br />";
     }
     else {
      $html = $html."<a href='javascript:rmlink($_[0]{'options'}{'position'});' title='Remove link to larger image'>Remove Link</a><br />";
     }
    }
    $html = $html."</font>\n".
    "<input type='button' onClick='edit(this);' value='Edit'/>\n";
   if($action eq "edit"){
    $html = $html.
    "<input type='button' onClick='del(this);' value='Del'/>\n";
   }
  }

  foreach my $obj (@{$_[0]{'children'}}) {
    if($$obj{'tag'} eq "caption" && $$obj{'options'}{'placement'} eq "bottom") {
      $html = $html.&gethtml($obj);
      last;
    }
  }

  foreach my $obj (@{$_[0]{'children'}}) {
    if($$obj{'tag'} eq "caption" &&
     $$obj{'options'}{'placement'} eq "right") {
      $html = $html.&gethtml($obj);
      last;
    }
  }

  $html = $html."</td>\n";

  if($action =~ /^edit/ && (($_[0]{'options'}{'position'} + 1) % $cols)) {
    $html = $html."<td valign='top'><a href='javascript:addspace(".
     ($_[0]{'options'}{'position'} + 1).");' title='Insert Space'>\n".
     "<img src='/img/web/d-arrow.gif' border=0 /></a><br /><br />".
     "<a href='javascript:addimage(".
     ($_[0]{'options'}{'position'} + 1).");' title='Insert Image'>\n".
     "<img src='/img/web/i-insert.gif' border=0 /></a><br /><br />".
     "<a href='javascript:swap(".
      $_[0]{'options'}{'position'}.",".
     ($_[0]{'options'}{'position'} + 1).");' title='Swap Images'>\n".
     "<img src='/img/web/h-arrow.gif' border=0 /></a></td>";
  }

  if($action =~ /^edit/) {
    $html = $html."<input type='hidden' name='/tag' value='image'>\n";
  }
  $html = $html."</tr></table>\n";

  $html = $html."</td>\n";
  return $html;
}

sub gallery2html {
  my $html;

  $html = "<table";

  tableoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
    if($key eq "rows" || $key eq "cols") {
      next tableoptions;
    }
    $html = $html." $key='$value'";
  }
  $html = $html.">\n";

  if($action =~ /^edit/) {
    $html = $html.
    "<tr><td colspan=20><font size=2>\n".
    "<input type='hidden' name='tag' value='gallery'>\n".
    "<input size=4 type='hidden' name='cols' value='".
    $_[0]{'options'}{'cols'}."'/>\n".
    "<input type='hidden' name='otherparams' value='";

    editgalleryoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
      if($key eq "cols" || $key eq "rows") {
        next editgalleryoptions;
      }
      $html = $html." $key=\"$value\"";
    }

    $html = $html.
    "'/n>\n";
   if($action eq "edit"){
    $html = $html.
    "<input type='button' onClick='edit(this);' value='Table Properties'/>\n".
    "<a href='javascript:addimage()'>Insert Image</a>";
   }
    $html = $html.
    "</td></tr>\n";
  }

  my $cols = $_[0]{'options'}{'cols'};
  my $rows = $_[0]{'options'}{'rows'};
  for(my $y = 0;$y < $rows;$y++) {
    $html = $html."<tr>";
    for(my $x = 0;$x < $cols;$x++) {
      my $good = 0;
      foreach my $obj (@{$_[0]{'children'}}) {
        if($$obj{'options'}{'position'} eq $x + ($cols * $y)) {
          $good = 1;
          $html = $html.&gethtml($obj);
        }
      }
      if(!$good){
        $html = $html."<td align='center'>";
        if($action =~ /^edit/){
          $html .= "<a href='javascript:delspace(".($x + ($cols * $y)).
          ");' title='Delete Space'><img src='/img/web/x-delete.gif' border=0 /></a>";
        }
        $html .= "</td>\n";
      }
    }
    $html = $html."</tr>\n";
  }

  if($action =~ /^edit/) {
    $html = $html."<input type='hidden' name='/tag' value='gallery'>\n";
  }
  if($action eq "save") {
    my $prev = param('previous');
    if(!$prev){$prev = "index.html";}
    my $next = param('next');
    if(!$next){$next = "index.html";}
    $html .= "<tr><td><table width=100% border=0><tr><td align='left'>\n".
    "<a href='$prev'>Previous</a>".
    "</td><td align='right'>\n".
    "<a href='$next'>Next</a>".
    "</td></tr></table>\n";
  }
  $html = $html."</table></td></tr>\n";
  return $html;
}

sub page2html {
  my $html;

  $html = "<html>\n<title>\n".
  $_[0]{'options'}{'name'}.
  "\n</title>\n";

  if($action =~ /^edit/){
    $imgedittop = 280;
    $imgeditleft = 10;
    $html = $html.
    "<script name='javascript'>\n".
    "  addimagexml = '';\n".
    "  addcaptionto = '';\n".
    "  addlinkto = '';\n".
    "  addlinkname = '';\n".
    "  addcaptionon = 0;\n".
    "  addcaptionvalue = '';\n".
    "  pos = 'end';\n".
    "  plain = '';\n";
    if($action eq "editlink"){
      $html = $html.
      "  function writeback() {\n".
      "    found = 0;\n".
      "    for(x=0;x < window.opener.document.inpage.elements.length;x++) {\n".
      "      obj = window.opener.document.inpage.elements[x];\n".
      "      if(obj.name == 'position' && obj.value == '".param('position')."'){\n".
      "        found = 1;\n".
      "      }\n".
      "      if(obj.name == 'plain' && found) {\n".
      "        plain = obj;\n".
      "        found = 0;\n".
      "      }\n".
      "    }\n".
      "    document.xmlform.action.value = '$action';\n".
      "    update(1);\n".
      "    opener.document.xmlform.action.value = 'edit';\n".
      "    opener.update();\n".
      "  }\n";
    }
    $html = $html.
    "  function editlink(position) {\n".
    "   intag = 0;\n".
    "    for(x=0;x < document.inpage.elements.length;x++) {\n".
    "      obj = document.inpage.elements[x];\n".
    "      if(obj.name == 'position') {intag = obj.value; }\n".
    "      if(intag == position && obj.name == 'plain'){\n". 
    "        window.open('gallery.pl?' +\n".
    "        'action=editlink' +\n".
    "        '&autoupdate=' + document.xmlform.autoupdate.checked +\n".
    "        '&position=' + position +\n".
    "        '&source=' +\n".
    "        escape(\"<page ";
        opt: while ((my $key, my $value) = each %{$page{'options'}}) {
          if($key eq "name" || $key eq "srcdir" || $key eq "sync" ||
            $key eq "imgsize" || $key eq "quality" ||
            $key eq "filter" || $key =~ /^crop/) {
            next opt;
          }
          $html .= " $key='$value'";
        }
        $html .= ">".
        "<gallery cols='1' ".
        "bgcolor='".$page{'children'}[0]{'options'}{'bgcolor'}."'>\") +\n".
    "        obj.value +\n".
    "        escape('</gallery></page>'));\n".

    "      }\n".
    "    }\n".
    "  }\n".
    "  function update(manual) {\n".
    "    if(!document.xmlform.autoupdate.checked && !manual){\n".
    "      return;\n".
    "    }\n".
    "    intag = 0; xml = '';\n".
    "    depth = 0;\n".
    "    for(x=0;x < document.inpage.elements.length;x++) {\n".
    "      obj = document.inpage.elements[x];\n".
    "      if(plain && depth < 3) {\n".
    "        if(obj.name == 'tag') {\n".
    "          depth += 1;\n".
    "          intag = 1;\n".
    "          if(depth == 3){xml = xml + '<image '; }\n".
    "        }\n".
    "        else if(obj.name == '/tag') {\n".
    "          depth -= 1;\n".
    "          intag = 0;\n".
    "        }\n".
    "      }\n".
    "      else if(obj.name == 'plain') {\n".
    "        if(intag){\n".
    "          xml = xml + '>\\n';\n".
    "          intag = 0;\n".
    "        }\n".
    "        xml = xml + unescape(obj.value) + '\\n';\n".
    "      }\n".
    "      else if(obj.name == 'tag') {\n".
    "        if(intag){\n".
    "          xml = xml + '>\\n';\n".
    "          intag = 0;\n".
    "        }\n".
    "        xml = xml + '<' + obj.value + '\\n';\n".
    "        intag = 1;\n".
    "        depth += 1;\n".
    "      }\n".
    "      else if(obj.name == '/tag') {\n".
    "        if(intag){\n".
    "          xml = xml + '>\\n';\n".
    "          intag = 0;\n".
    "        }\n".
    "        if(pos == addlinkto && obj.value == 'image'){ xml = xml + ".
      "\"<image position=0 filename='\" + addlinkname + \"'/>\";\n".
    "          pos = 'end';\n".
    "        }\n".
    "        if(pos == addcaptionto && obj.value == 'image'){ xml = xml + \"<caption placement='\" +\n".
    "          addcaptionon + \"' value='\" + escape(addcaptionvalue) + \"' />\";\n".
    "          pos = 'end';\n".
    "        }\n".
    "        if(addimagexml && obj.value == 'gallery'){\n".
    "          xml = xml + addimagexml;\n".
    "        }\n".
    "        xml = xml + '<' + '/' + obj.value + '>\\n';\n".
    "        depth -= 1;\n".
    "      }\n".
    "      else if(obj.name == 'otherparams'){\n".
    "        xml = xml + '   ' + obj.value + '\\n';".
    "      }\n".
    "      else if(obj.type == 'checkbox'){\n".
    "        if(obj.checked) {\n".
    "          xml = xml + '    ' + obj.name + '=\\'yes\\'\\n';\n".
    "        }\n".
    "      }\n".
    "      else if(obj.type == 'button'){\n".
    "      }\n".

    "      else if(obj.name != '' && obj.value != '' && plain) {\n".
    "        if(obj.name == 'position'){ pos = obj.value; }\n".
    "        xml = xml + '    ' + obj.name + '=\\'' + escape(obj.value) + '\\'\\n';\n".
    "      }\n".

    "      else if(obj.name != '' && obj.value != '') {\n".
    "        if(obj.name == 'position'){ pos = obj.value; }\n".
    "        xml = xml + '    ' + obj.name + '=\\'' + obj.value + '\\'\\n';\n".
    "      }\n".

    "    }\n".
#"document.write(xml);\n".
    "    if(plain){\n".
    "      plain.value = xml;\n".
    "      window.close();\n".
    "    }\n".
    "    else{\n".
    "      document.xmlform.source.value = xml;\n".
    "      document.xmlform.submit();\n".
    "    }\n".
    "  }\n".
    "  function addspace(position) {\n".
    "    for(x=0;x < document.inpage.elements.length;x++) {\n".
    "      obj = document.inpage.elements[x];\n".
    "      if(obj.name == 'position' && parseInt(obj.value) >= parseInt(position)){\n".
    "        obj.value = (parseInt(obj.value) + 1) + '';\n".
    "      }\n".
    "    }\n".
    "    document.xmlform.action.value = '$action';\n".
    "    document.inpage.sync.checked = 0;\n".
    "    update(1);\n".
    "  }\n".
    "  function delspace(position) {\n".
    "    for(x=0;x < document.inpage.elements.length;x++) {\n".
    "      obj = document.inpage.elements[x];\n".
    "      if(obj.name == 'position' && parseInt(obj.value) >= parseInt(position)){\n".
    "        obj.value = (parseInt(obj.value) - 1) + '';\n".
    "      }\n".
    "    }\n".
    "    document.xmlform.action.value = '$action';\n".
    "    document.inpage.sync.checked = 0;\n".
    "    update(1);\n".
    "  }\n".
    "  function addimage(position) {\n".
    "    if((addimageat = position) || (addimageat = prompt('Enter image position:', '0'))) {\n".
    "      depth = 0;\n".
    "      ingallery = 0;\n".
    "      for(x=0;x < document.inpage.elements.length;x++) {\n".
    "        obj = document.inpage.elements[x];\n".
    "        if(obj.name == 'tag') {\n".
    "          depth = depth + 1;\n".
    "          if(obj.value == 'page'){ ingallery = depth; }\n".
    "        }\n".
    "        if(obj.name == '/tag') {\n".
    "          depth = depth - 1;\n".
    "          if(obj.value == 'page'){ ingallery = 0; }\n".
    "        }\n".
    "        if(obj.name == 'position' && obj.value >= addimageat) {\n".
    "          obj.value = parseInt(obj.value) + 1;\n".
    "        }\n".
    "        if(obj.name == 'quality' && depth == ingallery){ quality = obj.value; }\n".
    "        if(obj.name == 'filter' && depth == ingallery){ filter = obj.value; }\n".
    "        if(obj.name == 'imgsize' && depth == ingallery){ size = obj.value; }\n".
    "        if(obj.name == 'cropstart' && depth == ingallery){ cropstart = obj.value; }\n".
    "        if(obj.name == 'cropsize' && depth == ingallery){ cropsize = obj.value; }\n".
    "      }\n".
    "      addimagexml = \"<image ".
      "filename='/img/art/paw/splitrefsmall.gif' ".
      "quality='\" + quality + \"' ".
      "filter='\" + filter + \"' ".
      "size='\" + size + \"' ".
      "cropstart='\" + cropstart + \"' ".
      "cropsize='\" + cropsize + \"' ".
      "position='\" + addimageat + \"' />\";\n";
  if($action eq "edit"){
    $html = $html.
    "      document.inpage.sync.checked = 0;\n";
  }
  $html = $html.
    "      document.xmlform.action.value = '$action';\n".
    "      update(1);\n".
    "    }\n".
    "  }\n".
    "  function rmlink(image) {\n".
    "    found = 0;\n".
    "    for(x=0;x < document.inpage.elements.length;x++) {\n".
    "      obj = document.inpage.elements[x];\n".
    "      if(obj.name == 'position'){found = obj.value;}\n".
    "      if(obj.name == 'plain' && found == image){\n".
    "        obj.value = '';\n".
    "      }\n".
    "    }\n".
    "    document.xmlform.action.value = '$action';\n".
    "    update(1);\n".
    "  }\n".
    "  function addlink(image) {\n".
    "    addlinkto = image;\n".
    "    tagstart = 0;\n".
    "    found = 0;\n".
    "    for(x=0;x < document.inpage.elements.length;x++) {\n".
    "      obj = document.inpage.elements[x];\n".
    "      if(!found){\n".
    "        if(obj.name == 'filename'){addlinkname = obj.value; }\n".
    "        if(obj.name == 'position' && obj.value == image){\n".
    "          found = 1;\n".
    "        }\n".
    "      }\n".
    "    }\n";
  if($action eq "edit"){
    $html = $html.
    "    document.inpage.sync.checked = 0;\n";
  }
  $html = $html.
    "    document.xmlform.action.value = '$action';\n".
    "    update(1);\n".
    "  }\n".
    "  function addcaption(image, placement) {\n".
    "    if(addcaptionvalue = prompt('Enter caption text:', \"<font face=\" + unescape('%22') + \"verdana\" + unescape('%22') + \" size=2>Caption</font>\")) {\n".
    "      addcaptionto = image;\n".
    "      addcaptionon = placement;\n";
  if($action eq "edit"){
    $html = $html.
    "      document.inpage.sync.checked = 0;\n";
  }
  $html = $html.
    "      document.xmlform.action.value = '$action';\n".
    "      update(1);\n".
    "    }\n".
    "  }\n".
    "  function del(clicked) {\n".
    "    tagA = new Array();\n".
    "    tag = matched = 0;\n".
    "    depth = -1;\n".
    "    for(x=0;x < document.inpage.elements.length;x++) {\n".
    "      if(!matched) {\n".
    "        obj = document.inpage.elements[x];\n".
    "        if(obj.name == 'tag') {\n".
    "          depth += 1;\n".
    "          tagA[depth] = x;\n".
    "        }\n".
    "        if(obj.name == '/tag') {\n".
    "          depth -= 1;\n".
    "        }\n".
    "        if(clicked == obj){\n".
    "          matched = 1;\n".
    "          tag = tagA[depth];\n".
    "        }\n".
    "      }\n".
    "      else { break; }\n".
    "    }\n";
  if($action eq "edit"){
    $html = $html.
    "    document.inpage.sync.checked = 0;\n";
  }
  $html = $html.
    "    depth = 0;\n".
    "    for(x=tag;x < document.inpage.elements.length;x++) {\n".
    "      obj2 = document.inpage.elements[x];\n".
    "      if(obj2.name == 'tag') {\n".
    "        depth += 1;\n".
    "      }\n".
    "      if(obj2.name == '/tag') {\n".
    "        depth -= 1;\n".
    "      }\n".
    "      if(depth >= 0){\n".
    "        obj2.name = '';\n".
    "        obj2.value = '';\n".
    "        if(depth == 0){depth = -255;\n".
    "          break;}\n".
    "      }\n".
    "    }\n".
    "    document.xmlform.action.value = '$action';\n".
    "    update();\n".
    "  }\n".
    "  function swap(x,y) {\n";
  if($action eq "edit"){
    $html = $html.
    "    document.inpage.sync.checked = 0;\n";
  }
  $html = $html.
    "    for(n=0;n < document.inpage.elements.length;n++) {\n".
    "      obj = document.inpage.elements[n];\n".
    "      if(obj.name == 'position') {\n".
    "        if(obj.value == x){\n".
    "          obj.value = y;\n".
    "        }\n".
    "        else if(obj.value == y){\n".
    "          obj.value = x;\n".
    "        }\n".
    "      }\n".
    "    }\n".
    "    document.xmlform.action.value = '$action';\n".
    "    update(1);\n".
    "  }\n".
    "  sidebar = '';\n".
    "  function showinsidebar(filename)\n".
    "  {\n".
    "    sidebar = window.open('','sidebar', 'dependant=yes,menubar=no,scrollbars=yes,resizable=yes,height=400,width=400');\n".
    "    if(!sidebar.document.images[0])\n".
    "    {\n".
    "      sidebar.document.write(\n".
      "      \"<html><head><title>Image Side Bar</title></head>\\n\" +\n".
      "      \"<body bgcolor='#000088' text='#FFFFFF'><p align='center'>\");\n".
    "      for(x=0;x < document.inpage.elements.length;x++) {\n".
    "        obj = document.inpage.elements[x];\n".
    "        if(obj.name == 'filename')\n".
    "        {\n".
    "          sidebar.document.write(\n".
      "          obj.value + '<a name=\"' + obj.value + '\"<br />' +\n".
      "          '<img id=\"' + filename + '\" src=\"gallery.pl?action=getimage&source=%3cimage%20filename%3d%27' + obj.value + '%27%20size%3d%27<370x370%27%20filter%3d%27Lanczos%27%20quality%3d%2725%27%20%2f%3e\" />' +\n".
      "          '<br /><br />');\n".
    "        }\n".
    "      }\n".
    "      sidebar.document.write('<font color=\"#000088\">EOF</font></p></body></html>');".
    "      sidebar.document.close();\n".
    "    }\n".
    "    if(!document.all)\n".
    "    {\n".
    "      sidebar.find('EOF',1,0);\n".
    "      sidebar.find(filename,0,1);\n".
    "    }\n".
    "    else\n".
    "    {\n".
    "      txt = sidebar.document.body.createTextRange();\n".
    "      txt.findText('EOF');\n".
    "      txt.select();\n".
    "      txt.scrollIntoView();\n".
    "      txt.findText(filename,-327680,1);\n".
    "      txt.select();\n".
    "      txt.scrollIntoView();\n".
    "    }\n".
    "    sidebar.focus();\n".
    "  }\n".
    "  function edit(clicked) {\n".
    "    tagA = new Array();\n".
    "    tag = matched = 0;\n".
    "    depth = -1;\n".
    "    for(x=0;x < document.inpage.elements.length;x++) {\n".
    "      obj = document.inpage.elements[x];\n".
    "      if(!matched) {\n".
    "        if(obj.name == 'tag') {\n".
    "          depth += 1;\n".
    "          tagA[depth] = x;\n".
    "        }\n".
    "        if(obj.name == '/tag') {\n".
    "          depth -= 1;\n".
    "        }\n".
    "        if(clicked == obj){\n".
    "          matched = 1;\n".
    "          tag = tagA[depth];\n".
    "        }\n".
    "      }\n".
    "    }\n".
    "    editbox = window.open('','edit', 'dependent=yes,menubar=no,scrollbars=yes,resizable=yes,height=450,width=400');\n".
    "    editbox.document.write(\n".
      "      \"<\" + \"html><\" + \"head><\" + \"title>Edit Element<\" + \"/title><\" + \"/head>\\n\" +\n".
      "      \"<\" + \"body bgcolor=#000088 text=#FFFFFF\");\n".
    "    if(document.inpage.elements[tag].value == 'image') {\n".
    "      editbox.document.write(\n".
      "      \" onMouseUp='mouseup();'\");\n".
    "    }\n".
    "    editbox.document.write(\">\\n\" +\n".
      "      \"<\" + \"script language='javascript'>\\n\" +\n".
      "      \"  caller = '';\\n\" +\n".
      "      \"  function setcaller(call) {\\n\" +\n".
      "      \"    caller = call;\\n\" +\n".
      "      \"  }\\n\" +\n".
      "      \"  function switchRot() {\\n\" +\n".
      "      \"    if(document.editform.rotate && (document.editform.rotate.value == 90 || document.editform.rotate.value == -90))\\n\" +\n".
      "      \"    {\\n\" +\n".
      "      \"      stringarray = document.editform.size.value.split('x',2);\\n\" +\n".
      "      \"      imgwidth = parseInt(stringarray[0]);\\n\" +\n".
      "      \"      imgheight = parseInt(stringarray[1]);\\n\" +\n".
      "      \"      stringarray = document.editform.cropstart.value.split('x',2);\\n\" +\n".
      "      \"      cropleft = parseInt(stringarray[0]);\\n\" +\n".
      "      \"      croptop = parseInt(stringarray[1]);\\n\" +\n".
      "      \"      stringarray = document.editform.cropsize.value.split('x',2);\\n\" +\n".
      "      \"      cropwidth = parseInt(stringarray[0]);\\n\" +\n".
      "      \"      cropheight = parseInt(stringarray[1]);\\n\" +\n".

      "      \"      document.editform.size.value = imgheight + 'x' + imgwidth;\\n\" +\n".
      "      \"      document.editform.cropstart.value = croptop + 'x' + cropleft;\\n\" +\n".
      "      \"      document.editform.cropsize.value = cropheight + 'x' +cropwidth;\\n\" +\n".
      "      \"    }\\n\" +\n".
      "      \"  }\\n\" +\n".
      "      \"  function ret() {\\n\" +\n".
      "      \"    switchRot();\\n\" +\n".
      "      \"    opener.callback(caller);\\n\" +\n".
      "      \"  }\\n\");\n".
    "    if(document.inpage.elements[tag].value == 'image') {\n".
    "      editbox.document.write(".


      "        \"  starty = startx = simgwidth = simgheight = scroptop = scropleft = scropheight = scropwidth = simgqual = 0;\\n\" +\n".
      "        \"  xMousePos = 0;\\n\" +\n".
      "        \"  yMousePos = 0;\\n\" +\n".
      "        \"  xMousePosMax = 0;\\n\" +\n".
      "        \"  yMousePosMax = 0;\\n\" +\n".

      "        \"  clicked = 0;\\n\" +\n".

      "        \"  function mousedown(object) {\\n\" +\n".
      "        \"    if(document.getElementById) {\\n\" +\n".
      "        \"      stringarray = document.editform.size.value.split('x',2);\\n\" +\n".
      "        \"      simgwidth = parseInt(stringarray[0]);\\n\" +\n".
      "        \"      simgheight = parseInt(stringarray[1]);\\n\" +\n".
      "        \"      stringarray = document.editform.cropstart.value.split('x',2);\\n\" +\n".
      "        \"      scropleft = parseInt(stringarray[0]);\\n\" +\n".
      "        \"      scroptop = parseInt(stringarray[1]);\\n\" +\n".
      "        \"      stringarray = document.editform.cropsize.value.split('x',2);\\n\" +\n".
      "        \"      scropwidth = parseInt(stringarray[0]);\\n\" +\n".
      "        \"      scropheight = parseInt(stringarray[1]);\\n\" +\n".

      "        \"      simgqual = parseInt(document.editform.quality.value);\\n\" +\n".

      "        \"      starty = yMousePos;\\n\" +\n".
      "        \"      startx = xMousePos;\\n\" +\n".

      "        \"      clicked = object;\\n\" +\n".
      "        \"    }\\n\" +\n".
      "        \"  }\\n\" +\n".
      "        \"  function captureMousePosition(e) {\\n\" +\n".
      "        \"    if (document.all) {\\n\" +\n".
      "        \"      xMousePos = window.event.x+document.body.scrollLeft;\\n\" +\n".
      "        \"      yMousePos = window.event.y+document.body.scrollTop;\\n\" +\n".
      "        \"      xMousePosMax = document.body.clientWidth+document.body.scrollLeft;\\n\" +\n".
      "        \"      yMousePosMax = document.body.clientHeight+document.body.scrollTop;\\n\" +\n".
      "        \"    } else if (document.getElementById) {\\n\" +\n".
      "        \"      xMousePos = e.pageX;\\n\" +\n".
      "        \"      yMousePos = e.pageY;\\n\" +\n".
      "        \"      xMousePosMax = window.innerWidth+window.pageXOffset;\\n\" +\n".
      "        \"      yMousePosMax = window.innerHeight+window.pageYOffset;\\n\" +\n".
      "        \"    }\\n\" +\n".
      "        \"    resize(xMousePos - startx,yMousePos - starty);\\n\" +\n".
      "        \"  }\\n\" +\n".
      "        \"  function mouseup() {\\n\" +\n".
      "        \"    clicked = 0;\\n\" +\n".
      "        \"  }\\n\" +\n".
      "        \"  function resize(xmouse, ymouse) {\\n\" +\n".
      "        \"    //Value is relative\\n\" +\n".
      "        \"      stringarray = document.editform.size.value.split('x',2);\\n\" +\n".
      "        \"      imgwidth = parseInt(stringarray[0]);\\n\" +\n".
      "        \"      imgheight = parseInt(stringarray[1]);\\n\" +\n".
      "        \"      stringarray = document.editform.cropstart.value.split('x',2);\\n\" +\n".
      "        \"      cropleft = parseInt(stringarray[0]);\\n\" +\n".
      "        \"      croptop = parseInt(stringarray[1]);\\n\" +\n".
      "        \"      stringarray = document.editform.cropsize.value.split('x',2);\\n\" +\n".
      "        \"      cropwidth = parseInt(stringarray[0]);\\n\" +\n".
      "        \"      cropheight = parseInt(stringarray[1]);\\n\" +\n".

      "        \"      imgqual = parseInt(document.editform.quality.value);\\n\" +\n".

      "        \"    if(!clicked){\\n\" +\n".
      "        \"      startx = xmouse;\\n\" +\n".
      "        \"      starty = ymouse;\\n\" +\n".
      "        \"    }\\n\" +\n".
      "        \"    if(clicked == 2) {\\n\" +\n".
      "        \"      if(xMousePos < 125){\\n\" +\n".
      "        \"        imgqual = simgqual + xmouse;\\n\" +\n".
      "        \"      }\\n\" +\n".
      "        \"    }\\n\" +\n".
      "        \"    else if(startx > (simgwidth + $imgeditleft + 1) && starty > (simgheight + $imgedittop + 1) && (xmouse + ymouse) != 0 && clicked) {\\n\" +\n".
      "        \"      tmp = xmouse + ymouse;\\n\" +\n".
      "        \"      tmp2 = simgwidth + simgheight;\\n\" +\n".
      "        \"      imgwidth = (simgwidth + tmp / (tmp2 / simgwidth));\\n\" +\n".
      "        \"      imgheight = (simgheight + tmp / (tmp2 / simgheight));\\n\" +\n".
      "        \"      imgwidth = Math.round(imgwidth + 0.4);\\n\" +\n".
      "        \"      imgheight = Math.round(imgheight + 0.4);\\n\" +\n".
      "        \"    }\\n\" +\n".
      "        \"    else if(startx > (simgwidth + $imgeditleft + 1) && clicked) {\\n\" +\n".
      "        \"      imgwidth = simgwidth + xmouse;\\n\" +\n".
      "        \"    }\\n\" +\n".
      "        \"    else if(starty > (simgheight + $imgedittop +1) && clicked) {\\n\" +\n".
      "        \"      imgheight = simgheight + ymouse;\\n\" +\n".
      "        \"    }\\n\" +\n".

      "        \"    else if(\\n\" +\n".
      "        \"           startx > (scropleft + $imgeditleft + 1) &&\\n\" +\n".
      "        \"           startx < (scropleft + scropwidth + $imgeditleft + 1) &&\\n\" +\n".
      "        \"           starty > (scroptop + $imgedittop + 1) &&\\n\" +\n".
      "        \"           starty < (scroptop + scropheight + $imgedittop + 1)) {\\n\" +\n".
      "        \"      if(starty > (scroptop + scropheight + $imgedittop - 9) && startx > (scropleft + scropwidth + 1)) {\\n\" +\n".
      "        \"        if(clicked) {\\n\" +\n".
      "        \"          cropheight = scropheight + ymouse;\\n\" +\n".
      "        \"          cropwidth = scropwidth + xmouse;\\n\" +\n".
      "        \"        }\\n\" +\n".
      "        \"        document.getElementById('imgmiddle').style.cursor = 'se-resize'\\n\" +\n".
      "        \"      } else if(starty < (scroptop + $imgedittop + 11) && startx < (scropleft + 21)) {\\n\" +\n".
      "        \"        if(clicked) {\\n\" +\n".
      "        \"          cropheight = scropheight - ymouse;\\n\" +\n".
      "        \"          cropwidth = scropwidth - xmouse;\\n\" +\n".
      "        \"          croptop = scroptop + ymouse;\\n\" +\n".
      "        \"          cropleft = scropleft + xmouse;\\n\" +\n".
      "        \"        }\\n\" +\n".
      "        \"        document.getElementById('imgmiddle').style.cursor = 'nw-resize'\\n\" +\n".
      "        \"      } else if(starty < (scroptop + $imgedittop + 11) && startx > (scropleft + scropwidth + 1)) {\\n\" +\n".
      "        \"        if(clicked) {\\n\" +\n".
      "        \"          cropheight = scropheight - ymouse;\\n\" +\n".
      "        \"          cropwidth = scropwidth + xmouse;\\n\" +\n".
      "        \"          croptop = scroptop + ymouse;\\n\" +\n".
      "        \"        }\\n\" +\n".
      "        \"        document.getElementById('imgmiddle').style.cursor = 'ne-resize'\\n\" +\n".
      "        \"      } else if(starty > (scroptop + scropheight + $imgedittop - 9) && startx < (scropleft + $imgeditleft + 11)) {\\n\" +\n".
      "        \"        if(clicked) {\\n\" +\n".
      "        \"          cropheight = scropheight + ymouse;\\n\" +\n".
      "        \"          cropwidth = scropwidth - xmouse;\\n\" +\n".
      "        \"          cropleft = scropleft + xmouse;\\n\" +\n".
      "        \"        }\\n\" +\n".
      "        \"        document.getElementById('imgmiddle').style.cursor = 'sw-resize'\\n\" +\n".
      "        \"      } else if(startx < (scropleft + $imgeditleft + 11)) {\\n\" +\n".
      "        \"        if(clicked) {\\n\" +\n".
      "        \"          cropwidth = scropwidth - xmouse;\\n\" +\n".
      "        \"          cropleft = scropleft + xmouse;\\n\" +\n".
      "        \"        }\\n\" +\n".
      "        \"        document.getElementById('imgmiddle').style.cursor = 'w-resize'\\n\" +\n".
      "        \"      } else if(starty < (scroptop + $imgedittop + 11)) {\\n\" +\n".
      "        \"        if(clicked) {\\n\" +\n".
      "        \"          cropheight = scropheight - ymouse;\\n\" +\n".
      "        \"          croptop = scroptop + ymouse;\\n\" +\n".
      "        \"        }\\n\" +\n".
      "        \"        document.getElementById('imgmiddle').style.cursor = 'n-resize'\\n\" +\n".
      "        \"      } else if(startx > (scropleft + scropwidth + $imgeditleft - 9)) {\\n\" +\n".
      "        \"        if(clicked) {cropwidth = scropwidth + xmouse; }\\n\" +\n".
      "        \"        document.getElementById('imgmiddle').style.cursor = 'e-resize'\\n\" +\n".
      "        \"      } else if(starty > (scroptop + scropheight + $imgedittop - 9)) {\\n\" +\n".
      "        \"        if(clicked) {cropheight = scropheight + ymouse; }\\n\" +\n".
      "        \"        document.getElementById('imgmiddle').style.cursor = 's-resize'\\n\" +\n".
      "        \"      } else if(clicked){\\n\" +\n".
      "        \"        cropleft = scropleft + xmouse;\\n\" +\n".
      "        \"        croptop = scroptop + ymouse;\\n\" +\n".
      "        \"        if(cropleft + cropwidth > imgwidth) {cropleft = imgwidth - cropwidth; }\\n\" +\n".
      "        \"        if(croptop + cropheight > imgheight) {croptop = imgheight - cropheight; }\\n\" +\n".
      "        \"      } else {\\n\" +\n".
      "        \"        document.getElementById('imgmiddle').style.cursor = 'move';\\n\" +\n".
      "        \"      }\\n\" +\n".
      "        \"    }\\n\" +\n".
   
      "        \"    if(clicked) {\\n\" +\n".
      "        \"      document.editform.size.value = imgwidth + 'x' + imgheight;\\n\" +\n".
      "        \"      document.editform.cropstart.value = cropleft + 'x' + croptop;\\n\" +\n".
      "        \"      document.editform.cropsize.value = cropwidth + 'x' +cropheight;\\n\" +\n".
      "        \"      if(imgqual > 100){imgqual = 100;}\\n\" +\n".
      "        \"      if(imgqual < 0){imgqual = 0;}\\n\" +\n".
      "        \"      document.editform.quality.value = imgqual;\\n\" +\n".
      "        \"      formatimg();\\n\" +\n".
      "        \"    }\\n\" +\n".
      "        \"    else {\\n\" +\n".
      "        \"      starty = startx = 0;\\n\" +\n".
      "        \"    }\\n\" +\n".
      "        \"  }\\n\" +\n".
      "        \"  function pcent() {\\n\" +\n".
      "        \"      stringarray = document.imgform.percent.value.split('x',2);\\n\" +\n".
      "        \"      tmpx = parseFloat(stringarray[0]);\\n\" +\n".
      "        \"      tmpy = parseFloat(stringarray[1]);\\n\" +\n".
      "        \"      tmpx = tmpx * (imgcache.width / 100);\\n\" +\n".
      "        \"      tmpy = tmpy * (imgcache.height / 100);\\n\" +\n".
      "        \"      document.editform.size.value = tmpx + 'x' + tmpy;\\n\" +\n".
      "        \"      formatimg();\\n\" +\n".
      "        \"  }\\n\" +\n".
      "        \"  function checkflip(obj)\\n\" +\n".
      "        \"  {\\n\" +\n".
      "        \"    if(obj.checked){document.getElementById('flip').value = 'yes'}\\n\" +\n".
      "        \"    else {document.getElementById('flip').value = 'no'}\\n\" +\n".
      "        \"  }\\n\" +\n".
      "        \"  function formatimg() {\\n\" +\n".
      "        \"    if(document.getElementById) {\\n\" +\n".
      "        \"      if(document.editform.size.value == 'NaNxNaN'){\\n\" +\n".
      "        \"        document.editform.size.value = imgcache.width + 'x' + imgcache.height;\\n\" +\n".
      "        \"      }\\n\" +\n".
      "        \"      if(document.editform.cropstart.value == 'NaNxNaN'){\\n\" +\n".
      "        \"        document.editform.cropstart.value = '0x0';\\n\" +\n".
      "        \"      }\\n\" +\n".
      "        \"      if(document.editform.cropsize.value == 'NaNxNaN'){\\n\" +\n".
      "        \"        document.editform.cropsize.value = document.editform.size.value;\\n\" +\n".
      "        \"      }\\n\" +\n".
      "        \"      if(document.editform.filter.value == ''){\\n\" +\n".
      "        \"        document.editform.filter.value = 'Lanczos';\\n\" +\n".
      "        \"      }\\n\" +\n".
      "        \"      if(document.editform.quality.value == ''){\\n\" +\n".
      "        \"        document.editform.quality.value = '100';\\n\" +\n".
      "        \"      }\\n\" +\n".
      "        \"      stringarray = document.editform.size.value.split('x',2);\\n\" +\n".
      "        \"      imgwidth = parseInt(stringarray[0]);\\n\" +\n".
      "        \"      imgheight = parseInt(stringarray[1]);\\n\" +\n".
      "        \"      stringarray = document.editform.cropstart.value.split('x',2);\\n\" +\n".
      "        \"      cropleft = parseInt(stringarray[0]);\\n\" +\n".
      "        \"      croptop = parseInt(stringarray[1]);\\n\" +\n".
      "        \"      stringarray = document.editform.cropsize.value.split('x',2);\\n\" +\n".
      "        \"      cropwidth = parseInt(stringarray[0]);\\n\" +\n".
      "        \"      cropheight = parseInt(stringarray[1]);\\n\" +\n".

      "        \"      quality = parseInt(document.editform.quality.value);\\n\" +\n".
      "        \"      myslider = document.getElementById('slider');\\n\" +\n".
      "        \"      myslider.style.left = quality;\\n\" +\n".

      "        \"    tmpx = (100/(imgcache.width/imgwidth));\\n\" +\n".
      "        \"    tmpy = (100/(imgcache.height/imgheight));\\n\" +\n".
      "        \"    document.imgform.percent.value = (Math.round((tmpx * 100) + 0.4)/100) + '%x' + (Math.round((tmpy * 100) + 0.4)/100) + '%';\\n\" +\n".
      "        \"      if(croptop + cropheight > imgheight) {\\n\" +\n".
      "        \"        if(cropheight > imgheight){ cropheight = imgheight; }\\n\" +\n".
      "        \"        croptop = imgheight - cropheight;\\n\" +\n".
      "        \"      }\\n\" +\n".
      "        \"      if(cropleft + cropwidth > imgwidth) {\\n\" +\n".
      "        \"        if(cropwidth > imgwidth){ cropwidth = imgwidth; }\\n\" +\n".
      "        \"        cropleft = imgwidth - cropwidth;\\n\" +\n".
      "        \"      }\\n\" +\n".

      "        \"      if(imgwidth < 1) { imgwidth = 1; }\\n\" +\n".
      "        \"      if(imgheight < 1) { imgheight = 1; }\\n\" +\n".
      "        \"      if(cropwidth < 1) { cropwidth = 1; }\\n\" +\n".
      "        \"      if(cropheight < 1) { cropheight = 1; }\\n\" +\n".
      "        \"      if(cropleft < 0) { cropleft = 0; }\\n\" +\n".
      "        \"      if(croptop < 0) { croptop = 0; }\\n\" +\n".

      "        \"        dispimgwidth = imgwidth;\\n\" +\n".
      "        \"        dispimgheight = imgheight;\\n\" +\n".
      "        \"        dispcropleft = cropleft;\\n\" +\n".
      "        \"        dispcroptop = croptop;\\n\" +\n".
      "        \"        dispcropwidth = cropwidth;\\n\" +\n".
      "        \"        dispcropheight = cropheight;\\n\" +\n".

      "        \"      document.images[3].width = dispimgwidth;\\n\" +\n".
      "        \"      document.images[3].height = dispimgheight;\\n\" +\n".

      "        \"      document.getElementById('imgcover').setAttribute('width', dispimgwidth + 12);\\n\" +\n".
      "        \"      document.getElementById('imgcover').setAttribute('height', dispimgheight + 12);\\n\" +\n".

      "        \"      document.getElementById('imgtop').setAttribute('width', dispcropleft + 1);\\n\" +\n".
      "        \"      document.getElementById('imgtop').setAttribute('height', dispcroptop + 1);\\n\" +\n".

      "        \"      document.getElementById('imgmiddle').setAttribute('width', dispcropwidth);\\n\" +\n".
      "        \"      document.getElementById('imgmiddle').setAttribute('height', dispcropheight);\\n\" +\n".

      "        \"      document.getElementById('imgbottom').setAttribute('width', ((dispimgwidth + 1) - dispcropwidth) - dispcropleft);\\n\" +\n".
      "        \"      document.getElementById('imgbottom').setAttribute('height', ((dispimgheight + 1) - dispcropheight) - dispcroptop);\\n\" +\n".

      "        \"      document.editform.size.value = imgwidth + 'x' + imgheight;\\n\" +\n".
      "        \"      document.editform.cropstart.value = cropleft + 'x' + croptop;\\n\" +\n".
      "        \"      document.editform.cropsize.value = cropwidth + 'x' +cropheight;\\n\" +\n".
      "        \"    }\\n\" +\n".
      "        \"  }\");\n".
    "      }\n    editbox.document.write(\"".



      "<\" + \"/script>\\n".
      "<\" + \"input type='button' value='done' onClick='ret();'/><\" + \"br />\\n".
      "\");\n".
    "    depth = 0;\n".
    "    editbox.document.write(".
      "\"<table border=0>\\n\" +\n".
      "\"<tr><td><form name='editform'>\\n\" +\n".
      "\"<table cellspacing=0 cellpadding=0 border=0>\\n\");\n".
    "    for(x=tag;x < document.inpage.elements.length;x++) {\n".
    "      obj2 = document.inpage.elements[x];\n".
    "      if(obj2.name == 'tag') {\n".
    "        depth += 1;\n".
    "      }\n".
    "      else if(obj2.name == '/tag') {\n".
    "        depth -= 1;\n".
    "        if(depth == 0){depth = -255; }\n".
    "      }\n".
    "      if(depth == 1 && obj2.type != 'button' && obj2.name != '/tag' &&\n".
      "obj2.name != 'tag' && obj2.type != 'checkbox' && obj2.name != 'plain'";

  if($action eq "editlink"){ $html = $html." && obj2.name != 'position'"; }

  $html = $html.
      "){\n".
    "        editbox.document.write(".
             "\"<tr><td>\" + obj2.name + \":</td><td>\");\n".
    "        if(obj2.name == 'value') {\n".
    "          editbox.document.write(\"<textarea name='\" + ".
               "obj2.name + \"'>\" + unescape(obj2.value) + \"</textarea>\");\n".
    "        }\n".
    "        else if(obj2.name == 'quality' && document.inpage.elements[tag].value == 'image') {\n".
    "          editbox.document.write(\"<input type='text' name='\" + \n".
               "obj2.name + \"' value='\" + obj2.value + \"'\" +\n".
               "\" onChange='formatimg();' size=3 />\" +\n".

               "\"<span style='position:relative;top:0;left:0'>.\" +\n".
               "\"<div style='position:absolute;top:0;left:0'>\" +\n".
               "\"<img src='/img/web/sliderule.gif' /></div>\" +\n".
               "\"<div id='slider' style='position:absolute;top:0;left:0'>\" +\n".
               "\"<img src='/img/web/slider.gif' /></div>\" +\n".

               "\"<div style='position:absolute;top:0;left:0'>\" +\n".
               "\"<table border=0 cellspacing=0 cellpadding=0 onMouseDown='mousedown(2);'>\" +\n".
               "\" <tr><td width=105 height=16 onMouseDown='mousedown(2);'>\\n\" +\n".
               "\"<img src='/img/web/dot.gif' /></td></tr></table></div>\" +\n".

               "\"</span>\");\n".
    "        }\n".
    "        else if(obj2.name == 'filter') {\n".
    "          editbox.document.write(\"<select name='\" + \n".
    "          obj2.name + \"'>\\n\" + \n".
    "          \"<option value='\" + obj2.value + \"' selected />\" + obj2.value + '\\n' + \n".
    "          \"<option value='Lanczos' />-----------\\n\" + \n".
    "          \"<option value='Point' />Point\\n\" + \n".
    "          \"<option value='Box' />Box\\n\" + \n".
    "          \"<option value='Triangle' />Triangle\\n\" + \n".
    "          \"<option value='Hermite' />Hermite\\n\" + \n".
    "          \"<option value='Hanning' />Hanning\\n\" + \n".
    "          \"<option value='Hamming' />Hamming\\n\" + \n".
    "          \"<option value='Blackman' />Blackman\\n\" + \n".
    "          \"<option value='Gaussian' />Gaussian\\n\" + \n".
    "          \"<option value='Quadratic' />Quadratic\\n\" + \n".
    "          \"<option value='Cubic' />Cubic\\n\" + \n".
    "          \"<option value='Catrom' />Catrom\\n\" + \n".
    "          \"<option value='Mitchell' />Mitchell\\n\" + \n".
    "          \"<option value='Lanczos' />Lanczos\\n\" + \n".
    "          \"<option value='Bessel' />Bessel\\n\" + \n".
    "          \"<option value='Sinc' />Sinc\\n\" + \n".
    "          \"</select>\");\n".
    "        }\n".
    "        else if(obj2.name == 'placement') {\n".
    "          editbox.document.write(\"<select name='\" + \n".
    "          obj2.name + \"'>\\n\" + \n".
    "          \"<option value='\" + obj2.value + \"' selected />\" + obj2.value + '\\n' + \n".
    "          \"<option value='top' />------------\\n\" + \n".
    "          \"<option value='top' />Top\\n\" + \n".
    "          \"<option value='bottom' />Bottom\\n\" + \n".
    "          \"<option value='left' />Left\\n\" + \n".
    "          \"<option value='right' />Right\\n\" + \n".
    "          \"</select>\");\n".
    "        }\n".
    "        else if(obj2.name == 'rotate') {\n".
    "          editbox.document.write(\"<select name='\" + \n".
    "          obj2.name + \"'>\\n\" + \n".
    "          \"<option value='\" + obj2.value + \"' selected />\" + obj2.value + '\\n' + \n".
    "          \"<option value='0' />------------\\n\" + \n".
    "          \"<option value='0' />None\\n\" + \n".
    "          \"<option value='90' />90 CW\\n\" + \n".
    "          \"<option value='-90' />90 CCW\\n\" + \n".
    "          \"<option value='180' />180\\n\" + \n".
    "          \"</select>\\n\"\n".
    "          );\n".
    "        }\n".
    "        else if(obj2.name == 'flip')\n".
    "        {\n".
    "          editbox.document.write(\"<input type='checkbox' name='flipcheck' onClick='checkflip(this)'\");\n".
    "          if(obj2.value == 'yes')\n".
    "          {\n".
    "            editbox.document.write(\"checked\");\n".
    "          }\n".
    "          editbox.document.write(\" />\");\n".
    "          editbox.document.write(\"<input type='hidden' id='\" + obj2.name + \"' name='\" + \n".
               "obj2.name + \"' value='\" + obj2.value + \"'\");\n".
    "          editbox.document.write(\" \>\");\n".
    "        }\n".
    "        else {\n".
    "          editbox.document.write(\"<input type='text' name='\" + \n".
               "obj2.name + \"' value='\" + obj2.value + \"'\");\n".
    "          if(document.inpage.elements[tag].value == 'image') {\n".
    "            editbox.document.write(\" onChange='formatimg();'\");\n".
    "          }\n".
    "          editbox.document.write(\" \>\");\n".
    "        }\n".
    "        editbox.document.write(\"</td></tr>\\n\");\n".
    "      }\n".
    "    }\n".
    "    editbox.document.write(\"</table>\" +\n".
    "          \"<script>switchRot();</\" + \"script>\\n\");\n".
    "    editbox.document.write('<\' + \'/form></td>\\n');\n".
    "    if(document.inpage.elements[tag].value == 'image') {\n".
    "      editbox.document.write(".
      "\"<td valign='top'><form name='imgform'><table cellspacing=0><tr><td>\\n\" +\n".
      "        \"size\%:</td><td valign='top'><input type='text' name='percent' onChange='pcent();' size=15/>\\n\" +\n".
      "        \"</td></tr>\\n\" +\n".
      "        \"</table></td>\\n\");\n".
    "    }\n".
    "    editbox.document.write(\"</tr></table>\\n\");\n".

    "    if(document.inpage.elements[tag].value == 'image') {\n".
    "      editbox.document.write(".

      "        \"<\" + \"div style='position: absolute;top: $imgedittop;left: $imgeditleft'>\\n\" +\n".
      "        \"  <\" + \"img src='/img/web/dot.gif' height='100' width='100' onLoad='formatimg();' alt='Loading Image'/>\\n\" +\n".
      "        \"<\" + \"/div>\\n\" +\n".

      "        \"<\" + \"div style='position: absolute;top: ".($imgedittop - 1).";left: 9'>\\n\" +\n".
      "        \"  <\" + \"table id='imgcover' height='112' width='112' border=0 cellspacing=0 cellpadding=0>\\n\" +\n".
      "        \"    <\" + \"tr><\" + \"td bgcolor=#888888 id='imgtop' height=1 width=1><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"        <\" + \"td bgcolor=#888888><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"        <\" + \"td bgcolor=#888888><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"        <\" + \"td bgcolor=#4488CC rowspan=3 onMouseDown='mousedown(1);' style='cursor: e-resize'><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"    <\" + \"/tr>\\n\" +\n".
      "        \"    <\" + \"tr><\" + \"td bgcolor=#888888><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"        <\" + \"td id='imgmiddle' height=50 width=50  onMouseDown='mousedown(1);' style='cursor: move'><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"        <\" + \"td bgcolor=#888888><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"    <\" + \"/tr>\\n\" +\n".
      "        \"    <\" + \"tr><\" + \"td bgcolor=#888888><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"        <\" + \"td bgcolor=#888888><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"        <\" + \"td bgcolor=#888888 id='imgbottom' height=51 width=51><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"    <\" + \"/tr>\\n\" +\n".

      "        \"    <\" + \"tr><\" + \"td bgcolor=#4488CC colspan=3 onMouseDown='mousedown(1);' style='cursor: s-resize'><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"        <\" + \"td bgcolor=#88CCFF height=10 width=10 onMouseDown='mousedown(1);' style='cursor: se-resize'><\" + \"img src='/img/web/dot.gif' /><\" + \"/td>\\n\" +\n".
      "        \"    <\" + \"/tr>\\n\" +\n".
      "        \"  <\" + \"/table>\\n\" +\n".
      "        \"<\" + \"/div>\\n\" +\n".
      "        \"<\" + \"script>\\n\" +\n".
      "        \"      document.onmousemove = captureMousePosition;\\n\" +\n".
      "        \"      imgcache = new Image();\\n\" +\n".
      "        \"      imgcache.src = 'gallery.pl?action=getimage&source=' + ".
        "escape('<image quality=10 filename=\\\\'' + document.editform.filename.value + '\\\\' />');\\n\" +\n".
      "        \"      document.images[3].src = imgcache.src;\\n\" +\n".
#      "        \"      formatimg();\\n\" +\n".
      "        \"<\" + \"/script>\\n\");\n".


    "    }\n".
    "    editbox.document.close();\n".
    "    editbox.setcaller(tag);\n".
    "  }\n".
    "  function callback(tag) {\n".
    "    if(document.inpage.elements[tag].value == 'image' ||
            document.inpage.elements[tag].value == 'caption') {\n";
  if($action eq "edit"){
    $html = $html.
    "      document.inpage.sync.checked = 0;\n";
  }
  $html = $html.
    "    }\n".
    "    depth = 0;\n".
    "    for(x=tag;x < document.inpage.elements.length;x++) {\n".
    "      obj2 = document.inpage.elements[x];\n".
    "      if(obj2.name == 'tag') {\n".
    "        depth += 1;\n".
    "      }\n".
    "      else if(obj2.name == '/tag') {\n".
    "        depth -= 1;\n".
    "        if(depth == 0){depth = -255; }\n".
    "      }\n".
    "      if(depth == 1 && obj2.type != 'button' && obj2.name != '/tag'){\n".
    "        for(z=0;z < editbox.document.editform.elements.length;z++) {\n".
    "          robj = editbox.document.editform.elements[z];\n".
    "          if(obj2.name == robj.name) {\n".
    "            if(obj2.name == 'value')\n".
    "            { obj2.value = escape(robj.value);}\n".
    "            else\n".
    "            { obj2.value = unescape(escape(robj.value).replace(/%27/g, '%22'));}\n".
    "          }\n".
    "        }\n".
    "      }\n".
    "    }\n".
    "    editbox.close();\n".
    "    document.xmlform.action.value = '$action';\n".
    "    update();\n".
    "  }\n".
    "</script>\n";
  }

  $html = $html."<body";

  pageoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
    if($key eq "name" || $key eq "srcdir" || $key eq "sync" ||
       $key eq "imgsize" || $key eq "quality" ||
       $key eq "filter" || $key =~ /^crop/) {
      next pageoptions;
    }
    $html = $html." $key='$value'";
  }
  $html = $html.">\n";

  if($action =~ /^edit/) {
    $html = $html.
    "<form name='inpage'>\n".
    "<input type='hidden' name='tag' value='page'>\n";
   if($action eq "edit"){
    $html = $html.
    "<input type='checkbox' name='sync'";
    if($_[0]{'options'}{'sync'} eq "yes") {
      $html = $html." checked";
    }
    $html = $html.
    "/>\n".
    "<font face='verdana' size=2>\n".
    "Reload directory and reset images to defaults".
    "</font>\n";
   }
    $html = $html.
    "<input type='hidden' name='srcdir' value='".
    $_[0]{'options'}{'srcdir'}."'/>\n".
    "<input type='hidden' name='quality' value='".
    $_[0]{'options'}{'quality'}."'/>\n".
    "<input type='hidden' name='filter' value='".
    $_[0]{'options'}{'filter'}."'/>\n".
    "<input type='hidden' name='imgsize' value='".
    $_[0]{'options'}{'imgsize'}."'/>\n".
    "<input type='hidden' name='cropstart' value='".
    $_[0]{'options'}{'cropstart'}."'/>\n".
    "<input type='hidden' name='cropsize' value='".
    $_[0]{'options'}{'cropsize'}."'/>\n".
    "<input type='hidden' name='otherparams' value='";

    editpageoptions: while ((my $key, my $value) = each %{$_[0]{'options'}}) {
      if($key eq "srcdir" || $key eq "sync" ||
         $key eq "imgsize" || $key eq "quality" ||
         $key eq "filter" || $key =~ /^crop/) {
        next editpageoptions;
      }
      $html = $html." $key=\"$value\"";
    }

    $html = $html.
    "'/n>";
   if($action eq "edit"){
    $html = $html.
    "<br/>\n".
    "<input type='button' onClick='edit(this);' value='Page Properties'/>";
   }
    $html = $html.
    "</td></tr>\n";
  }

  grep {
    $html = $html.&gethtml($_);
  } @{$_[0]{'children'}};

  if($action =~ /^edit/) {
    $html = $html.
    "<input type='hidden' name='/tag' value='page'>\n".
    "<input type='button' value='update' onClick='document.xmlform.action.value = \"$action\";update(1);' />\n".
    "<font face='verdana' size=2>\n".
    "<a href='javascript:document.xmlform.action.value = ".
    "\"view\"; update(1);'>View</a>\n".
    "</font><br />\n";
    if($action eq "editlink") {
      $html = $html.
      "<input type='button' value='Done' onClick='writeback();' />\n";
    }
    else {
      $html = $html.
      "<input type='button' value='Save' onClick='document.xmlform.action.value = \"savetop\";update(1);' />\n";
    }
    $html = $html.
    "</form>\n".
    "<form name='xmlform' action='gallery.pl' method='post'>\n".
    "<input type='checkbox' name='autoupdate' ";
    if((param('autoupdate') ne 'false' && param('autoupdate')) ||
     param('action') eq "new" || param('action') eq "load") {
      $html = $html."checked ";
    }
    $html = $html."/>Auto-update after each edit.\n".
    "<input type='checkbox' name='displayimages' onClick='update();'";
    if((param('displayimages') ne 'false' && param('displayimages')) &&
     param('action') ne "new" && param('action') && "load") {
      $html = $html."checked ";
    }
    $html = $html."/>Display images in gallery while editing.\n".
    "<input type='hidden' name='position' value='".param('position')."'/>\n".
    "<input type='hidden' name='action' value='$action'/>\n".
    "<input type='hidden' name='source' value=''/></form>\n";
  }

  $html = $html."</body>\n</html>\n";
  return $html;
}
sub getxml {
  my $xml = "<$_[0]{'tag'}\n";
  while((my $key, my $value) = each %{$_[0]{'options'}} ) {
    $xml = $xml."    $key='$value'\n";
  }
  if($_[0]{'children'}[0]{'tag'}) {
    $xml = $xml.">\n";
    grep {
      $xml = $xml.&getxml($_);
    } @{$_[0]{'children'}};
    $xml = $xml."</".$_[0]{'tag'}.">\n";
  }
  else {
    $xml=$xml."/>\n";
  }
  return $xml; 
}

sub docmd { #  &docmd(\%hash, $source); ## $hash{'options'}{'optionname'}=value
                         ## $hash{'children'}[0]{'options'}{'optionname'}=value
  my $xml = $_[1];
  %{$_[0]{'options'}};
  %{@{$_[0]{'children'}}};

  while($xml =~ /^[ \r\n\t]/){$xml =~ s/^[ \r\n\t]*//g;}

  if($xml =~ /<([a-z]*)/i) { $_[0]{'tag'} = $1; }
  $xml =~ s/^<($_[0]{'tag'})[ \r\n\t]*//i;
  while ($xml !~ /^\/*>/) {
    (my $key, my $value, $xml) = split("=~=", &getoption($xml));
    if($key ne "rows") {$_[0]{'options'}{$key} = $value;}
  }

  if($page{'options'}{'sync'} eq "yes" && $_[0]{'tag'} eq "gallery") {
    $xml =~ s/[\r\n]+/ /g;
    $xml =~ s/^>.*<\/gallery>/<\/gallery>/;

    my $cols = $_[0]{'options'}{'cols'};
    opendir DIR, $credentials{'file'}.$page{'options'}{'srcdir'};
    my @dir = readdir DIR;
    close DIR;
    @dir = grep($_ =~ /[gj][ip][fe]*[fg]/i, @dir);

    for(my $x=0;$x < @dir;$x++) {
      my $sizex;
      my $sizey;
      my $maxx;
      my $maxy;
      open TMP, "/usr/local/bin/identify \"".
       $credentials{'file'}.$page{'options'}{'srcdir'}.$dir[$x]."\" |";
      $sizex = join "", <TMP>;
      close TMP;
      if($sizex =~ / ([0-9]+)x([0-9]+) /){ $sizex = $1; $sizey = $2; }
      if($page{'options'}{'imgsize'} =~ /([0-9]*)x([0-9]*)/){
        $maxx = $1; $maxy = $2;
      }
      if($sizex > $maxx) {
        $sizey = int(($maxx / $sizex) * $sizey);
        $sizex = $maxx;
      }
      if($sizey > $maxy) {
        $sizex = int(($maxy / $sizey) * $sizex);
        $sizey = $maxy;
      }

      $xml = "<image filename='".$page{'options'}{'srcdir'}.
             $dir[$x]."' align='center' position='".
             $x."' size='".
             $sizex."x".$sizey."' quality='".
             $page{'options'}{'quality'}."' filter='".
             $page{'options'}{'filter'}."' cropstart='".
             $page{'options'}{'cropstart'}."' cropsize='".
             $page{'options'}{'cropsize'}."' flip='no' rotate='0'>".
             "<image filename='".$page{'options'}{'srcdir'}.
             $dir[$x]."' position='0' />".
             "</image>\n".$xml;
    }
    $xml = "> ".$xml;
  }

  if($xml =~ /^>/) {
    $xml =~ s/^>[ \r\n\t]*//;

    my $count = 0;
    while($xml !~ /^<\/$_[0]{'tag'}/i) {
      $xml = &docmd($_[0]{'children'}[$count], $xml);
      $count += 1;
    }
    $xml =~ s/^[^>]*>[ \r\n\t]*//;
  }
  else {
    $xml =~ s/^\/>[ \r\n\t]*//;
  }
  if($_[0]{'tag'} eq "gallery"){
    my $rows = 0;
    foreach my $obj (@{$_[0]{'children'}}) {
      if($rows < $$obj{'options'}{'position'}) {
        $rows = $$obj{'options'}{'position'};
      }
    }
    $rows = int($rows /
            $_[0]{'options'}{'cols'}) + 1;
    $_[0]{'options'}{'rows'} = $rows;
  }
  return $xml;
}

sub getoption { #($key, $value, $source) = split("=~=", &getoption($source))
  my $xml = $_[0];
  if($xml =~ /^([a-zA-Z]*)=/) { 
    my $option = $1;
    my $value;
    $xml =~ s/^$option=//;
    if($xml =~ /^(['"])/) {
      if($xml =~ /^$1([^$1]*)$1/) { $value = $1; }
      $xml =~ s/^.$value.//;
    }
    else {
      if($xml =~ /^([^ \r\n\t]*)/){ $value = $1; }
      $xml =~ s/^$value//;
    }
    $xml =~ s/^[ \r\n\t]*//;
    return "$option=~=$value=~=$xml"
  }
}

sub text2href {
  my $percent = sprintf "%%%x", ord "%";
  my $line = join "", @_;
  $line =~ s/%/$percent/g;
  while($line =~ /([^a-zA-Z0-9%])/){
    my $tmp = $1;
    my $char = sprintf "%%%x", ord $tmp;
    if($char =~ /^%.$/) { $char =~ s/%/%0/; }
    $line =~ s/[$tmp]/$char/g;
  }
return $line;
}

sub href2text {
  my $startline = join "", @_;
  my $line;
  while($startline =~ /([^%]*)%(..)(.*)/)
  {
    my $tmp = chr(hex($2));
    $line .= $1.$tmp;
    $startline = $3;
  }
  $line .= $startline;
  return $line;
}

