////////////////////////////////////////////////////////////////////////////////
//Copyright(c)2005-(c)2008 Internet Archive. Software license GPL version 2.



// encrapsulate all our functions and variables.  no globals!
var IAPlay = {

// constants
CLIK2PLAYWIDTH:320,
CONTROLLER_HEIGHT:24,
SUBTITLE_HEIGHT:50,

// why do flash use commas, why?
// (NOTE: flowplayer detection ignores a middle ",0" substring)
MIN_FLASH_VERSION:[7,0],   // the bare minimum -- a C- student
MP4_FLASH_VERSION:[9,115], // this one can play h.264-encoded .mp4!

// usually constant, but *can* change
FLASH_WIDTH:320,  // or 640 for h.264 clips
VIDEO_HEIGHT:240, // or 480 for h.264 clips


  
player:null, // flowplayer JS API object

playlists:null, // holds movies and audio playlist info and other stuff
flowplayerplaylist:null, // DOM obj of playlist div (if there is one)


ready:false,
movie:false,
captions:[],
lastCaptionID:'',
start:0,  // location (in seconds) to seek player to (when relevant)
useVideoTag:false,




// input argument is an object with the following keys/names:
// (for audio)
//   mp3s
//   names
//   lengths
// (for movies)
//   identifier
//   mp4s
//   mp4names
//   flvnames (optional)
//   flvs     (optional)
//   srts     (optional)
insertPlayer:function(playlists)
{
  if (typeof(playlists)=='undefined')
    playlists = this.playlists; // movies coming from click2play()...

  if (!this.useVideoTag)
    this.hide('tryVideo');
  
  
  // id name of the div we will insert the player at ...
  var flowplayerdiv = 'flowplayerdiv'; // ... which is always this
  if (typeof(playlists.flowplayerdiv)!='undefined') // ...unless overridden by arg
    flowplayerdiv = playlists.flowplayerdiv;

  var autoPlay = true;
  if (typeof(playlists.autoPlay)!='undefined') // ...unless overridden by arg
    autoPlay = playlists.autoPlay;
  
  
  
  // see if we are a movie
  var movie = 0 <
    ((typeof(playlists.flvs)=='undefined' ? 0 : playlists.flvs.length)  +
     (typeof(playlists.mp4s)=='undefined' ? 0 : playlists.mp4s.length));
  this.movie = movie;
  

  /************* SETUP THE PLAYLIST AND EMBED FLASH! ***************/ 
  var urls        = null;
  var names       = null;

  // ensure client has minimum flash plugin to play movies or mp3s
  if (!this.useVideoTag  &&
      IAPlay.checkFlashUpgradeNeeded(IAPlay.MIN_FLASH_VERSION))
  {
    return false;
  }
  
  
  if (!movie)
  {
    urls  = playlists.mp3s;
    names = playlists.names;
    document.getElementById(flowplayerdiv).style.height=this.CONTROLLER_HEIGHT;
  }
  else
  {
    var upgradeflash = false;
    if (playlists.mp4s.length)
    {
      if (this.useVideoTag  ||  flashembed.isSupported(IAPlay.MP4_FLASH_VERSION))
      {
        // they can play the mp4s!  keep only the mp4s
        urls  = playlists.mp4s;
        names = playlists.mp4names;
        
        // quadruple the video playsize (double width; double height)
        this.FLASH_WIDTH = 640;
        this.VIDEO_HEIGHT = 480;
      }
      else
      {
        upgradeflash = true;
      }
    }

    if (!urls  &&  typeof(playlists.flvs)!='undefined'  &&  playlists.flvs.length)
    {
      // either only flash videos OR client's flash plugin can only handle flash
      // video (and shockwave) clips (and not h.264 clips)
      urls  = playlists.flvs;
      names = playlists.flvnames;
    }

    if (!urls)
    {
      var str = 'Sorry!  no clips in this item could be played with your flash plugin.';
      if (upgradeflash)
      {
        str = '<div style="padding:10px; border:1px solid brown; background-color:wheat;" class="urge">'+
          'Newer versions of the flash plugin can play this item\'s videos -- ' +
          'Adobe Flash Player version ' + IAPlay.MP4_FLASH_VERSION +
          ' or higher.<br/>'+
          '<small>(It appears you have version: '+flashembed.getVersion()+
          ')</small><br/>'+
          '<a href="http://www.adobe.com/go/getflash/">Get current Flash version</a>'+
          '</div>';
      }

      document.getElementById(flowplayerdiv).innerHTML = str;
      return false;
    }
  }
  



  // tracey jan2009 -- next 2 notes were true for older flowplayer, not sure now--
  //   but we certainly want fully qualified IA playlist urls for offsite
  //   embedding of our flash player and movies on people's sites/blogs!
  // NOTE: for audio embedding, make it the fully qualified url
  // NOTE: have to make it the same as the host where this JS is loaded from
  // or else clicking on playlist rows fails, etc.
  var playListAry = [];
  for (var i=0, url; url = urls[i]; i++)
  {
    if (url.match(/\/\/localhost\//))
      playListAry[i] = url;
    else
      playListAry[i] = 'http://'+location.host+'/download/' + url;
    
    if (!movie  &&  i==0)
      playListAry[0] = { url:playListAry[0], autoPlay:false };
  }

  // save whether or not we are to jump into the movie...
  this.start = (urls == playlists.mp4s ? // for .mp4s
                (this.arg('start') ? parseFloat(this.arg('start')) : 0) : 0);
    
  //console.log(playListAry);
  //console.log(names);
  


  // handle flowplayer bug (IMHO) where when it embeds a mp3(s) flash container
  // into a DIV that is *not* blank/empty, player is invisible and you have to
  // click on the DIV first (?!)
  if (!movie)
    document.getElementById(flowplayerdiv).innerHTML = ' ';

  
  var config = {
       key: '#$b6eb72a0f2f1e29f3d4',
       playlist: playListAry,
       clip: (!movie ? {autoPlay:autoPlay} :
              {autoPlay:autoPlay,accelerated:true,scaling:'fit'}),
       canvas: 
       {
         backgroundColor: '0x000000',
         backgroundGradient: 'none'
       },
       plugins: 
       {
         audio:
         {
             url:'http://'+location.host+'/flow/flowplayer.audio-3.0.3-dev.swf'
         },
         controls:
         {
             playlist:    (playListAry.length > 1 ? true : false),
             fullscreen:  (movie?true:false),
             gloss:       'high',
             backgroundColor: '0x000000',
             backgroundGradient: 'medium',
             sliderColor:'0x777777',
             progressColor:'0x777777',
             timeColor:'0xeeeeee',
             durationColor:'0x01DAFF',
             buttonColor:'0x333333',
             buttonOverColor:'0x505050'
         }
       }
  };

  if (movie  &&  urls == playlists.mp4s)
  {
    // makes it so we can jump into any part of an h.264 movie before it loads!
    config.clip.provider = 'h264streaming';
    config.plugins.h264streaming = {
      url:'http://'+location.host+'/flow/flowplayer.h264streaming-3.0.5.swf'
    };
  }

  if (typeof(playlists.identifier)!='undefined')
  {
    var label = 'Item '+playlists.identifier+' at archive.org';
    var cm = [
    {
    },
    '-',
    'Flowplayer 3.0.5'
    ];

    cm[0][label] = function(){ location.href = 'http://www.archive.org/details/' + playlists.identifier; };
    
    config.contextMenu = cm;
  }
  



  // setup any captioning if relevant
  var captioned = false;
  if (movie  &&  typeof(playlists.srts)!='undefined'  &&  playlists.srts.length)
  {
    if (config.playlist.length > 1)
    {
      // more than 1 clip to play in the viewer -- have to deduce which .srt
      // pertains to which!
      var langs = {'':1, 'en':1, 'fr':1, 'english':1};//xxx
      
      for (var i=0, clip; clip=config.playlist[i]; i++)
      {
        var parts = clip.split('/');
        var srtbase = parts[parts.length-1].replace(/(_512kb)*\.mp4/,'');
        
        var caption = null;
        for (var j=0, srt; srt=playlists.srts[j]; j++)
        {
          for (var lang in langs)
          {
            var cmp = playlists.identifier + '/' + srtbase + (lang?'.'+lang:'') + '.srt';
            //console.log('checking:' + srt + ' vs: ' + cmp);
            if (srt == cmp)
            {
              var captionUrl = 'http://'+location.host+'/download/' + srt;
              //console.log(caption);
              if (typeof(this.captions[i])=='undefined')
                this.captions[i] = {}
              this.captions[i][lang?lang:'en'] = captionUrl;
              captioned = true;
            }
          }
        }
      }
    }
    else
    {
      var i=0;
      for (var j=0, srt; srt=playlists.srts[j]; j++)
      {
        var lang = '';
        var tmp = srt.substr(0, srt.length-4);
        var tmp1 = tmp.lastIndexOf('.');
        var tmp2 = tmp.lastIndexOf('_');
        var tmp3 = tmp.lastIndexOf('-');
        if (tmp1 < playlists.identifier.length + 1) tmp1 = -1;
        if (tmp2 < playlists.identifier.length + 1) tmp2 = -1;
        if (tmp3 < playlists.identifier.length + 1) tmp3 = -1;
        if (tmp1 > 0  ||  tmp2 > 0  ||  tmp3 > 0)
        {
          tmp = Math.max(tmp1, tmp2);
          tmp = Math.max(tmp3, tmp );
          var lang = srt.substr(tmp+1, srt.length - 5 - tmp);
          //console.log(lang);
        }

        if (!lang  ||  (typeof(this.captions[i])!='undefined'  &&
                        typeof(this.captions[i][lang?lang:'en'])!='undefined'))
        {
          // basically back off / give up and use the filename
          lang = srt.substr(srt.lastIndexOf('/')+1);
          lang =lang.substr(0, lang.length - 4); // nix ".srt" suffix
        }
        
        
              var captionUrl = 'http://'+location.host+'/download/' + srt;
              //console.log(caption);
              if (typeof(this.captions[i])=='undefined')
                this.captions[i] = {}
              this.captions[i][lang?lang:'en'] = captionUrl;
              captioned = true;
      }
    }
  }

  if (captioned)
  {
    var cc = [];
    for (i=0; i<2; i++)
    {
      cc[i] = {
        'url':'http://'+location.host+'/flow/flowplayer.content-3.0.2.swf', 
        bottom: (i ? 1 : 0) + this.CONTROLLER_HEIGHT,
        left:   (i ? 0 : 1),
        width: '100%',
        height: this.SUBTITLE_HEIGHT,
        backgroundGradient: 'none',
        backgroundColor: 'transparent',
        border: 0, 
        style: {
          'body': {
            'fontSize': '14',
            fontFamily: 'Arial', 
            textAlign: 'center', 
            color: (i ? '#ffffff'/*white*/ : '#ff0000'/*red*/),
            fontWeight: 'bold'
          }
        }
      };
    }
    
    // configure a content plugin so that it looks good for showing
    config.plugins.captions = {
      'url':'http://'+location.host+'/flow/flowplayer.captions-3.0.0.swf',
      captionTarget: 'content'
    };
    config.plugins.captions2 = {
      'url':'http://'+location.host+'/flow/flowplayer.captions-3.0.0.swf',
      captionTarget: 'c2'
    };
    // make it so the video will *not* play behind the subtitle section
    config.screen ={width:this.FLASH_WIDTH,height:this.VIDEO_HEIGHT,top:0,left:0};
    config.plugins.content = cc[0];
    config.plugins.c2      = cc[1];
    // config.log = { level:'debug' };
  }


  this.flowplayerplaylist = document.getElementById("flowplayerplaylist");

  if (movie)
  {
    // set div's width & height (flowplayer flash obj maximizes into it)
    var el = document.getElementById(flowplayerdiv);
    el.style.width  =  this.FLASH_WIDTH;
    el.style.height = (this.VIDEO_HEIGHT + this.CONTROLLER_HEIGHT +
                       (captioned ? this.SUBTITLE_HEIGHT : 0));
    
    if (this.flowplayerplaylist)
      this.flowplayerplaylist.style.width =  this.FLASH_WIDTH;
  }



  
  // create Flowplayer instance into DIV element whose id="flowplayerdiv"
  //console.log(config);

  if (this.useVideoTag)
  {
    var ogv = (typeof(this.playlists.ogv)!='undefined'  &&  this.playlists.ogv ?
               this.playlists.ogv : '');
    var mp4 = (typeof(this.playlists.mp4s)!='undefined' &&
               this.playlists.mp4s.length > 0 ? this.playlists.mp4s[0] : '');
    if (ogv  ||  mp4)
    {
      var el = document.getElementById(flowplayerdiv);
      var str = '<video controls="true" autoplay="true" '+
        // NOTE: *not* explicitly setting width lets widescreen films show correct
        // ' width="'+el.style.width+'" '+
        ' height="'+
        (parseInt(el.style.height) - this.CONTROLLER_HEIGHT) +'">\n' +
        
        '  <source type="video/mp4" src="http://www.archive.org/download/'+mp4+'"/>\n'+
        '  <source type="video/ogg" src="http://www.archive.org/download/'+ogv+'"/>\n'+

        "\n</video>\n";
      //console.log(str);
      document.getElementById(flowplayerdiv).innerHTML = str;
      return false;
    }
  }
  
  var player = $f(flowplayerdiv,
                  'http://'+location.host+'/flow/flowplayer.commercial-3.0.5.swf', config);
  this.player = player;

  

  if (!this.flowplayerplaylist)
    return false;

  

  //flowplayer API callback that we implement to get flash events when they happen
  if (this.flowplayerplaylist)
  {
    // if playlist present, show the clip's "play triangle" icon; hide the rest
    player.onBegin(function() {
      IAPlay.ready = true;

      var clipnum = $f().getClip().index;
      //console.log("UPDATING TO CLIP: "+clipnum);

      var els = IAPlay.flowplayerplaylist.getElementsByTagName("img");
      for (var i=0; i < els.length; i++)
        els[i].style.visibility = (i==clipnum ? 'visible' : 'hidden');
    });

    // if we are supposed to seek the movie ahead, do so when (first) clip starts
    if (this.start)
    {
      player.onStart(function() {
        if (IAPlay.start)
        {
          IAPlay.player.pause();
          IAPlay.player.seek(IAPlay.start);
          IAPlay.player.resume();
        }
        
        IAPlay.start = 0;
      });
    }
  }
  



  

  var table = '<table class="fplay" style="font: 8pt Arial; margin:0px; border-collapse: collapse !important; border: 2px solid #666666; color:white; font-weight:bold;" width="100%" border="1">\n';
  for (var i=0; i<names.length; i++)
  {
    var name = names[i];
    var col3 = (typeof(playlists.lengths)=="undefined"?"":"<td class=\"c3\">"+
                playlists.lengths[i]+"</td>");
    if (captioned  &&  col3==""  &&  typeof(this.captions[i])!='undefined')
    {
      var str = '';
      for (var lang in this.captions[i])
        str += (str?' | ':'') + ' <span style="padding:0 5 0 5" id="kap.'+
          i+'.'+lang+'"><a onclick="return IAPlay.caption('+i+',\''+
          lang+'\')" href="'+this.captions[i][lang]+'">'+lang+'</a></span>';
      col3 = "<td class=\"c3\"><nobr>Captions:</nobr> <nobr>[ "+ str +" ]</nobr></td>";
    }
    
    table +=
      //NOTE: clicking the row fires an onBegin() event
      '<tr onclick="$f().play('+i+'); return false" class="'+
      (i%2 ? 'eve' : 'odd') + "\"><td class=\"c1\">"+(i+1)+
      "<img src=\"/images/orange_arrow.gif\"/></td><td>"+name+'</td>' + col3+
      "</tr>\n";
  }
  table += "</table>\n";
  //console.log(table);

  this.flowplayerplaylist.innerHTML = table;
  return false;
},


caption:function(idx, lang)
{
  if (this.ready)
  {
    var clip = this.player.getClip(idx);
    
    // keep in mind there could be 2+ languages/caption choices per video!
    var desired = this.captions[idx][lang];
    var current = clip.captionUrl;

    //console.log('show caption '+lang+' please for clip #'+idx);
    //console.log(current+' ==> '+desired);
    
    if (desired != current)
    {
      // play a new caption or new video file (for 2+ videos) with a caption
      clip.update({captionUrl:desired, showCaptions:true});
    }
    else
    {
      // toggle captions on/off for current playing video
      this.player.getPlugin('content').toggle();
      this.player.getPlugin('c2').toggle();
      clip.update({showCaptions:(clip.showCaptions ? false : true)});
    }
    

    if (this.lastCaptionID)
    {
      var el = document.getElementById(this.lastCaptionID);
      el.style.backgroundColor = 'black';
    }

    this.lastCaptionID = 'kap.'+idx+'.'+lang;
    var el = document.getElementById(this.lastCaptionID);
    el.style.backgroundColor = clip.showCaptions ? 'red' : 'black';

    // c2 is the white layer -- xxxx this is still sometimes wrong
    var o = {};
    var kk = 'zindex';
    o[kk]= 7;
    o['z-index']= o[kk];
    o['zIndex']= o[kk];
    $f().getPlugin('content').css(o);
    $f().getPlugin('captions').css(o);
    //console.log(o);

    o[kk]= 10;
    o['z-index']= o[kk];
    o['zIndex']= o[kk];
    $f().getPlugin('c2').css(o);
    $f().getPlugin('captions2').css(o);
    

    if (desired != current)
    {
      // xxx seems heavyhanded
      this.player.stop();
      this.player.close();
      this.player.unload();

      this.player.setClip(clip);
      this.player.load();
      this.player.play(idx);
    }
  }
  return false;
},


// parse a CGI arg
arg:function(theArgName)
{
  sArgs = location.search.slice(1).split('&');
  r = '';
  for (var i=0; i < sArgs.length; i++)
  {
    if (sArgs[i].slice(0,sArgs[i].indexOf('=')) == theArgName)
    {
      r = sArgs[i].slice(sArgs[i].indexOf('=')+1);
      break;
    }
  }
  return (r.length > 0 ? unescape(r).split(',') : '')
},


// inserts embedding HTML to allow a user to embed our flash player on their site
embedthis:function()
{
  var player = null;
  if (this.ready)
    player = $f();

  if (player)
  {
    // these 2 calls get enabled from the file "flowplayer.embed***.min.js"
    player.embed();
    var str = player.getEmbedCode(); 

    if (this.movie) // default to not autoplay
      str = str.replace(/"autoPlay":true/g, '"autoPlay":false');

    if (str.substr(0,10)=='&lt;embed ')
    {
      // NOTE: Embedding on some sites, like blogger.com, have issues with a
      // single <embed/> tag.  So we change the end of the embed HTML to
      // reopen/close tag.  However, we only see this when got here on non-IE!
      str = str.replace(/\/&gt;/, '&gt; &lt;/embed&gt;');
    }

    if (this.movie  &&  typeof(this.playlists.identifier)!='undefined')
    {
      // Add in a thumbnail "splash image" to the playlist for when the
      // first video buffers too slowly to show a splash image quickly
      str = str.replace(/"playlist":\[/,
                        '"playlist":[{"url":"http://www.archive.org/download/'+
                        this.playlists.identifier+
                        '/format=Thumbnail?.jpg","autoPlay":true,"scaling":"fit"},');
    }
    
    // we are putting this inside a value of form "text" elem...  
    str = str.replace(/\"/g, '&quot;').replace(/\n/g, ' ');
    
    str = 'Now simply copy the code below and paste it into your webpage:<br/><input style="border:1px solid gray;" id="embed" type="text" size="20" onclick="document.getElementById(\'embed\').focus(); document.getElementById(\'embed\').select();" readonly="readonly" value="'+str+'"/>' +
      // uncomment for debugging
      // '<textarea rows="50" cols="120">'+str+'</textarea>'
      '';
    
    str = '<div style="padding:2px; background-color:#ddd; border:1px dashed gray;">' + str +
      '<hr/>  NOTE: We are not able to offer a simple piece of HTML to show the playlist along with the player.' +
      '</div>';
  }
  else
  {
    str = '<div style="padding:2px; background-color:#ddd; border:1px dashed gray;">Please first start playing the media so that we can get the HTML for you to use.</br>Then click <a onclick="return IAPlay.embedthis();" href="http://www.archive.org/about/javascript-required.htm">embed this</a> again.</div>';
  }
  
  var obj=document.getElementById('embedthis');
  obj.style.width = '320px';
  obj.innerHTML = str;
  return false;
},



clipthis:function()
{
  var str = '\
<div style="text-align:left; padding:5px; background-color:#ddd; border:1px dashed gray;">\
<form action="/bookmarks.php" onsubmit="return IAPlay.clipcheck()">\
Selecting and bookmarking a clip <img src="/images/cut.png"> from this video is easy:<br/>\
Start playing the video.<br/>\
Press this button: <a onclick="return IAPlay.clippoint(\'start\')" href="#"><img src="/images/resultset_next.png"></a>\
  when you want your clip to START.\
  <span id="startbox" style="display:none">[ Time: <input id="startpt" type="text" name="start" value="">]</span><br/>\
Press this button: <a onclick="return IAPlay.clippoint(\'end\')" href="#"><img src="/images/resultset_previous.png"></a>\
  when you want your clip to END.\
  <span id="endbox" style="display:none">[ Time: <input id="endpt" type="text" name="end" value="">]</span><br/>\
  <input type="hidden" id="mediabox" name="media">\
  <input type="hidden" name="add_bookmark" value="1">\
  <input type="hidden" name="item_identifier" value="'+IAD.pr(IAD.identifier)+'">\
  <input type="hidden" name="title" value="'+IAD.pr(IAD.meta.metadata.title)+'">\
  <input type="hidden" name="mediatype" value="'+IAD.pr(IAD.meta.metadata.mediatype)+'">\
  <input type="submit"></form>\
</div>\
';
  
  var obj = document.getElementById('clipthis');
  obj.style.width = '640px';
  obj.innerHTML = str;
  return false;
},


clippoint:function(startend)
{
  var ptime = this.player.getTime();
  var el;
  console.log(this.player.getClip().completeUrl, ptime);//xxx

  el = document.getElementById(startend+'pt');
  el.value = ptime;

  el = document.getElementById(startend+'box');
  el.style.display='inline';

  var url = this.player.getClip().completeUrl;
  el = document.getElementById('mediabox');
  el.value = url.substr(url.lastIndexOf('/')+1);
},
  

clipcheck:function()
{
  var startpt = document.getElementById('startpt').value;
  var endpt   = document.getElementById('endpt'  ).value;
  if (!startpt && endpt)
    return true;
  if (startpt && !endpt)
    return true;
  if (parseFloat(startpt) < parseFloat(endpt))
    return true;
  alert('Your start point must come before your end point.  Please adjust and re-submit.');
  return false;
},

  

tryVideoTag:function()
{
  this.useVideoTag = true;
  var obj = document.getElementById('tryVideo');
  if (obj)
    obj.innerHTML = 'Now click to play above to try the &lt;video&gt; tag!<br/>You may <a href="#" onclick="return IAPlay.cookieVideoTag()">click here</a> to always use the &lt;video&gt; tag (we will set a cookie).';
  return false;
},

cookieVideoTag:function()
{
  var obj = document.getElementById('tryVideo');
  if (obj)
    obj.innerHTML = 'Your preference for &lt;cookie&gt; tag has been set!  Enjoy!';
  this.setCookie('videoTag','1',180); // persist the choice for 6 months
  return false;
},

uncookieVideoTag:function()
{
  var obj = document.getElementById('tryVideo');
  if (obj)
    obj.innerHTML = 'Thanks for trying the &lt;video&gt; tag!  Reload page if desired!';
  this.setCookie('videoTag','1',-1); // make cookie expire
  return false;
},

// from http://www.w3schools.com/JS/js_cookies.asp
setCookie:function(c_name,value,expiredays)
{
  var exdate=new Date();
  exdate.setDate(exdate.getDate()+expiredays);
  document.cookie=c_name+ "=" +escape(value)+
    ((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
},

// modified from: http://www.w3schools.com/JS/js_cookies.asp
getCookie:function(c_name)
{
  if (document.cookie.length>0)
  {
    c_start=document.cookie.indexOf(c_name + "=");
    if (c_start!=-1)
    { 
      c_start=c_start + c_name.length+1; 
      c_end=document.cookie.indexOf(";",c_start);
      if (c_end==-1) c_end=document.cookie.length;
      
      return decodeURIComponent(document.cookie.substring(c_start,c_end).replace(/\+/g,' '));
    } 
  }
  return "";
},

unhide:function(i)
{
  var e=document.getElementById(i);
  if (e) e.style.display = 'block';
  return false;
},
  
hide:function(i)
{
  var e=document.getElementById(i);
  if (e) e.style.display = 'none';
  return false;
},
  
toggle:function(i)
{
  var e=document.getElementById(i);
  if (e)
    e.style.display=(e.style.display!='block'?'block':'none');
  return false;
},



// input argument is an object with the following keys/names:
//   identifier
//   server
//   flvs
//   mp4s
//   flvnames
//   mp4names
//   thumbs
click2play:function(playlists)
{
  this.playlists = playlists;

  // 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)
  {
    var obj = document.getElementById('flowplayercontainer');
    if (obj)
    {
      var tryVideoTag = document.createElement('div');
      tryVideoTag.style.marginTop = 2;
      if (!this.getCookie('videoTag'))
      {
        tryVideoTag.innerHTML = '<div id="tryVideo" style="font-size:90%; border:1px dashed #ddd; background-color:#f0f0f0; padding:2px; width:300px; margin:auto;">Your browser supports the new &lt;video&gt; tag!<br>Would you like to <nobr><a onclick="return IAPlay.tryVideoTag()" href="#">try the new &lt;video&gt; tag</a></nobr>?</div>';
      }
      else
      {
        this.useVideoTag = true;
        tryVideoTag.innerHTML = '<div id="tryVideo" style="font-size:90%; padding:2px;">(<a href="#" onclick="return IAPlay.uncookieVideoTag()">Click here</a> to stop using the &lt;video&gt; tag)</a>';
      }
      obj.appendChild(tryVideoTag);
    }
  }
  
  
  if (navigator.userAgent.indexOf('iPhone') >= 0  ||
      navigator.userAgent.indexOf('iPod'  ) >= 0  ||
      navigator.userAgent.indexOf(' Pre/' ) >= 0) // palm pre
  {
    // the HTTP user agent appears to be an iphone/ipod/pre -- don't bother w/ the
    // flash video and have the click go right to a MPEG4 instead...
    // (... or the agent appears to be an ipod video 8-)
    clik = '<a href="/download/' +
      (playlists.mp4s.length > 0 ? playlists.mp4s[0] :
       playlists.identifier + '/format=256Kb%20MPEG4') + '">';
  }
  else if (navigator.userAgent.indexOf('OLPC/') >= 0  &&
           typeof(playlists.ogv)!='undefined'  &&  playlists.ogv)
  {
    // OLPC cutie green machine -- gnash shipped with it can't seem to play
    // our h.264 files (yet!) but it can play "Ogg Video"
    clik = '<a href="/download/' + playlists.ogv + '">';
  }
  else
  {
    clik =
      '<a href="/about/javascript-required.htm" '+
      ' onClick="return IAPlay.insertPlayer()">';
  }

  
  str =
    '<div style="margin-left:auto; margin-right:auto; width:'+
    IAPlay.CLIK2PLAYWIDTH+'; height:'+IAPlay.VIDEO_HEIGHT+
    'px; text-align:center; position:relative;">' +
    '<div style="width:'+IAPlay.CLIK2PLAYWIDTH+
    '; position:absolute; top:0; left:0;">';

  var thumbs=playlists.thumbs;
  
  var l=thumbs.length;
  /**/ if (l==1)thumbA2 = new Array(thumbs[0], null,      null,      null);
  else if (l==2)thumbA2 = new Array(thumbs[0], null,      null,      thumbs[1]);
  else if (l==3)thumbA2 = new Array(thumbs[0], thumbs[1], thumbs[2], null);
  else if (l>=4)thumbA2 = new Array(thumbs[0], thumbs[1], thumbs[2], thumbs[3]);
  else          thumbA2 = new Array(null,      null,      null,      null);
    
        
  // show up to first 4 thumbs, in 2x2 grid
  // add 10px solid black bar on top and bottom of overall grid
  var prefix = (playlists.server ? 'http://'+playlists.server : '');
  for (i=0; i < 4; i++)
  {
    str +=
      clik +
      '<img alt="click to play movie" title="click to play movie" style="border:0; border'+
      (i < 2 ? '-top' : '-bottom') +
      ':10px solid black; width:160px; height:110px;" ' +
      (thumbA2[i] ?
       'src="'+ prefix + thumbA2[i] + '"/>' :
       'src="/images/movies.gif">') +
      '</a>';
    if (i % 2 == 1)
      str += '<br/>';
  }

  
  str +=
    clik +
    '<img alt="click to play movie" title="click to play movie" style="position:absolute; top:0px; left:0px; height:'+
    IAPlay.VIDEO_HEIGHT+'px; width:'+IAPlay.CLIK2PLAYWIDTH+
    'px; z-index:2; border:0px;" src="/images/clicktoplay.png"/></a>';

  
  str += '</div></div>';
  //console.log(str);
  
  document.getElementById('flowplayerdiv').innerHTML = str;
},
  


checkFlashUpgradeNeeded:function(requiredVersion)
{
  if (flashembed.isSupported(requiredVersion))
    return false;
  
  var obj = document.getElementById('embedthis');
  if (obj)
  {
    var currentVersion = flashembed.getVersion();
    var ver = flashembed.getVersion();
    var uhave = (ver=='0,0' ?
                 ' you do not have flash installed or have it disabled' :
                 ' you have version: '+ver+'');
    obj.innerHTML =
    '<div style="padding:10px; border:1px solid brown; background-color:wheat;" class="urge">'+
    'Internet Archive\'s<!--\'--> in-browser media player requires '+
    'Adobe Flash Player version ' + requiredVersion + ' or higher.<br/>'+
    '<small>(It appears '+uhave+')</small><br/>'+
    '<a href="http://www.adobe.com/go/getflash/">Get current Flash version</a>'+
      '</div>';
  }
  
  return true;
}
  

}; // end IAPlay definition
