
function addEvListener(targ,type,func) {
  if(document.addEventListener) {   // gecko
    targ.addEventListener(type,func,false);
  } else if(document.attachEvent) { // IE
    targ.attachEvent('on'+type,func);
  } else { // ?
    targ['on'+type] = func;
  }
}


function Albumstar(debugDivId,imageDivId,thumbsDivId,titleDivId){
  this.debugDivId  = debugDivId;
  this.imageDivId  = imageDivId;
  this.thumbsDivId = thumbsDivId;
  this.titleDivId  = titleDivId;
  this.d = false;
  this.asr = false;
  this.info = false;
  this.albumTitle = '';
  this.current_n = 0;

  this.debug = function(s) {
    var as = this;
    if(!this.d) { this.d = document.getElementById(as.debugDivId); }
    s = s.replace(/\n/g,"<br />\n");
    this.d.innerHTML += s;
  };

  this.actOnURL = function() {
    var as = this;
    var req_n;
    var h = window.location.hash;
    if(h) {
      as.debug("came with hash "+h+"\n");
      if(h.substring(0,1) == '#') {
        req_n = parseInt(h.substring(1));
      } else {
        req_n = parseInt(h);
      }
    }
    if(req_n > 0 && req_n <= as.numImages()) {
      as.showImage(req_n,"beats me");
    } else {
      as.showThumbs();
    }
  };

  this.numImages = function() {
    var as = this;
    return as.info ? as.info.length : 0;
  };

  this.setInfo = function(info,title) {
    var as = this;
    as.info = info;
    as.albumTitle = title;

    var as_title = document.getElementById(as.titleDivId);
    as_title.innerHTML = title;
    document.title = as.albumTitle;

    var n = as.info.length;
    as.debug("There are "+n+" images.\n");

    var theThumbDiv = document.getElementById(as.thumbsDivId);
    for(var i=0; i<n; i++) {
      as.debug(i+"\n");
      var thisPic = as.info[i];

      var versions = thisPic.versions;
      var j;
      var thumb = false;
      var thumbUrl = '';
      for(j=0; !thumb && j < versions.length; j++) {
	var v = versions[j];
	if( v.size == "thumb" ) {
	  thumb = v;
	  thumbUrl = thumb.path;
	  break;
	}
      }

      var newThumb = document.createElement("a");
      newThumb.className="as_thumb";
      newThumb.style.backgroundImage="url("+thumbUrl+")";
      newThumb.href="#"+(i+1);
      newThumb.onclick=(function(i){ return function(){as.showImage(i)} })(i+1);
      newThumb.title=thisPic.comment;
      //newThumb.appendChild(document.createTextNode("banana phone"));
      theThumbDiv.appendChild(newThumb);
      as.debug("appended thumb "+(i+1)+".\n");
    }
  };

  this._show_snap = function() {
    var as = this;
    var div = document.getElementById(as.imageDivId);
    div.style.display = 'block';
    return;
  };

  this._show_thumbs = function() {
    var as = this;
    var div = document.getElementById(as.thumbsDivId);
    div.style.display = 'block';
    return;
  };

  this._hide_snap = function() {
    var as = this;
    var div = document.getElementById(as.imageDivId);
    div.style.display = 'none';
    return;
  };

  this._hide_thumbs = function() {
    var as = this;
    var div = document.getElementById(as.thumbsDivId);
    div.style.display = 'none';
    return;
  };

  this._show_debug = function() {
    var as = this;
    var div = document.getElementById(as.debugDivId);
    div.style.display = 'block';
    return;
  };

  this._hide_debug = function() {
    var as = this;
    var div = document.getElementById(as.debugDivId);
    div.style.display = 'none';
    return;
  };

  this.pagePrev = function() {
    var as = this;
    as.debug("Page prev.\n");
    as.showImage(as.current_n - 1);
    return;
  };

  this.pageNext = function() {
    var as = this;
    as.debug("Page next.\n");
    as.showImage(as.current_n + 1);
    return;
  };

  this.showThumbs = function() {
    var as = this;
    as.debug("Back to thumbnail page.\n");
    if(as.asr) {
      as.asr.noAutoResize();
      as.asr = undefined;
    }
    as._hide_snap();
    as._show_thumbs();
    document.title = as.albumTitle;
    window.location.hash = '#'; // '' seems to cause looping...
  };

  this.showImage = function(n,url) {
    var as = this;
    as.debug("Thumb click: "+n+".\n");

    var thisPic = as.info[n-1];
    if( ! thisPic ) {
      as.debug("No image "+n+".\n");
      return;
    }

    as.debug("showing image "+n+" at "+url+"\n");

    // if there's an old resizer active, get rid of it.
    if(as.asr) {
      as.asr.noAutoResize();
      as.asr = undefined;
    }

    as._hide_thumbs();
    as._show_snap();

    // update the location and current_n
    document.title = as.albumTitle+': '+thisPic.comment;
    window.location.hash = n;
    as.current_n = n;


// {item:1
//  comment:"is110a: 2003-europe"
//  source:"s110/full/2003-europe-0001.jpeg"
//  versions:[{x:160
//             y:120
//             size:"thumb"
//             path:"s110/thumb/thumb_2003-europe-0001.jpeg"
//             uuid:"fc592446-ab01-4ccb-ab25-348030cc6545"}
//            {x:800
//             y:600
//             size:"midsize"
//             path:"s110/midsize/2003-europe-0001.jpeg"
//             uuid:"2bcfcab8-5973-4ee4-885b-c0c652dcf789"}
//            {x:1600
//             y:1200
//             size:"original"
//             path:"s110/full/2003-europe-0001.jpeg"
//             uuid:"4e8eea7b-6d80-4485-91e7-cd8683781f11"}
//           ]
//  exif:{date:"2003/11/23 @ 08:15:08"
//        ydim:"1200"
//        model:"Canon PowerShot S110"
//        aperture:"f/2.8"
//        xdim:"1600"
//        shutter:"1/9 sec."
//        focallen:"5.4 mm"
//        iso:""
//        flash:"No"
//       }
// }


  //var full_blurb = document.getElementById('full_blurb');
  //full_blurb.innerHTML = '<span style="color: red;">Yo!</span>';
  //full_blurb.innerHTML = "Something at called '"+thisPic.comment+"', i guess...";
    as.debug("Something called '"+thisPic.comment+"', i guess...\n");


    var as_caption   = document.getElementById("as_caption");
    var as_date      = document.getElementById("as_date");
    var as_settings  = document.getElementById("as_settings");
    var as_copyright = document.getElementById("as_copyright");

    as_caption.innerHTML   = thisPic.comment;
    as_date.innerHTML      = thisPic.exif.date;
    as_settings.innerHTML  = thisPic.exif.model+" &mdash; "+thisPic.exif.shutter+" @ "+thisPic.exif.aperture;
    as_copyright.innerHTML = "&copy; Robert Parker Starling";

    //var xbuf =  50;
    //var ybuf = 150;
    var xbuf =  50;
    var ybuf = 200;
    var imgSet = new Array();


    var versions = thisPic.versions;
    var ZZversions = [
    {x:160,  y:107,  path:"test_images/img_3291_touch_160x107.jpg",   size:0 },
    {x:375,  y:250,  path:"test_images/img_3291_touch_375x250.jpg",   size:1 },
    {x:750,  y:500,  path:"test_images/img_3291_touch_750x500.jpg",   size:2 },
    {x:1500, y:1000, path:"test_images/img_3291_touch_1500x1000.jpg", size:3 },
    {x:3291, y:2125, path:"test_images/img_3291_touch_3178x2125.jpg", size:4 }
    ];


    var i;
    for(i=0; i < versions.length; i++) {
      var v = versions[i];
      imgSet.push(
        { x: v.x,
          y: v.y,
          //src: "asx-hack.cgi/2003-europe/_i/"+v.uuid
          src: v.path
        }
      );
      as.debug("for image "+n+", found version '"+v.size+"'\n");
    }

    as.asr = new as_Autoresizer(as,'as_theImage',xbuf,ybuf,imgSet);
    as.asr.autoResize();
  };
}

