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

  //////////////////////////////
 ////     OBSOLETED       /////
//////////////////////////////


/*
  !! NOTE !!  We no longer use this file (or flowplayer).

  See "/includes/play.js"
  for the new version of what we are using for all video/audio now.

  This file remains since we have a very small number of things still
  using it (zotero, mashup) and there may be some patrons in the field using
  this file for displaying movies on 3rd party sites (but we hope not!)
*/


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

// constants
CLIK2PLAYWIDTH:320,
CLIK2PLAYHEIGHT:240,
CONTROLLER_HEIGHT:26,
AUDIO_HEIGHT:220,
FLASH_WIDTH:640,
VIDEO_HEIGHT:480,


// 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!


// id name of the div we will insert the player at ...
flowplayerdiv:'flowplayerdiv',  //can in be overridden (rarely, eg mashup.js)


player:null, // flowplayer JS API object

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


ready:false,
movie:false,
captioned:false,
lastCaptionID:'',
start:0,  // location (in seconds) to seek player to (when relevant)
end:0,    // location (in seconds) to stop player at (when relevant)
playingClipNum:0, // only for <video> tag now, but could be used more in future
playing264:false,
flashFailed:false,
audioSharingShowing:false,
playerShowing:false,

flowdir:'http://'+location.host+'/flow/',
playerSwfUrl:'http://'+location.host+'/flow/flowplayer.commercial-3.2.1.swf',
emptySRT:'http://'+location.host+'/includes/empty.srt',

names:[],
urls:[],


insertPlayer:function(playlists) // convenience legacy function
{
  this.configPlayer(playlists);
  return this.showPlayer();
},



