// album.js
//
//  Javascript code that generates photoalbum page
//
//  Usage:
//
//    document.write(photoAlbum("index.html"));
//
//  where index.html is the URL of the page that calls it.
//  Make sure to include it _after_ the BODY tag and images.js.
//
//  Search string (the part of URL after ?) tells this Javascript what to show and how.
//  Anchor (the part of URL after #) is used by SlideShowPro for the same purpose.
//  Slideshow is shown if there is an anchor in URL.  Variables id and num are used by both,
//  so you can switch slideshow on and off by moving search to anchor and back.
//
//  Dependencies:
//    medium/*.jpg
//    small/*.jpg
//    i/*.png
//    imageset[] array (usually defined in imagelist.js)
//
//  -- Dmitriy Mayorov http://dimview.org
//

// Preloaded images for mouseovers
var a_over_img = new Array; 
var a_out_img  = new Array; 

function photoAlbum(baseurl)
{

  function getDateByImageName(s)
  {                                        
    var months = new Array();
    months['01'] = russian ? 'января' : 'Jan';
    months['02'] = russian ? 'февраля' : 'Feb';
    months['03'] = russian ? 'марта' : 'Mar';
    months['04'] = russian ? 'апреля' : 'Apr';
    months['05'] = russian ? 'мая' : 'May';
    months['06'] = russian ? 'июня' : 'Jun';
    months['07'] = russian ? 'июля' : 'Jul';
    months['08'] = russian ? 'августа' : 'Aug';
    months['09'] = russian ? 'сентября' : 'Sep';
    months['10'] = russian ? 'октября' : 'Oct';
    months['11'] = russian ? 'ноября' : 'Nov';
    months['12'] = russian ? 'декабря' : 'Dec';
    var delim = russian ? ' ' : '-';
    // Be sure to handle older files properly.
    if (s.substring(0, 4) >= '1999') {
      return s.charAt(7) + s.charAt(8) + delim + 
        months[s.charAt(5) + s.charAt(6)] + delim + s.substring(0, 4);
    } else {
      return s.substring(0, 4);
    }
  }

  function getAlbum(a, r)
  {
    var s;
    if (a == 'f') {
      s = 'family';
    } else if (a == 'i') {
      s = 'flying';
    } else if (a == 'n') {
      s = 'nature';
    } else if (a == 'p') {
      s = 'places';
    } else {
      s = 'recent';
    }
    if (r) {
      s += '.ru';
    } else {
      s += '.en';
    }
    return s;
  }

  // Equivalent to what the form does, only for links
  function makeURL(b, r, l, j, f, i, n, p, a)
  {
    // num is used by SlideShowPro, too
    var x = b + '?';
    if (r) { x += 'r=y&'; }
    if (l) { x += 'l=y&'; }
    if (f && i && n && p) {
      // This is the default, no need to do anything
    } else {
      if (f) { x += 'f=on&'; }
      if (i) { x += 'i=on&'; }
      if (n) { x += 'n=on&'; }
      if (p) { x += 'p=on&'; }
    }
    x += 'num=' + j + '&';

    // SlideShowPro needs album id
    x += 'id=' + getAlbum(a, r);
    return x;
  }

  function getBrowserWindowWidth()
  {
    return (document.layers) ? window.innerWidth : document.body.clientWidth;
  }

  function getBrowserWindowHeight()
  {
    return (document.layers) ? window.innerHeight : document.body.clientHeight;
  }

  // Get parameters (it's either makeURL() output, filter form submission, or SlideShowPro anchor)
  var params = unescape('' + self.location.search);
  var russian = false;                         
  var large = false;
  var firstimg = 0;
  var showf = true;
  var showi = true;
  var shown = true;
  var showp = true;
  if (params.length > 0) {
    if (params.indexOf('r=y') > 0) {
      russian = true;
    }
    if (params.indexOf('l=y') > 0) {
      large = true;
    }
    showf = (params.indexOf('f=on') > 0);
    showi = (params.indexOf('i=on') > 0);
    shown = (params.indexOf('n=on') > 0);
    showp = (params.indexOf('p=on') > 0);
    if (!showf && !showi && !shown && !showp) { // No filter
      showf = true;
      showi = true;
      shown = true;
      showp = true;
    }
  } else if (self.location.hash) { // SlideShowPro parameters
    large = true;
    if (self.location.hash.indexOf('id=recent.ru') > 0) {
      russian = true;
    } else if (self.location.hash.indexOf('id=family.en') > 0) {
      showf = true;  showi = false; shown = false; showp = false;
    } else if (self.location.hash.indexOf('id=family.ru') > 0) {
      russian = true;
      showf = true;  showi = false; shown = false; showp = false;
    } else if (self.location.hash.indexOf('id=flying.en') > 0) {
      showf = false; showi = true;  shown = false; showp = false;
    } else if (self.location.hash.indexOf('id=flying.ru') > 0) {
      russian = true;
      showf = false; showi = true;  shown = false; showp = false;
    } else if (self.location.hash.indexOf('id=nature.en') > 0) {
      showf = false; showi = false; shown = true;  showp = false;
    } else if (self.location.hash.indexOf('id=nature.ru') > 0) {
      russian = true;
      showf = false; showi = false; shown = true;  showp = false;
    } else if (self.location.hash.indexOf('id=places.en') > 0) {
      showf = false; showi = false; shown = false; showp = true;
    } else if (self.location.hash.indexOf('id=places.ru') > 0) {
      russian = true;
      showf = false; showi = false; shown = false; showp = true;
    }
  }

  // Decide how many images will fit on screen
  var cols; // Number of zigzag columns of images
  cols = Math.floor(getBrowserWindowWidth() / (large ? (640*2.3) : (160*2.3)));
  if (cols < 1) {
    cols = 1;
  }
  var per_col; // Number of images per column
  per_col = Math.floor(getBrowserWindowHeight() / (large ? 640 : 160));
  if (per_col < (large ? 1 : 3)) {
    per_col = (large ? 1 : 3);
  }
  var per_page = cols * per_col;

  // Split imageset[] into a_*[] arrays, filtering along the way
  var img_total = 0;
  var a_category = new Array;
  var a_filename = new Array;
  var a_width    = new Array;
  var a_height   = new Array;
  var a_exif     = new Array;
  var a_russian  = new Array;
  var a_english  = new Array;
  var a_altfile  = new Array;
  for (var i = 0; i < imageset.length; i += 10) {
    if ( (showf && imageset[i] == 'f')
      || (showi && imageset[i] == 'i')
      || (shown && imageset[i] == 'n')
      || (showp && imageset[i] == 'p')
      || (imageset[i] == ' ' && showf && showi && shown && showp)
       ) {
      a_category[img_total] = imageset[i];
      a_filename[img_total] = imageset[i + 1];
      a_width   [img_total] = imageset[i + 2];
      a_height  [img_total] = imageset[i + 3];
      a_exif    [img_total] = imageset[i + 4];
      a_russian [img_total] = imageset[i + 5];
      a_english [img_total] = imageset[i + 6];
      if (imageset[i + 7]) {
        a_russian[img_total] += '<BR><FONT size=-1><I><A HREF="http://maps.google.com/maps?q=' + imageset[i + 7] + '+' + imageset[i + 8] + '&amp;z=16">Карта</A></I></FONT>';
        a_english[img_total] += '<BR><FONT size=-1><I><A HREF="http://maps.google.com/maps?q=' + imageset[i + 7] + '+' + imageset[i + 8] + '&amp;z=16">Map</A></I></FONT>';
      } 
      a_altfile [img_total] = imageset[i + 9];
      if (a_altfile[img_total]) {
        a_over_img[img_total] = new Image();
        a_out_img[img_total] = new Image();
        if (large) {
           a_over_img[img_total].src = 'medium/' + a_altfile[img_total]; 
           a_out_img[img_total].src= 'medium/' + a_filename[img_total];
         } else {
           a_over_img[img_total].src = 'small/' + a_altfile[img_total]; 
           a_out_img[img_total].src= 'small/' + a_filename[img_total];
         }
      }
      // Addressing specific photo by file name
      if ( params.indexOf(a_filename[img_total]) > 0
        || self.location.hash.indexOf(a_filename[img_total]) > 0
         ) {
        firstimg = img_total;
      }
      ++img_total;
    }
  }
  firstimg = Math.floor(firstimg / per_page) * per_page;
  if (firstimg > img_total - 1) {     
    firstimg = img_total - 1;          
    if (firstimg < 0) {
      firstimg = 0;
    }
  }

  // Now ready to generate HTML
  var o = '<CENTER>';

  // Navigation bar
  o += '<TABLE border="0" width="100%"><TR valign="top"><TD align="left" width="25%">';
  if (russian) {
    o += '<A HREF="'+ makeURL(baseurl, false, large, a_filename[firstimg], showf, showi, shown, showp, a_category[firstimg]) + '">English</A>';
  } else {
    o += '<A HREF="'+ makeURL(baseurl, true, large, a_filename[firstimg], showf, showi, shown, showp, a_category[firstimg]) + '">По-русски</A>';
  }
  o += '&nbsp;&nbsp;&nbsp;';
  if (img_total > per_page) {
    if (firstimg > 0) {
      o += '<A HREF="' + makeURL(baseurl, russian, large, a_filename[(firstimg > per_page) ? firstimg - per_page : 0],
        showf, showi, shown, showp, a_category[(firstimg > per_page) ? firstimg - per_page : 0]) + '">' + '&laquo;' + (russian ? 'позже' : 'later') + '</A> ';
    }
    o += '</TD><TD align="center">';
    var imax = Math.floor((img_total + per_page - 1) / per_page);
    var ellipsis_shown = false;
    for (i = 0; i < imax; ++i) {
      var dist = Math.floor(firstimg / per_page) - i;
      if (dist < 0) {
        dist = -dist; 
      }
      if ( firstimg >= i * per_page 
        && firstimg <  (i + 1) * per_page
         ) {
        o += '<B>[' + (imax - i) + ']</B> ';
        ellipsis_shown = false;
      } else {
        if ( imax > 10
          && i !== 0
          && i !== imax - 1
          && dist >  3
          && dist !== 7
          && dist !== 15
          && dist !== 31
          && dist !== 63
          && dist !== 127
          && dist !== 255
           ) {
          if (!ellipsis_shown) {
            ellipsis_shown = true;
            o += " ... ";
          }
        } else {
          o += '<A HREF="' + makeURL(baseurl, russian, large, a_filename[i * per_page], showf, showi, shown, showp, a_category[i * per_page]) + '">' + (imax - i) + '</A> ';
          ellipsis_shown = false;
        }
      }
    }
    o += '</TD><TD align="right" width="25%">';
    if (firstimg + per_page < img_total) {
      o += '<A HREF="' + makeURL(baseurl, russian, large, a_filename[firstimg + per_page], showf, showi, shown, showp, a_category[firstimg + per_page]) + '">' + (russian ? 'раньше' : 'earlier') + '&raquo;</A>';
    }
  } else {
    o += '</TD><TD align="right">';
  }
  var img_min = firstimg;
  var img_max = firstimg + per_page - 1;
  if (img_max > img_total - 1) {
    img_max = img_total - 1;
  }
  o += '&nbsp;&nbsp;&nbsp;';
  if (large) {
    o += '<A HREF="'+ makeURL(baseurl, russian, false, a_filename[firstimg], showf, showi, shown, showp, a_category[firstimg]);
    o += russian ? '">мелко</A>' : '">small</A>&nbsp;';
  } else {
    o += '<A HREF="'+ makeURL(baseurl, russian, true, a_filename[firstimg], showf, showi, shown, showp, a_category[firstimg]);
    o += '">' + (russian ? 'крупно' : 'large') + '</A>';
  }
  o += '</TD></TR></TABLE>';

  // Main table
  if (img_total === 0) {
    if (russian) {
      o += '<P>Нет фотографий, соответствующих выбранным критериям фильтра.';
    } else {
      o += '<P>No images match filter condition.';
    }
  }
  o += '<P><TABLE BORDER="0" WIDTH="100%"><TR>';
  for (var j = 0; j < cols; ++j)
  {
    o += '<TD VALIGN=top ALIGN=center WIDTH="' + (100/cols) + '%">';
    // One picture cell start
    o += '<TABLE BORDER="0">';
    var isleft = true;

    for ( i = (img_min + j * per_col)
        ; (i <= img_max) && (i < (img_min + (j + 1) * per_col))
        ; ++i
        )
    {
      o += '<TR>';
      var align;
      if (isleft) {
        align = 'right';
      } else {
        align = 'left';
      }
      // image cell
      o += '<TD rowspan=3 ALIGN=' + align + '>';
      if (large) {
        // Can't put the border around large photo because don't know its size
        o += '<IMG src="medium/' + a_filename[i] + '" alt="' + a_exif[i] + '" border=0 ';
        if (a_altfile[i]) {
          o += 'name=img' + i + ' '
             + 'onMouseOver="if (document.images) document.img' + i + '.src=a_over_img[' + i + '].src; return true;" ' 
             + 'onMouseOut="if (document.images) document.img' + i + '.src=a_out_img[' + i + '].src; return true;" ';
        }
        o += '>';
      } else {
        o += 
        '<TABLE border=0 cellpadding=0 cellspacing=0>' +
        '<TR><TD rowspan=2 colspan=2>' + 
        '<A href="' + makeURL(baseurl, russian, true, a_filename[i], showf, showi, shown, showp, a_category[i]) + '" title="' + a_exif[i] + '">' +
        '<IMG src="small/' + a_filename[i] + 
        '" alt="' + a_exif[i] + '" width=' + a_width[i] + ' height=' + 
        a_height[i] + ' border=0 ';
        if (a_altfile[i]) {
          o += 'name=img' + i + ' '
             + 'onMouseOver="if (document.images) document.img' + i + '.src=a_over_img[' + i + '].src; return true;" ' 
             + 'onMouseOut="if (document.images) document.img' + i + '.src=a_out_img[' + i + '].src; return true;" ';
        }
        o += '></A>' +
        '</TD><TD><IMG alt="" src="i/rt.png" width=8 height=8 '+
        'border=0></TD></TR><TR><TD><IMG alt="" src="i/r.png" width=8 height=' + 
        (a_height[i] - 8) + ' border=0></TD></TR><TR><TD><IMG alt="" ' + 
        'src="i/lb.png" width=8 height=8 border=0></TD><TD><IMG alt="" ' + 
        'src="i/b.png" width=' + (a_width[i] - 8) + 
        ' height=8 border=0></TD><TD><IMG alt="" src="i/rb.png" width=8 ' + 
        'height=8 border=0></TD></TR></TABLE>';
      }
      o += '</TD>';
      if (i === (img_min + j * per_col)) {
        o += '<TD></TD>';
      }
      o += '</TR>';
      o += '<TR>';
      // text cell
      var s = getDateByImageName(a_filename[i]);
      if (isleft) {
        align = 'left';
        s = '<IMG alt="" src="i/arrowleft.png" width=19 height=13 border=0>&nbsp;' + s;
      } else {
        align = 'right';
        s = s + '&nbsp;<IMG alt="" src="i/arrowright.png" width=19 height=13 border=0>';
      }
      o += '<TD ALIGN=' + align + '><TT><B><FONT color="#008000">' + s + 
        '</FONT></B></TT><BR>' + ((russian && (a_russian[i].length > 0)) ? a_russian[i] : a_english[i]);
      if (large) {
        o += '<BR><FONT color="#808080">' + a_exif[i] + '</FONT>';
      }
      o += '</TD></TR>';
      if ((i === img_max) || (i === ((img_min + (j + 1) * per_col) - 1))) {
        o += '<TR><TD></TD></TR>';
      }
      isleft = !isleft;
    }
    o += '</TABLE>';
    // One picture cell end
    o += '</TD>';
  }
  o += '</TR></TABLE>';

  // Another table at the bottom to hold grayscale bar and filter form
  o += '<P><TABLE border="0" width="100%"><TR><TD>';

  // grayscale bar and its helper function
  function hexgray(x) {
    var s = x.toString(16);
    if (s.length === 1) {
      s = '0' + s;
    }
    return s + s + s;
  }
  var steps = 10;
  o += '<P><TABLE border="0" cellpadding="1" cellspacing="0" bgcolor="black">';
  o += '<TR><TD>';
  o += '<TABLE border="0" cellpadding="0" cellspacing="0">';
  o += '<TR align=center valign=middle>';
  for (i = 0; i <= steps; ++i) {
    o += '<TD width="' + Math.floor(100 / (steps + 1)) + '%" bgcolor="#' + 
      hexgray(Math.floor(i * 255 / steps)) + '"><TT><FONT color="' + 
      (i > steps / 2 ? 'black' : 'white') + '">' +  
      Math.floor(i * 100 / steps) + '%' + 
      '</FONT></TT></TD>';
  }
  o += '</TR></TABLE>';
  o += '</TD></TR></TABLE>';
  // end of grayscale bar

  o += '</TD><TD align="right">';

  // Filter
  o += '<FORM action=' + baseurl + ' method="get">';
  o += '<INPUT type="hidden" name="num" value=' + a_filename[firstimg] + '>';
  o += '<INPUT type="hidden" name="id" value=' + getAlbum(a_category[firstimg], russian) + '>';

  if (russian) {
    o += '<INPUT type="hidden" name="r" value="y">';
  }
  if (large) {
    o += '<INPUT type="hidden" name="l" value="y">';
  }

  o += '<INPUT type="checkbox" name="f" ' + (showf ? 'checked' : '' ) + '>';
  o += (russian ? '<ACRONYM title="Семья"><A href="family.ru.html">7я</A></ACRONYM>' : '<A href="family.en.html">Family</A>') + '&nbsp; ';

  o += '<INPUT type="checkbox" name="i" ' + (showi ? 'checked' : '' ) + '>';
  o += (russian ? '<ACRONYM title="Опознанные летающие объекты"><A href="flying.ru.html">ОЛО</A></ACRONYM>' : '<ACRONYM title="Identified Flying Object"><A href="flying.en.html">IFO</A></ACRONYM>s') + '&nbsp; ';

  o += '<INPUT type="checkbox" name="n" ' + (shown ? 'checked' : '' ) + '>';
  o += (russian ? '<A href="nature.ru.html">Живность</A>' : '<A href="nature.en.html">Nature<A>') + '&nbsp; ';

  o += '<INPUT type="checkbox" name="p" ' + (showp ? 'checked' : '' ) + '>';
  o += (russian ? '<A href="places.ru.html">Места</A>' : '<A href="places.en.html">Places</A>') + '&nbsp; ';

  o += '<INPUT type="submit" value=' + (russian ? '"Фильтр"' : '"Filter"') + '>';
  o += '</FORM>';

  o += '</TD></TR></TABLE>';
  
  o += '</CENTER>';

  return o;
}
