var ImgShrink = {
  shrinkChildImages: function(element) {
    ImgShrink.shrinkChildImagesEx(element, "IMG");
  },
  shrinkChildIframes: function(element) {
    ImgShrink.shrinkChildImagesEx(element, "IFRAME");
  },
  shrinkChildImagesEx: function(element, tagname) {
    imgs = element.getElementsByTagName(tagname);
    var min_width = [ 100, 200, 400 ];
    var i_factor = 0.707106;
    var i, j;
    for (i = 0; i < imgs.length; i++) { 
      img = imgs[i];
      factor = 1;
      for (j = 0; img.width > min_width[j] && j < min_width.length; j++) {
        factor *= i_factor;
      }
      if (factor < 1) {
        w = img.width;
        h = img.height;
        img.width = Math.round(w * factor);
        img.height = Math.round(h * factor);
      }
      img.style.position = "relative";
      img.style.visibility = "visible";
    }
  },

  shrinkAllImages: function() {
    entry_id = "content";
    class_name = "textblock small";

    el = document.getElementById(entry_id);
    if (el) {
      DocGen.forEachClassName(el, class_name,
        ImgShrink.shrinkChildImages);
      DocGen.forEachClassName(el, class_name,
        ImgShrink.shrinkChildIframes);
    }
  },

  register: function() {
    DocGen.doOnLoad(ImgShrink.shrinkAllImages);
  }
}

var TextBlockResize = {
  equalColumns: function() {
    class_name = "textblock small";
    spacer_class_name = "text-entry-separator col";
    cols = document.getElementsByClassName(class_name);
    var ncols = cols.length;
    var i;
    var colheight = new Array();
    var nentries = new Array();
    var maxheight, colmax;
    colmax = 0;
    maxheight = 0;
    for (i = 0; i < ncols; i++) {
      colheight[i] = cols[i].clientHeight;
      if (colheight[i] > maxheight) {
        maxheight = colheight[i];
        colmax = i;
      }
      ce = cols[i].getElementsByClassName("text-entry");
      if (ce) nentries[i] = ce.length; else nentries[i] = 0;
    }
    var coldiff = new Array();
    for (i = 0; i < ncols; i++) {
      coldiff[i] = maxheight - colheight[i];
    }
    for (i = 0; i < ncols; i++) {
      spacer_class = spacer_class_name + (i + 1);
      spacers = cols[i].getElementsByClassName(spacer_class);
      if (spacers) {
        h = coldiff[i] / (nentries[i] - 1);
        for (j = 0; j < spacers.length; j++)
          spacers[j].style.height = h + "px";
      }
    }
  },

  register: function() {
    DocGen.doOnLoad(TextBlockResize.equalColumns);
  }
}

ImgShrink.register();
TextBlockResize.register();

