// This code relies heavily on the images within one posting all
// being the same size. This is a quick hack, hope it works across
// browsers.

// This code takes all images with the same ID (which is in general
// not in compliance with normal HTML practices), removes all but the
// first images and replaces the first with a two-row table; row one
// includes the first image, original size; row two includes clickable
// thumbnails of all images.

// The normal IMG tags should all apply: TITLE, ALT, BORDER, STYLE,
// CLASS, ... are all maintained in both the large and thumbnail
// versions (size are obviously changed for the thumbnail). In fact,
// "transferStyles" is a variable that contains some attributes that
// will be transferred to the containing TABLE; for instance, if
// 'style' contains 'float: right;' then it will be correctly applied.

// It should be "browser-neutral" but it hasn't been tested much.
// Good luck!

if (! document.nativeGetElementById) {
    // No need to continue if I've already done this getElementById *hack*
    // elsewhere and (re)loaded it unnecessarily

    // Use browser sniffing to determine if IE or Opera (ugly, but required)
    var isOpera, isIE = false;
    if(typeof(window.opera) != 'undefined'){isOpera = true;}
    if(!isOpera && navigator.userAgent.indexOf('Internet Explorer')){isIE = true;}

    //fix both IE and Opera (adjust when they implement this method properly)
    if(isOpera || isIE){
        document.nativeGetElementById = document.getElementById;
        //redefine it!
        document.getElementById = function(id){
            var elem = document.nativeGetElementById(id);
            if(elem){
                //verify it is a valid match!
                if(elem.attributes['id'] && elem.attributes['id'].value == id){
                    //valid match!
                    return elem;
                } else {
                    //not a valid match!
                    //the non-standard, document.all array has keys for all name'd, and id'd elements
                    //start at one, because we know the first match, is wrong!
                    for(var i=1;i<document.all[id].length;i++){
                        if(document.all[id][i].attributes['id'] && document.all[id][i].attributes['id'].value == id){
                            return document.all[id][i];
                        }
                    }
                }
            }
            return null;
        };
    }
}

var IMAGESIZEREDUCTION = 7;
var transferStyles = [ 'style', 'align', 'class' ];

var images = [];

function combineImages() {
    node = document;

    var allImages = node.getElementsByTagName('img');

    for (var i=0; i < allImages.length; i++) {
        id = allImages[i].getAttribute('id');
        if (id) {
            var found = false;
            for (var j=0; j < images.length; j++) {
                if (images[j][0] == id) {
                    images[j].push(allImages[i]);
                    found = true;
                    break;
                }
            }
            if (! found) {
                images.push([]);
                images[images.length - 1].push(id);
                images[images.length - 1].push(allImages[i]);
            }
        }
    }

    for (var i=0; i < images.length; i++) {
        if (images[i].length > 2) {
            var id = images[i][0];

            //---------------------------------
            // replace first image with table+image
            //---------------------------------

            // create table
            var tbl = document.createElement('table');
            tbl.setAttribute('id', id + '-table');

            // THIS DOESN'T WORK YET
            //for (var j=0; j < images[i][1].attributes; j++) {
            //    tbl.setAttribute(images[i][1].attributes[j].nodeName, images[i][1].attributes[j].nodeValue);
            //}

            for (var j=0; j < transferStyles.length; j++) {
                if (images[i][1].hasAttribute(transferStyles[j])) {
                    tbl.setAttribute(transferStyles[j], images[i][1].getAttribute(transferStyles[j]));
                }
            }

            var tblBody = document.createElement('tbody');
            var imgRow = document.createElement('tr');
            var imgCell = document.createElement('td');
            var newImage = images[i][1].cloneNode(true);
            imgCell.appendChild(newImage);
            imgRow.appendChild(imgCell);
            tblBody.appendChild(imgRow);

            var thumbRow = document.createElement('tr');
            var thumbCell = document.createElement('td');
            thumbCell.setAttribute('align', 'center');
            thumbRow.appendChild(thumbCell);
            tblBody.appendChild(thumbRow);

            tbl.appendChild(tblBody);

            images[i][1].parentNode.replaceChild(tbl, images[i][1]);

            var width = Math.floor(images[i][1].width / IMAGESIZEREDUCTION);
            var height = Math.floor(images[i][1].height / IMAGESIZEREDUCTION);

            for (var j=1; j < images[i].length; j++) {
                var newAnchor = document.createElement('a');
                newAnchor.setAttribute('href', images[i][j].src);
                newAnchor.setAttribute('onclick',
                                       'document.getElementById("' + images[i][0] + '").src="' + images[i][j].src + '"; '
                                       + 'document.getElementById("' + images[i][0] + '").setAttribute("title","'
                                       + images[i][j].getAttribute('title') + '");'
                                       + 'return(false);');

                var newImage = images[i][j].cloneNode(true);
                newImage.width = width;
                newImage.height = height;

                // I have to remove the 'style' attribute so I can
                // align and format it as needed to fit in thumbCell.
                newImage.removeAttribute('style');

                newAnchor.appendChild(newImage);
                thumbCell.appendChild(newAnchor);
                thumbCell.appendChild(document.createTextNode(' '));

                if (j > 1) {
                    images[i][j].parentNode.removeChild(images[i][j]);
                }

                if ( (j % (IMAGESIZEREDUCTION - 1)) == 0 ) {
                    thumbCell.appendChild(document.createElement('br'));
                }
            }
        }
    }
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      if (oldonload) {
        oldonload();
      }
      func();
    }
  }
}

addLoadEvent(combineImages);