function as_Autoresizer(astar,imgId,xbuf,ybuf,imgSet){
  this.imgSet = imgSet;
  this.imgId = imgId;

  this.imgAspect=1;
  this.cur=0;

  this.xbuf=xbuf;
  this.ybuf=ybuf;

  this.resizeDirty=1;
  this.upresDirty=1;

  this.imResize = function() {
    var as = this;

    if( as.resizeDirty || as.upresDirty ) {

      astar.debug("<hr />");
      if( as.resizeDirty ) { astar.debug("resizeDirty"); }
      if( as.upresDirty  ) { astar.debug("upresDirty");  }

      as.resizeDirty = 0;  // clear the resize bit.

      var wx;
      var wy;
      var st = document.getElementById('as_st');
      if( 0 ) {
      } else if( window.innerWidth ) {
        wx = window.innerWidth;   // Moz
        wy = window.innerHeight;  // Moz
        astar.debug('window.inner{Width,Height} = {'+wx+','+wy+'}');
      } else if( document.documentElement &&
                 ( document.documentElement.clientWidth ||
                   document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        wx = document.documentElement.clientWidth;
        wy = document.documentElement.clientHeight;
        astar.debug('document.documentElement.client{Width,Height} = {'+wx+','+wy+'}');
      } else if( document.body &&
                 (document.body.clientWidth || document.body.clientHeight) ) {
        wx = document.body.clientWidth;    // IE
        wy = document.body.clientHeight;   // IE
        astar.debug('document.body.client{Width,Height} = {'+wx+','+wy+'}');
      } else {
        astar.debug('huh?');
        return;  // who knows.
      }
      wx -= this.xbuf;  // avail x for image
      wy -= this.ybuf;  // avail y for image
      var wa = wy / wx;
      var ix = wx;
      if( wa > this.imgAspect ) {
        //astar.debug(wx+'x'+wy+' ('+wa+') is taller than the image ('+this.imgAspect+')');
        ix = wx;
      } else {
        //astar.debug(wx+'x'+wy+' ('+wa+') is wider than the image ('+this.imgAspect+')');
        ix = wy / this.imgAspect;
      }
      var div = document.getElementById('as_snap');
      //alert('(before) snap is '+div);
      //alert('(before) snap.style is '+div.style);
      //alert('(before) snap.style.width is '+div.style.width);
      div.style.width  = ix+'px';
      div.style.height = 'auto';
      //alert('(after) snap is '+div);
      //alert('(after) snap.style is '+div.style);
      //alert('(after) snap.style.width is '+div.style.width);
      astar.debug('snap.style.{width,height} = {'+div.style.width+','+div.style.height+'}');

      var img = document.getElementById(this.imgId);

      // if the horiz space available is wider than the current image and
      // there are more (higher-res) images available,
      var xspace = ix-this.xbuf;
      if( xspace>this.imgSet[this.cur].x &&
          this.cur<this.imgSet.length-1 )
      {
        //astar.debug("xspace "+xspace+" > img.x "+this.imgSet[this.cur].x);
        this.upresDirty = 1;  // turn this on until that condition is false.

        // then either upgrade, or start the next-better image loading
        for(var i=this.cur+1; i<this.imgSet.length; i++) {

          var ix = this.imgSet[i].x;
          var iy = this.imgSet[i].y;

          // if the next image has been started,
          if( this.imgSet[i].image != null ) {

            // if it's done loading, swap it in
            if( this.imgSet[i].image.complete ) {
              astar.debug("img "+i+" ("+ix+"x"+iy+") finished loading");
              //// .width and .height don't seem to exist in Safari or Mac IE
              ////if( this.imgSet[i].image.width != ix ) {
              ////    alert('image "'+this.imgSet[i].src+'" width is '+this.imgSet[i].image.width+' rather than the expected '+ix);
              ////}
              ////if( this.imgSet[i].image.height != iy ) {
              ////    alert('image "'+this.imgSet[i].src+'" height is '+this.imgSet[i].image.height+' rather than the expected '+iy);
              ////}
              this.imgAspect = iy / ix;
              img.src=this.imgSet[i].src;
              this.cur=i;
              //alert('using '+img.src);
              st.innerHTML='';
              window.defaultStatus='';
              break;
            } else {
              astar.debug("waiting for img "+i);
              break;
            }

          // start loading the next image
          } else {
            var im = new Image();
            im.src = this.imgSet[i].src;
            this.imgSet[i].image = im;
            astar.debug("loading img "+i+" ("+ix+"x"+iy+") in the background to fill "+xspace+" xspace.");
            st.innerHTML='loading higher-res image in the background...';
            window.defaultStatus='loading higher-res image in the background...';
            break;  // give it one more timer loop before pre-loading another
          }
        }
      } else {
        this.upresDirty = 0;  // we can rest until the user resizes
      }
    }

    if(as.wantAutoResize) {
      //window.setTimeout( function(){as.imResize()}, 200 );
      //window.setTimeout( "if(as){as.imResize()}", 200 );
      window.setTimeout( function(){if(as){as.imResize()}}, 200 );
    }
  };

  this.imResizeMark = function() {
    this.resizeDirty = 1;  // set the bit.
  };

  this.autoResize = function() {
    var as = this;
    as.wantAutoResize = true;
    window.onresize=function(){if(as){as.imResizeMark();}};
    //window.setTimeout( "if(as){as.imResize();}", 200 );
    window.setTimeout( function(){if(as){as.imResize()}}, 200 );
  };

  this.noAutoResize = function() {
    var as = this;
    as.wantAutoResize = false;
  };

  var i = document.getElementById(this.imgId);
  i.src     = this.imgSet[0].src;
  this.imgAspect = this.imgSet[0].y / this.imgSet[0].x;
}