// input argument is an object with the following keys/names:
// (for audio)
//   mp3s
//   names
//   lengths
// (for movies)
//   identifier
//   mp4s
//   mp4names
//   flvnames (optional)
//   flvs     (optional)
//   captions (optional)
configPlayer:function(playlists)
{
  // http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
  if (location.host=='www-tracey.archive.org') { "use strict"; }

  
  if (typeof(this.mrss) != 'undefined')
  {
    // This MRSS is the new way we do business in this town.
    // We will completely synthesize a "playlists" object from MRSS from scratch!
    var play2 = {'mp4s':[],
                 'flvs':[],
                 'mp3s':[],
                 'names':[],
                 'mp4names':[],
                 'flvnames':[]
                };
    var k;
    k='title';     if(typeof(playlists[k])!='undefined') play2[k]=playlists[k];
    k='server';    if(typeof(playlists[k])!='undefined') play2[k]=playlists[k];
    k='captions';  if(typeof(playlists[k])!='undefined') play2[k]=playlists[k];
    k='thumbs';    if(typeof(playlists[k])!='undefined') play2[k]=playlists[k];
    k='identifier';if(typeof(playlists[k])!='undefined') play2[k]=playlists[k];
    
    playlists = play2;
    this.playlists = playlists; //swaparoo evil muhahahahaaaaaa!
    
    var mrss = $.parseXML(unescape(this.mrss).replace(/\+/g,' ').replace(/media:/g,''));
    $mrss = $(mrss);
    $mrss.find('item').each( function (i, node){ 
      //console.log(node);
      var title = $(node).find('title').text().replace(/^[0-9]+ /, '');
      $(node).find('content').each( function (idx, content ){
        var len = $(content).attr('duration');
        var ty  = $(content).attr('type');
        var url = $(content).attr('url').replace(/^\/download\/[^\/]+\//, '');
        //console.log(url);
        if (ty=='video/h264')
        {
          playlists.mp4s.push(url);
          playlists.mp4names.push(title);
        }
        else if (ty=='audio/mpeg')
        {
          playlists.mp3s.push(url);
          if (typeof(playlists.lengths)=='undefined')
            playlists.lengths=[];
          if (typeof(len)!='undefined'  &&  len>0)
          {
            var h = Math.floor(len / 3600);
            var m = Math.floor((len - (h * 3600)) / 60);
            var s = len - (h * 3600) - (m * 60);
            // left 0-pad "minutes" if hours present...
            // if either hours/mins present, left 0-pad "seconds"
            if (h || m || s)     { s = '00'+s; s=s.substr(s.length-2,2); }
            if (h)               { m = '00'+m; m=m.substr(m.length-2,2); }
            else if (s && m <10) { m =  '0'+m; m=m.substr(m.length-1,1); }
            else if (s && m  >9) { m = '00'+m; m=m.substr(m.length-2,2); }

            playlists.lengths.push((h ? h+':' : '')+
                                   (m ? m+':' : '')+
                                   s);
          }
          else
          {
            playlists.lengths.push(0);
          }
          playlists.names.push(title);
        }
        else if (ty=='video/x-flv')
        {
          playlists.flvs.push(url);
          playlists.flvnames.push(title);
        }
      });
    });
  }
  

  this.playlists = playlists;

  if (typeof(playlists.flowplayerdiv)!='undefined') // ...unless overridden by arg
    this.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! ***************/

  if (!movie)
  {
    this.urls  = playlists.mp3s;
    this.names = playlists.names;
  }
  else
  {
    if (playlists.mp4s.length)
    {
      // keep only the mp4s
      this.urls  = playlists.mp4s;
      this.names = playlists.mp4names;
      this.playing264 = true;
    }
    else if (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)
      this.urls  = playlists.flvs;
      this.names = playlists.flvnames;
    }
  }


  if (!this.urls  ||  this.urls.length==0)
  {
    this.warn('Sorry!  no clips in this item could be played with your flash plugin.');
    return;
  }






  // 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 = this.urls[i]; i++)
  {
    if (url.match(/\/\/localhost\//))
      playListAry[i] = url;
    else
      playListAry[i] = 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 = (this.urls == playlists.mp4s ? // for .mp4s
                (this.arg('start') ? parseFloat(this.arg('start')) : 0) : 0);

  this.end =   (this.urls == playlists.mp4s ? // for .mp4s
                (this.arg('end') ? parseFloat(this.arg('end')) : 0) : 0);




  //console.log(playListAry);
  //console.log(this.names);

  // have to swap out most non-simple chars (boo hoo!) for safe transporting to
  // the viral plugin(s)...
  var ttl = (typeof(playlists.title)=='undefined' ? playlists.identifier :
             playlists.title.replace(/[^-A-Za-z0-9_ ]/g, ' '));
  //console.log(ttl);

  var config = {
    key: '#$aa4baff94a9bdcafce8',
    playlist: playListAry,
    clip: {
      autoPlay:autoPlay,
      baseUrl:'http://'+location.host+'/download/'+playlists.identifier+'/'
    },
    canvas:
    {
      backgroundColor: '#000000',
      backgroundGradient: 'none'
    },
    plugins:
    {
      audio:
      {
        url:this.flowdir+'flowplayer.audio-3.2.1-dev.swf'
      },
      controls:
      {
        playlist:    (playListAry.length > 1 ? true : false),
        fullscreen:  (movie?true:false),
        height: this.CONTROLLER_HEIGHT,
        backgroundColor: '#000000',
        autoHide: { fullscreenOnly:true }
      },
      viral:
      {
        url: this.flowdir+'flowplayer.viralvideos-3.2.1-dev.swf',
        embed:false,
        email:false,
        share:
        {
          title: ((this.movies ?
                   'Click on an icon to share this video' :
                   'Click an icon to share this recording') +
                  "\n(allow pop ups for this feature)"),
          description: ttl + ' at archive.org',
          livespaces: false // disable Microsoft livespaces
        }
      }
    }
  };

  if (movie)
  {
    config.clip.scaling='fit';

    if (typeof(this.playlists.identifier)!='undefined')
    {
      var vurl='http://www.archive.org/details/'+this.playlists.identifier;
      // enable the "email" button and start with custom pre-filled out body
      config.plugins.viral.email = {texts:{
        subject: 'Internet Archive video'+(ttl ? ' -- '+ttl : ''),
        template:'{0}\n\n Video Link: <href="'+vurl+'">'+vurl+'</a>',
        message: 'We will fill out the video link, title, and subject for you.\nYou may add an additional personal message to the body here'
        }};
    }
  }
  else
  {
    // make more room for the scrubber bar!
    config.plugins.controls.scrubberHeightRatio= 0.6;
    config.plugins.controls.timeFontSize = 9;
    config.plugins.controls.mute = false;


    // ensure play/scrub bar stays at the top vertically of the flash container
    config.plugins.controls.top=0;

    // we have to adjust the viral plugin quite a bit for audio...
    // where the colors are to make much of the crap in it "disappear" by being
    // same color as the background...
    config.plugins.viral.top = this.CONTROLLER_HEIGHT;
    config.plugins.viral.icons = { color: '#000000',
                                   overColor: '#000000',
                                   fontColor: '#000000',
                                   lineColor: '#000000',
                                   backgroundColor: '#000000' };
    config.plugins.viral.canvas = { color: '#000000',
                                    fontColor: '#000000',
                                    lineColor: '#000000',
                                    backgroundColor: '#000000'
    };
    // ugh!  mattes out the annoying "sometimes shows and fades" small [Share]
    // icon internal to viral plugin...
    config.plugins.viralmatte ={'url':this.flowdir+'flowplayer.content-3.2.0.swf',
                                'top': this.CONTROLLER_HEIGHT,
                                'left': (this.FLASH_WIDTH / 2),
                                'height': 26,
                                'width':'100%',
                                'zIndex': 10000,
                                'opacity': 1.0,
                                style:{ 'opacity':1.0,
                                    'borderColor':'#000000',
                                    backgroundColor:'#000000',
                                    color:'#000000',
                                    backgroundGradient:'none' }
    };
  }



  if (movie  &&  this.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:this.flowdir+'flowplayer.pseudostreaming-3.2.1.swf'
    };
  }

  if (typeof(playlists.identifier)!='undefined')
  {
    var label=(movie?'View+':'Listen+to+')+playlists.identifier+'+at+archive.org';
    var cm = [
    {
    },
    '-',
    'Flowplayer v3.2.1'
    ];

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

    config.contextMenu = cm;
  }




  // setup any captioning if relevant
  this.captioned = this.captionSetup(config);


  this.flowplayerplaylist = document.getElementById("flowplayerplaylist");
  
  if (this.movie)
    this.insertPlaylist();


  //console.log(config);
  if (typeof(this.playlists.identifier)!='undefined')
    this.embedthis();
  this.config = config;
},


audioShare:function()
{
  if (!this.player)
  {
    alert('this feature requires our flash-based player to be used');
    return false;
  }

  var fpdiv = document.getElementById(this.flowplayerdiv);
  if (this.audioSharingShowing)
  {
    this.player.getPlugin('viral').fadeOut();
    this.player.getPlugin('viral').hide();
    fpdiv.style.height = this.CONTROLLER_HEIGHT + 'px';
    this.audioSharingShowing = false;
  }
  else
  {
    fpdiv.style.height = (this.CONTROLLER_HEIGHT+this.AUDIO_HEIGHT) +'px';
    IAPlay.player.getPlugin('viral').fadeIn();
    this.audioSharingShowing = true;
  }
  return false;
},


showPlayer:function()
{
  if (this.playerShowing) 
    return false;
  this.playerShowing = true;


  if (!this.flashOK())
    return false;
  
  
  var movie = this.movie;

  var flashed = document.getElementById(this.flowplayerdiv+'_api');
  var fpdiv = document.getElementById(this.flowplayerdiv);
  if (!movie  &&  flashed)
  {
    // OK this is wack.  lemme 'splain...
    // This is an audio item, and means flowplayer has already inserted a flash
    // plugin into the "flowplayerdiv".  We get here pretty much only when
    // the user is clicking the "try the new <audio> tag" (and not cookied).
    // Ideally, we'd just like to insert new <audio> tag HTML into flowplayerdiv.
    // BUT!  NOT SO FAST!  8-)
    // The prior flash "install" put a bunch of event handling stuff and hex
    // cursed the div (so the <audio> tag play/pause and mute/unmute buttons
    // weren't working).  Solution?  make a brand new clean div, and "steal"
    // the "id" back;  and tell the flash div to STFU...
    var fresh = document.createElement('div');
    fresh.style.width  = fpdiv.style.width;
    fresh.id = this.flowplayerdiv;

    fpdiv.id = 'kickedoldskool';
    fpdiv.style.height = '1px';
    fpdiv.style.width = '1px';
    fpdiv.innerHTML = '';
    fpdiv.display = 'none';
    fpdiv.parentNode.insertBefore(fresh, fpdiv);

    // now re-get the div for the id...
    fpdiv = document.getElementById(this.flowplayerdiv);
  }
  else
  {
    // 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 (?!)
    fpdiv.innerHTML = ' ';
  }




  if (movie)
  {
    // set div's width & height (flowplayer flash obj maximizes into it)
    fpdiv.style.width  = '100%';
    fpdiv.style.height = (this.VIDEO_HEIGHT + this.CONTROLLER_HEIGHT) + 'px';
    if (this.flowplayerplaylist)
      this.flowplayerplaylist.style.width =  this.FLASH_WIDTH + 'px';

    this.config.clip.onMetaData  = function(clip) { IAPlay.shrinkToFit(clip); };
  }
  else
  {
    fpdiv.style.height = this.CONTROLLER_HEIGHT + 'px';
  }





  // by avid movie fans request -- since we will be playing the movie now,
  // replace animated GIF in upper left (where applicable) with single Thumbnail!
  var thumb = document.getElementById('thumbnail');
  if (thumb  &&  movie  &&  typeof(this.playlists.identifier)!='undefined'  &&
      typeof(thumb.src)!='undefined')
  {
    thumb.src = 'http://www.archive.org/download/'+this.playlists.identifier+
      '/format=Thumbnail';
  }



  // create Flowplayer instance into DIV element whose id="flowplayerdiv"
  this.player = $f(this.flowplayerdiv, this.playerSwfUrl, this.config);

  if (!this.flowplayerplaylist)
    return false;


  {
    //flowplayer API callbacks that we use to get flash events when they happen
    if (this.flowplayerplaylist)
    {
      if (!this.movie)
      {
        this.player.onMouseOut(function() {
            if (IAPlay.audioSharingShowing)
              IAPlay.audioShare();
          });
      }


      // if playlist present, show the clip's "play triangle" icon; hide the rest
      this.player.onBegin(function() {
          IAPlay.ready = true;

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

          if (IAPlay.captioned)
            IAPlay.caption(clipnum);

          IAPlay.indicateIsPlaying(clipnum);
        });

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

              if (IAPlay.end)
              {
                IAPlay.warn('[beta] Desired seek range is: ['+
                            IAPlay.hms(IAPlay.start)+' to '+
                            IAPlay.hms(IAPlay.end)+
                          ']');
              }
            }

            IAPlay.start = 0;
          });
      }
    }
  }
  
  if (!this.movie)
    this.insertPlaylist();
  return false;
},

  
insertPlaylist:function()
{
  if (typeof(this.names)=='undefined')
    return; // eg: zotero item

  var table = '<table class="fplay" border="1">\n';
  for (var i=0; i<this.names.length; i++)
  {
    var name = this.names[i];
    var col3 = (typeof(this.playlists.lengths)=="undefined"?"":
                "<td class=\"c3\">"+
                (this.playlists.lengths[i] ? this.playlists.lengths[i] : "")+
                "</td>");
    if (this.captioned)
    {
      if (typeof(this.captions[i])=='undefined')
      {
        col3 = '<td class="c3"> </td>';
      }
      else
      {
        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="return IAPlay.playClip('+i+')" 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;
},


hms:function(s)
{
  var h=parseInt(s/3600);
  s -= h*3600;
  var m=parseInt(s/60);
  s -= m*60;
  return (
    (h>0?h+':':'')+
    (m<10?'0':'')+m+':'+
    (s<10?'0':'')+s);
},


// dynamically resizes the flowplayer div / video tag
// (and playlist, when applicable) to auto-center and have minimal blackbars!!
shrinkToFit:function(clip)
{
  var viddiv=0, vidSrcWidth=0,  vidSrcHeight=0;
  if (typeof(clip)=='undefined')
  {
    // video tag
    viddiv = document.getElementById('iavtag');
    if (viddiv)
    {
      vidSrcWidth  = viddiv.videoWidth;
      vidSrcHeight = viddiv.videoHeight;
    }
  }
  else
  {
    // flowplayer
    viddiv = document.getElementById(this.flowplayerdiv);
    vidSrcWidth  = clip.metaData.width;
    vidSrcHeight = clip.metaData.height;
  }

  if (!viddiv)
    return; // should never happen, but be safe!



  var newPlayerWidth =
    Math.round(this.VIDEO_HEIGHT * (1.0 * vidSrcWidth/vidSrcHeight));
    //console.log(vidSrcWidth+'x'+vidSrcHeight+' => '+newPlayerWidth+'x'+this.VIDEO_HEIGHT);
  viddiv.style.width = newPlayerWidth + 'px';
  var el = document.getElementById('flowplayerplaylist');
  if (el)
    el.style.width = newPlayerWidth + 'px';
},


// marks the playlist row for the video that is playing w/ orange triangle
indicateIsPlaying:function(clipnum)
{
  var els = IAPlay.flowplayerplaylist.getElementsByTagName("img");
  for (var i=0; i < els.length; i++)
    els[i].style.visibility = (i==clipnum ? 'visible' : 'hidden');
},


playClip:function(idx)
{
  // flash player
  IAPlay.showPlayer(); 
  $f().play(idx);
  return false;
},


// NOTE: only used for <video> or <audio> tag
clipEnded:function()
{
  idx = this.playingClipNum;
  console.log('clipEnded:'+idx);

  this.playClip(idx+1); // now play the next clip (if there is one)
},


// returns whether or not client has minimum flash plugin to play movies or mp3s
// turning on warning messages if they do not!
flashOK:function()
{
  if (this.flashFailed) // dbl check against 2+ presses of click2play when !flash
    return false;

  if (IAPlay.checkFlashUpgradeNeeded(IAPlay.MIN_FLASH_VERSION))
  {
    this.flashFailed = true;
    return false;
  }
  if (this.playing264  &&  !flashembed.isSupported(IAPlay.MP4_FLASH_VERSION))
  {
    this.warn(
      '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>');
    this.flashFailed = true;
    return false;
  }

  return true;
},


// subtitles/captions
captionSetup:function(config)
{
  var playlists = this.playlists;

  if(!this.movie  ||  typeof(playlists.captions)=='undefined')
    return false;

  this.captions = playlists.captions;
  config.clip.showCaptions = true;
  


  // If 1st video has srt, set it up (really just for embed code users)
  //console.log(this.captions);
  for (var j in this.captions[0])
  {
    config.clip.captionUrl = 'http://'+location.host+this.captions[0][j];
    break;
  }


  // configure a content plugin so that it looks good for showing
  config.plugins.captions  = { 'url':this.flowdir+'flowplayer.captions-3.2.0.swf',
                               captionTarget: 'content' };
  config.plugins.content = {
    display: 'none', // start *not* showing captions
    'url':this.flowdir+'flowplayer.content-3.2.0.swf',
    bottom: this.CONTROLLER_HEIGHT,
    left:   0,
    width: '100%',
    height: 50,
    backgroundGradient: 'none',
    backgroundColor: 'transparent',
    textDecoration: 'outline', // very important for readability in fullscreen!
    border: 0,
    style: {
      'body': {
      fontSize: '14',
      fontFamily: 'Arial',
      textAlign: 'center',
      fontWeight: 'bold',
      color: '#ffffff' //white
      }
    }
  };
  // config.log = { level:'debug' };

  return true;
},


caption:function(idx, lang)
{
  if (this.ready)
  {
    var clip = this.player.getClip(idx);

    if (typeof(lang)=='undefined')
    {
      // new clip is starting -- arbitrarily pick the first language
      lang = false;
      for (var i in this.captions[idx])
      {
        lang=i;
        break;
      }
      if (!lang)
      {
        this.player.getPlugin('captions').loadCaptions(idx, this.emptySRT);
        return false; // this particular clip has no subtitles.  nothing to do!
      }
    }


    // keep in mind there could be 2+ languages/caption choices per video!
    var desired = 'http://'+location.host+this.captions[idx][lang];

    //console.log('show caption '+lang+' please for clip #'+idx);

    this.player.getPlugin('captions').loadCaptions(idx, desired);

    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 = 'red';
  }
  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 IA A/V player on their site
embedthis:function()
{
  // quote since we'll be putting this inside a value of form "text" elem...
  var embedTag = '<iframe src="http://www.archive.org/embed/'+this.playlists.identifier+'" width="640" height="480" frameborder="0"></iframe>';
  embedTag = embedTag.replace(/\"/g, '&quot;');

  $('#embedthis').html('<small><a href="http://www.archive.org/about/javascript-required.htm" onclick="$(\'#etdiv\').toggle(); return false">embed this</a></small>' +
    '<div id="etdiv" style="display:none; padding:2px; background-color:#ddd; border:1px dashed gray;">' +
    '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="'+embedTag+'"/>' +
    '<hr/>  You may opt for a playlist along with the player -- <a href="/help/video.php">custom embedding tips</a>' +
    '</div>');
},




click2play:function()
{
  var clik =
      '<a href="/about/javascript-required.htm" '+
      ' onClick="return IAPlay.showPlayer()"';


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

  var thumbs=this.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 = (this.playlists.server ? 'http://'+this.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 + ' onmouseover="document.getElementById(\'c2pimg\').src=\'/images/clicktoplay_over.png\'" onmouseout="document.getElementById(\'c2pimg\').src=\'/images/clicktoplay_click.png\'"' +
    '><img id="c2pimg" alt="click to play movie" title="click to play movie" style="position:absolute; top:0px; left:0px; height:'+
    IAPlay.CLIK2PLAYHEIGHT+'px; width:'+IAPlay.CLIK2PLAYWIDTH+
    'px; z-index:2; border:0px;" src="/images/clicktoplay_click.png"/></a>';


  str += '</div></div>';
  //console.log(str);

  document.getElementById(this.flowplayerdiv).innerHTML = str;
},


warn:function(str)
{
  var obj = document.getElementById('flowplayercontainer');
  if (obj)
  {
    var warn = document.createElement('div');
    warn.className='urge flashme';
    warn.innerHTML = str;
    obj.appendChild(warn);
  }
  else
  {
    alert(str);
  }
},


checkFlashUpgradeNeeded:function(requiredVersion)
{
  // NOTE: wrap "flashembed" object calls with try/catch because upon flowplayer
  // upgrade to v3.2.1 (may2010) when flash plugin is disabled in firefox,
  // these calls started blowing up 8-(
  try { if (flashembed.isSupported(requiredVersion)) return false; } catch(E) {}


  var currentVersion = '0,0';
  try { currentVersion = flashembed.getVersion(); } catch(E) {}

  var uhave = (currentVersion=='0,0' ?
               ' you do not have flash installed or have it disabled' :
               ' you have version: '+currentVersion+'');
  this.warn(
    '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>');

  return true;
},

  
loaded:function()
{
  $('head').append($('<link rel="stylesheet" type="text/css" />')
    .attr('href', '/flow/players.css')); 

  // if there are no media files appropriate for our flash player, we won't
  // bother with wasting time loading flash
  if (!this.playlists)
    return false;
  
  this.configPlayer(this.playlists);
  
  if (typeof(this.playlists.thumbs)=='undefined')
    return this.showPlayer();
  
  if (!this.arg('start'))
    return this.click2play();

  // movies where supposed to jump right in...
  this.showPlayer();
  this.player.play();
  
  return false;
}
  
}; // end IAPlay definition



$(window).load(function(){ IAPlay.loaded();});

