var IAV = 
{
  // ----------------  STUFF FOR THE "FILMSTRIP" PART  --------------
  // maps IDENTIFIER to thumbnail #/seconds (we'll left 0-pad to the 6 digits...)
  MAP:{
"nightbay"                :[1,  "Night time-lapse of bustling SF bay -- music by Hunter!"],
"drake_saga1"             :[30, "The Drake Saga -- lightsabers!"],
"alc2008"                 :[1200,"AIDS LifeCycle 2008 -- biked SF to LA"],
"commute"                 :[15, "Time lapse of my commute across bay to work"],
"meteorocino"             :[1,  "Perseids Meteor Shower near Mendocino, CA"],

"bikeDiabloVideo"         :[60, "Spring bikedride up Mount Diablo (the Video)"],
"oldpresidio"             :[1,  "Walking through the antiqued Presidio"],
"TRL-2009"                :[30, "It's OK to be a Training Ride Leader"],
"dumpster"                :[1,  "dumpster diving for trashed video frames "],

"holiDVD"                 :[90, "Seasons Greetings 2008.  DVD loop video with stop motion"],
"inauguration2009"        :[330,"Hunter and I travel to D.C. to watch Obama's Inauguration"],
"ImLost"                  :[120,"Fun with the Lost TV show for my BFF kim's birthday"],
"ALC_stop_motion"         :[30, "AIDS LifeCycle -- stop motion daily intros"],

"CapeCodMarshClouds"      :[5,  "short time lapse of clouds moving over Cape Cod marsh"],
"MendocinoMeteorWeekend"  :[210,"Fun camping in the backcountry over a peak meteor weekend"],
"bikeDiablo"              :[65, "Spring bikeride up Mount Diablo (time lapse)"],

"Jessies_Sunrise"         :[20, "Early workday at Jessie St, SF (so I lapsed the sunrise 8-)"],
"briones_dusk"            :[5,  "Beautiful low clouds rushing over ridgeline in Briones park"],
"baysunset"               :[1,  "Low-light &amp; grainy quick clip of a breathtaking sunset"],
"helios-sunset"           :[1,  "Sunset at friend's land in Mendocino while camping"],

"TourOfCA"                :[30, "Time lapse of Tour of California race - Music by Hunter"],
"SFOsouth"                :[35, "Time lapse of sunny SFO flight to SoCal"],
"to-SF"                   :[30, "Earlier time lapse where I drive into SF"],
"from-SF"                 :[150,"Earlier time lapse where I drive home from a SF party"],
"archivewalk"             :[35, "Internet Archive takes a walk (time lapse)"],

"sunsetstrip"             :[1,  "Ultra widescreeen sunset short time lapse"],
"skyline-sunset"          :[5,  "My 2nd time lapse, at night overlooking SF bay from Skyline"],
"skyline-fireworks"       :[15, "Fireworks time lapse overlooking the SF bay from Skyline"],
"traceys-first-time-lapse":[1,  "2003 first scientific experiments with time lapsing"],

"rotoscope"               :[2,  "Tracey being a geek experimenting with lightsabers!"]

  },
  NO512S:["nightbay","alc2008","TRL-2009","dumpster","holiDVD",
          "inauguration2009","ImLost","ALC_stop_motion","skyline-fireworks"],
  WIDES:["nightbay","alc2008","meteorocino","oldpresidio","ImLost",
         "ALC_stop_motion","helios-sunset","sunsetstrip",
         "traceys-first-time-lapse","skyline-sunset","skyline-fireworks"],
  LAPSES:["nightbay","commute","meteorocino","CapeCodMarshClouds",
          "bikeDiablo","TourOfCA","Jessies_Sunrise","briones_dusk",
          "baysunset","helios-sunset","SFOsouth","to-SF","from-SF",
          "archivewalk","sunsetstrip","traceys-first-time-lapse",
          "skyline-sunset","skyline-fireworks"],

  HALF:'HALF',
  playerHeight:480 + 24, // ... + controller height
  filmstrip:null,
  

  //=========================================================================
  //
  //           CLIP EVENTS:
  //=========================================================================
  // [page start]  [0 can play]  [0 all loaded]  [1 can play]  [0 played] ...
  //=========================================================================
  //
  //           WHAT HAPPENS:
  //=========================================================================
  // load(0)         play(0)        load(2)                     hide(0)
  // load(1)           |               |                        show(1)
  //   |               |               |                        play(1)
  //   |               |               |                           |
  // --+---------------+---------------+---------------------------+----- ...
  //
  CLIPS:[
"http://www.archive.org/download/BraveNewFilmsFoxAttacksObama/foxattacksobama320_512kb.mp4?t=60.5/79",
"http://www.archive.org/download/SitaSingstheBlues_Trailer1/SitaTrailer1.2Sorensen_512kb.mp4?t=10/28",
"http://www.archive.org/download/dragostea_tin_dei_by_ozone/Dragostea_din_tei_By_Ozone_512kb.mp4?t=13/42",
"http://www.archive.org/download/allofthedead/allofthedead_fullscr_512kb.mp4?t=36/77",
"http://www.archive.org/download/Kinetic_Art_Demo_Video/nym_512kb.mp4?t=169/237.5",
"http://www.archive.org/download/StoreWars/sw_14M_512kb.mp4?t=46/104",
"http://www.archive.org/download/Political_Commercial/Political_Commercial_512kb.mp4?t=124.5/232",
"http://www.archive.org/download/inauguration2009/inauguration2009_512kb.mp4?t=220/239",
"http://www.archive.org/download/night_of_the_living_dead/night_of_the_living_dead_512kb.mp4?t=365/369",
"http://www.archive.org/download/alc7brownhunter/alc7brownhunter_512kb.mp4?t=137/153.5"
    ],
  
  IDS:[],
  FILES:[],
  QSTRINGS:[],
  v:[],
  playable:[],
  playing:false,
  playnext:0,
  nloading:0,

  playClips:function()
  {
    if (!document.getElementById('clips'))
      return;
    
    // newer browsers like FF 3.5+ and Safari 4+ can play the new <video> tag!
    // check for browsers that can handle the <video> tag natively...
    // (credit to J at v2v dot cc for this simpler JS detection technique!)
    var video = document.createElement('video');
    if (!video.play)
      return;

    for (var clip, i=0; clip=this.CLIPS[i]; i++)
    {
      clip = clip.replace(/http:\/\/www.archive.org\/download\//, '');
      var pcs = clip.split(/[\/\?]/);
      this.IDS[i] = pcs[0];
      this.FILES[i] = pcs[1].replace(/(_512kb.mp4|.ogv)$/, '');
      this.QSTRINGS[i] = ((pcs.length>2 ? '?'+pcs[2] : '') +
                          (pcs.length>3 ? '/'+pcs[3] : ''));
    }

    this.load(0);
    this.load(1);
  },

  load:function(idx)
  {
    var id=this.IDS[idx];
    this.log(id,' is loading');    
    this.nloading++;
    var v=document.createElement('video');
    v.autoload = true;
    v.style.position = 'absolute';
    v.style.top=0;
    v.style.left=0;
    v.width = 10;
    v.height = 10;
    v.autoplay = false;
    v.controls = false;
    v.innerHTML = '<source type="video/mp4" src="http://www.archive.org/download/'+id+'/'+this.FILES[idx]+'_512kb.mp4'+this.QSTRINGS[idx]+'"/><source type="video/ogg" src="http://www.archive.org/download/'+id+'/'+this.FILES[idx]+'.ogv'+this.QSTRINGS[idx]+'"/>';

    v.addEventListener("canplay", function() { IAV.canplay(idx); }, true);
    v.addEventListener("load",    function() { IAV.loaded(idx); }, true);
    v.addEventListener("ended",   function() { IAV.ended(idx); }, true);

    this.v[idx] = v;
    document.getElementById('clips').appendChild(v);
  },

  canplay:function(idx)
  {
    var id=this.IDS[idx];
    this.log(id, ' can start playback');
    if (!this.playing  &&  this.playnext == idx)
    {
      this.playing = true;
      this.playnext = idx + 1;
      this.v[idx].width = 640;
      this.v[idx].height = 480;
      this.v[idx].style.position = 'relative';
      
      this.v[idx].play();
      this.log(id, ' is playing');
    }
    else
    {
      if (this.playable[idx])  return; //xxx shouldnt need to do this?!
      this.playable[idx] = true;
      
      this.v[idx].currentTime=0;
      this.v[idx].play();
      this.v[idx].pause();
    }
  },

  loaded:function(idx)
  {
    var id=this.IDS[idx];
    this.log(id,' has been 100% downloaded');
    this.nloading--;
    
    if (this.nloading < 2  &&  idx+2 < this.IDS.length)
      this.load(idx+2);
  },

  ended:function(idx)
  {
    var id=this.IDS[idx];
    this.log(id,' has finished playback');
    this.v[idx].width = 10;
    this.v[idx].height = 10;
    this.v[idx].style.position = 'absolute';    
    this.playing = false;
    if (this.playable[idx+1])
      this.canplay(idx+1);
  },




  // (for video.htm and samples.htm only)
  playmp4:function(playern, identifier)
  {
    var plbuttons = 'false';
    var suffix = '_512kb';
    var width = 640;
    if (typeof(identifier)=='undefined'  ||  !identifier)
    {
      // means play all videos
      plbuttons = 'true';
      width = 800;
      var playlist = '';
      for (identifier in this.MAP)
      {
        if (this.omitClip(identifier))
          continue;
        
        suffix = '_512kb';
        for (var i=0,id; id=this.NO512S[i]; i++)
        {
          if(id==identifier)
          {
            suffix='';
            break;
          }
        }
        playlist += (playlist ? ',':'') +
          '"http://www.archive.org/download/'+identifier+'/'+identifier+suffix+
          '.mp4"';
      }
    }
    else
    {
      for(var i=0,id; id=this.NO512S[i]; i++) if(id==identifier){suffix='';break;}
      for(var i=0,id; id=this.WIDES[i] ; i++) if(id==identifier){width=800;break;}
      var playlist =
      '"http://www.archive.org/download/'+identifier+'/'+identifier+suffix+'.mp4"';
    }
    
    //this.log(playlist);
    
    // first hide all players
    for (var i=0, obj; obj=document.getElementById('player'+i); i++)
    {
      obj.innerHTML = ' ';
      obj.style.display = 'none';
    }

    // normally we want the player identified by our param.
    // however, for the last row
    var     t = document.getElementById('player'+(playern  ));
    if (!t) t = document.getElementById('player'+(playern-1));

    
    
      
    t.style.display = 'block';
    t.innerHTML = '\n\
 \n\
<embed type="application/x-shockwave-flash" width="'+width+'" height="'+this.playerHeight+'" \n\
    src="http://www.archive.org/flow/flowplayer.commercial-3.0.5.swf"  \n\
    allowfullscreen="true" allowscriptaccess="always" w3c="true" \n\
    flashvars=\'config={ \n                                            \
"key":"#$b6eb72a0f2f1e29f3d4", \n\
"playlist":[ \n\
'+playlist+'\n\
], \n\
"clip":{ \n\
  "autoBuffering":true, \n\
  "autoPlay":true, \n\
  "accelerated":true, \n\
  "scaling":"fit", \n\
  "provider":"h264streaming" \n\
}, \n\
"canvas":{ \n\
  "backgroundColor":"0x000000", \n\
  "backgroundGradient":"none" \n\
}, \n\
"plugins":{ \n\
  "h264streaming":{ \n\
    "url":"http://www.archive.org/flow/flowplayer.h264streaming-3.0.5.swf" \n \
  }, \n\
  "controls":{ \n\
    "playlist":'+plbuttons+', \n\
    "fullscreen":true, \n\
    "gloss":"high", \n\
    "backgroundColor":"0x000000", \n\
    "backgroundGradient":"medium", \n\
    "sliderColor":"0x777777", \n\
    "progressColor":"0x777777", \n\
    "timeColor":"0xeeeeee", \n\
    "durationColor":"0x01DAFF", \n\
    "buttonColor":"0x333333", \n\
    "buttonOverColor":"0x505050" \n\
  } \n\
}}\'> </embed>';
    //this.log(t.innerHTML);
    return false;
  },

  omitClip:function(identifier)
  {
    if (!this.LAPSES.length)
      return false;

    // means we are on page "samples.htm" and need to omit non time lapses
    for (var i=0,id; id=this.LAPSES[i] ; i++)
      if (id==identifier) return false; // not a timelapse video, omit
    return true;
  },

  filmstripSetup:function()
  {
    var str = '\n\
\n\
<div style="margin-top:-10px;  float:right;">\n\
  <a href="#" onclick="return IAV.playmp4(0)">Play all</a>\n\
</div>\n\
<center>\n\
  <div style="font-size:9pt; font-style:italic;">\n\
    <nobr>\n\
      mouse over an image to see more scenes -- click image to watch the full\n\
      video -- click text for more info/formats\n\
    <nobr>\n\
  </div>\n\
</center>\n\
<div>\n\
\n\
    ';
    var n=0;
    var playern=0;

    var usingplayer = location.href.match(/\/(video.htm|samples.htm)$/  );
    for (id in this.MAP)
    {
      if (this.omitClip(id))
        continue;
      
      var thumbn = this.MAP[id][0];
      var title  = this.MAP[id][1];
      var playerstr = '';
      if (usingplayer  &&  (n>0  &&  n % 4==0))
      {
        playerstr = '\n\n<br clear="left"/><center><div id="player'+playern+'"> </div></center>\n';
        playern++;
      }

      if (!this.HALF  ||  (n % 2 == 0))
        str += '</div>'+playerstr+"\n\n"+'<div class="strip'+this.HALF+'">';
      str += '<div title="click for more info" alt="click for more info" onclick="location.href=\'http://www.archive.org/details/'+id+'\'" class="rounded15 placard placard2'+this.HALF+((this.HALF && n % 2)?'b':'')+'">'+id+'</div>';

      // left 0-pad to 6 digits as needed
      var thumb = '000000' + thumbn;
      thumb = thumb.substr(thumb.length-6, 6);

      var onclik = (usingplayer ? 'href="#" onclick="return IAV.playmp4('+playern+',\''+id+'\')"' :
                    'href="http://www.archive.org/details/'+id+'"');
      
      str += '<a '+ onclik + '><img title="'+title+'" alt="'+title+'" id="'+id+'" onmouseover="IAV.imtoggle(\''+id+'\')" onmouseout="IAV.imtoggle(\''+id+'\')" class="cell'+this.HALF+'" src="http://www.archive.org/serve/'+id+'/'+id+'.thumbs/'+id+'_'+thumb+'.jpg"/></a>';

      n++;
      if (this.HALF  &&  n==8)
        break;
    }
    str += '</div>';

    
    var obj = document.getElementById('nvid');
    if (obj) obj.innerHTML = n;
    
    this.filmstrip.innerHTML += str;
    this.log(this.filmstrip);
  },
  
  
  setup:function()
  {
    if (location.href.match(/filmstrip/))
    {
      var bodyobj = document.getElementsByTagName("body")[0];
      if (!bodyobj)
        return false;
      var obj = document.createElement('div');
      obj.setAttribute('id', 'filmstrip');
      bodyobj.appendChild(obj);

      obj = document.getElementById('clips');
      if (obj)
        obj.setAttribute('id', 'ignored');
    }

    if (document.getElementById('clips'))
      return this.playClips();

    
    this.filmstrip = document.getElementById('filmstrip');
    if (!this.filmstrip)
      return false;

    var lapses =    location.href.match(/\/samples.htm$/);
    if (!lapses)    this.LAPSES=[]; // no filtering needed!
    if (lapses  ||  location.href.match(/\/video.htm$/))
    {
      // allow for 4 vids per line!
      this.css("div#content { padding-right:10px !important; }");
      this.HALF = '';
    }
    else
    {
      this.css("\n\
body { background:url('http://www.archive.org/~tracey/images/cloudtile.jpg')\n\
       repeat !important;\n\
}\n\
div.box {\n\
  color:yellow !important;\n\
  background-color:rgb(80,133,197) !important;\n\
  border-color: #000055 !important; }\n\
div.box a:link, div.box a:visited, div.box a:active, div.box a:hover {\n\
          color:white !important;\n\
}\n\
\n\
\n\
/* cuteness with BA/DL boxes */\n\
div.box#batting, div.box#downloads    { color: rgb(80,133,197) !important; }\n\
div.box#batting h1, div.box#downloads h1 { color: white !important; }\n\
div.box#batting ol li, div.box#downloads ol li {\n\
  margin-bottom: -20px;\n\
  list-style-image: url('http://www.archive.org/images/star.png');}\n\
\n\
/* cuteness with the reviews box */\n\
div.box#reviews             b   { display: none;}\n\
div.box#reviews             img { position: relative; top: -15px; }\n\
div.box#reviews             a   { position: relative; left: 80px; }\n\
div.box#reviews             br  { margin-bottom: -20px; }\n\
div.box#reviews                 {\n\
  background-image:url('http://www.archive.org/~tracey/images/dumbbunnyhead.gif');\n\
  background-repeat: no-repeat; background-position: center;\n\
}\n\
div.box#description                 { background-color:black !important; }\n\
");
    }

    this.css("\n\
.rounded15 {\n\
  -moz-border-radius:15px;\n\
  -webkit-border-radius:15px;\n\
  -khtml-border-radius:15px;\n\
  border-radius:15px;\n\
}\n\
.strip {\n\
  padding-top:25px;\n\
  padding-bottom:19px;\n\
  float:left;\n\
  position:relative;\n\
  background:url('/~tracey/images/sprok200x174.jpg');\n\
  margin-top:15px;\n\
  margin-bottom:15px;\n\
}\n\
.stripHALF {\n\
  padding-top:25px;\n\
  padding-bottom:19px;\n\
  float:left;\n\
  position:relative;\n\
  background:url('/~tracey/images/sprok200x119.jpg');\n\
  margin-bottom:10px;\n\
}\n\
.cell {\n\
  width:160px;\n\
  height:110px;\n\
  padding: 10 20 10 20;\n\
  margin:0px !important;\n\
  border: 0px;\n\
}\n\
.cellHALF {\n\
  width:80px;\n\
  height:55px;\n\
  padding: 10px;\n\
  margin:0px !important;\n\
  border: 0px;\n\
}\n\
.placard {\n\
  cursor:pointer;\n\
  border:1px solid #333;\n\
  color:white;\n\
  filter:alpha(opacity=70);-moz-opacity:.70;opacity:.70;\n\
  position:absolute;\n\
  background-color:black;\n\
  font-style:italic;\n\
  font-size:10pt;\n\
  padding:0 5 2 5;\n\
}\n\
.placard2 {\n\
  top:140px;\n\
  left:30px;\n\
  min-width:110px;\n\
}\n\
.placard2HALF {\n\
  min-width:55px;\n\
  top:88px;\n\
  left:5px;\n\
}\n\
.placard2HALFb {\n\
  min-width:55px;\n\
  top:88px;\n\
  left:115px;\n\
}\n\
    ");
    
    this.filmstripSetup();
    return false;
  },


  imtoggle:function(id)
  {
    var e=document.getElementById(id);
    if (e)
    {
      if (e.src.match(/.jpg$/))
      {
        e.jpg = e.src;
        e.src = 'http://www.archive.org/serve/'+id+'/'+id+'.gif';
      }
      else
      {
        e.src = e.jpg;
      }
    }
    return false;
  },

  
  css:function(str)
  {
    var headobj = document.getElementsByTagName("head")[0];
    if (!headobj)
      return;
    
    var obj = document.createElement('style');
    obj.setAttribute('type', 'text/css');
    if (obj.styleSheet)
      obj.styleSheet.cssText = str; //MSIE
    else
      obj.appendChild(document.createTextNode(str)); // other browsers
    
    headobj.appendChild(obj);
  },
  
  log:function()
  {
    if (typeof(console)!='undefined')
      console.log(arguments);
  }
};


IAV.setup();
