// To add a tab
//
// Modify VP_linksArray to add the name of your tab's (div id)
// Add your tab display (to display the link you can click on)
// Add your tab's div down below


// We call sendRequest from various places on the VideoPlayPage
// This is the dispatcher which looks at the passed in uri so
// that after we send our request to the passed in uri we know
// how to handle this.
//
// it be nice if we got rid of this and moved the sendAjaxRequest
// out to the callers...
function sendRequest(uri) {
  if (uri.indexOf('/videomorefrom?') == 0) {
    sendAjaxRequest(uri, handleMoreFromResponse);
    switchActiveDiv('morefromvids', false); // show 'Searching...' message
  } else if (uri.indexOf('/videostats?') == 0) {
    sendAjaxRequest(uri, handleStatsResponse);
  } else if (uri.indexOf('/videoevents?') == 0) {
    sendAjaxRequest(uri, null);
  }
  else {
    return;
  }
}

function sendPlaylistNextRequest() {
  if (VP_next10DocId == "0") {
    switchActiveDiv('next10link', false); // should have been disabled...
    return;
  }
  var currentDoc = window.location.search.split("docid=")[1].split("&")[0];
  var shortPlaylist = "";
  var playlistArray = VP_myPlaylist.split(",");
  if (playlistArray.length > 91) {
    // avoid MSIE's AJAX send-length limitation by choosing subset of playlist
    var arrLen = playlistArray.length;
    var curPos = -1;
    for (var i = 0; i < arrLen; i++) {
      if (currentDoc == playlistArray[i]) {
        curPos = i;
        break;
      }
    }
    var start = Math.max(0, curPos - 40);
    var end = Math.min(arrLen, start + 90);
    shortPlaylist = playlistArray.splice(start, end - start).join(",");
  } else {
    shortPlaylist = VP_myPlaylist;
  }
  var finalUri = '/videoplaylistnext?docid=' + VP_next10DocId + '&num=10&q=' +
                 shortPlaylist + 'n' + currentDoc;
  sendRequest(getNoCacheURL(finalUri));
}

function handleMoreFromResponse (req) {
  if (req.readyState == 4) {
    outputGrid('morefromvidsactive', req.responseText)
    switchActiveDiv('morefromvids', true); // hide message, show results
  }
}

function handleStatsResponse(req) {
  return;
}

/* Decorate playlist controls based on cookie settings */
function applyPlaylistSettings() {
  readSettingsFromCookie();
  refreshAutoplayLinks();
  refreshDescription();
  refreshVisibleTab("dmrcfp", "p");
  setPlaylistValid(false);
}

function readSettingsFromCookie() {
  // read settings from cookie if they are defined
  // needed for correctness after page refresh on IE
  var plSettings = getCookie(VP_playlistSettingsCookieName);
  if (!plSettings) { // cookie is not set yet
    savePlaylistSettings(); // store the values provided by the server
  } else {
    // read 'autoplayEnabled'
    if (plSettings.charAt(0) == '1') {
      VP_autoplayEnabled = true;
    } else {
      VP_autoplayEnabled = false;
    }
    // read 'collapseDescr'
    if (plSettings.charAt(1) == '0') {
      VP_collapseDescr = false;
    } else {
      VP_collapseDescr = true;
    }
    // read 'visibleTab'
    VP_visibleTab = plSettings.charAt(2);
  }
}

function refreshDescription() {
  if (ele('collapselink')) { // collapse/expand links are present
    if (VP_collapseDescr) {
      ele('collapselink').onclick();
    } else {
      ele('expandlink').onclick();
    }
  }
}

/**
 * This function is called by the play page to restore
 * the state of the playcorner tabs from from the cookie (which
 * gets stuffed into VP_visibileTab.)
 * You'll want to add something here if you add a new tab
 * 
 * @param {String} visibleTabs A string containing labels of all visible tabs. 
 *                 eg. "dmrcfp"
 * @param {String} defaultTab The label of the default tab. eg. "m"
 */
function refreshVisibleTab(visibleTabs, defaultTab) {
  if (visibleTabs != null && 
      defaultTab != null &&
      visibleTabs.indexOf(VP_visibleTab) < 0) {
    VP_visibleTab = defaultTab;
  }
  if (VP_visibleTab == 'd') {
    ele("ldetails").onclick();
  } else if (VP_visibleTab == 'm') {
    ele("lmorefrom").onclick();
  } else if (VP_visibleTab == 'r') {
    ele("lrelated").onclick();
  } else { // default is playlist
    VP_visibleTab = 'p';
    if (ele("lupnext") && ele("lupnext").onclick) {
      ele("lupnext").onclick();
    }
  }
}

/* Set my playlist values in the cookie */
function setMyPlaylist() {
  setSessionCookie(VP_playlistCookieName,
                   VP_myPlaylist,
                   VP_cookieDomain);
  setSessionCookie(VP_playlistIndexCookieName,
                   VP_myPlaylistIndex,
                   VP_cookieDomain);
  // Play request is generated at play page, set playlistValid to true
  setPlaylistValid(true);
  savePlaylistSettings();
}

/* Functions for saving playlist settings in the cookie */
function saveAutoplay(autoplay) {
  var plSettings = getCookie(VP_playlistSettingsCookieName);
  if (!plSettings) { // cookie is not set
    savePlaylistSettings(); // store current values
    return;
  }
  setPermanentCookie(VP_playlistSettingsCookieName,
                     ((autoplay ? "1" : "0" ) + plSettings.substring(1,3)),
                     VP_cookieDomain);
}

function saveCollapseDescr(collapse) {
  VP_collapseDescr = collapse;
  var plSettings = getCookie(VP_playlistSettingsCookieName);
  if (!plSettings) { // cookie is not set
    savePlaylistSettings(); // store current values
    return;
  }
  setPermanentCookie(VP_playlistSettingsCookieName,
                     (plSettings.charAt(0) + (collapse ? "1" : "0" ) +
          plSettings.charAt(2)),
                     VP_cookieDomain);
}

function saveVisibleTab(tabIndex) {
  VP_visibleTab = tabIndex;
  var plSettings = getCookie(VP_playlistSettingsCookieName);
  if (!plSettings) { // cookie is not set
    savePlaylistSettings(); // store current values
    return;
  }
  setPermanentCookie(VP_playlistSettingsCookieName,
                     (plSettings.substring(0,2) + tabIndex),
                     VP_cookieDomain);
}

function savePlaylistSettings() {
  setPermanentCookie(VP_playlistSettingsCookieName,
                     ((VP_autoplayEnabled ? "1" : "0") +
          (VP_collapseDescr ? "1" : "0") +
          VP_visibleTab),
                     VP_cookieDomain);
}

// sets playlistValid parameter to '0' (false) or '1' (true) in the cookie
function setPlaylistValid(isValid) {
  if (isValid) {
    setSessionCookie(VP_playlistParametersCookieName, "1", VP_cookieDomain);
  } else {
    setSessionCookie(VP_playlistParametersCookieName, "0", VP_cookieDomain);
  }
}

function getAutoplayFromCookie() {
  var plSettings = getCookie(VP_playlistSettingsCookieName);
  if (!plSettings) {  // not set in the cookie yet
    return VP_autoplayEnabled; // retun the value provided by server
  }
  if (plSettings.charAt(0) == '1') {
    return true;
  } else {
    return false;
  }
}

function flipAutoplay() {
  VP_autoplayEnabled = !VP_autoplayEnabled;
  saveAutoplay(VP_autoplayEnabled);
  refreshAutoplayLinks();
}

function setElementDisplay(elementName, displaySetting) {
  var el = ele(elementName);
  if (el && el.style && el.style) {
    el.style.display = displaySetting;
  }
}

function refreshAutoplayLinks() {
  if (VP_autoplayEnabled) {
    setElementDisplay('autoplayon', 'inline');
    setElementDisplay('autoplayoff', 'none');

  } else {
    setElementDisplay('autoplayon', 'none');
    setElementDisplay('autoplayoff', 'inline');
  }
}

/* Update the playlist based on AJAX results

  The format of the response is as follows:
  - first line is the number of results,
  - followed by playlist entries (one result on each line with a maximum
      of 12 results: first result is the current video, next 10 are the
      visible playlist entries, and the 12th result is the video following
      the last playlist result -needed for populating 'next 10' link),
  - on next line is the docid of the prev video,
  - finally the new playlist on the last line.
  There is always an empty line at the end; so in a typical case with
  all 10 playlist entries present, the response will have 16 lines.
*/
function updatePlaylist(resp) {
  var lineArr = resp.split("\r\n");
  var currentDocId = window.location.search.split("docid=")[1].split("&")[0];

  if (lineArr[0] == "0") {
    // should never be empty! Disable all links
    disablePlaylistLinks();
    ele('upnextvids').innerHTML = ""; // no playlist
    return;
  }

  // regenerate playlist HTML and show it in 'upnextvids' tab
  var plHTML = generatePlaylistHTML(lineArr, currentDocId);
  ele('upnextvids').innerHTML = plHTML;
  ele('summary').scrollTop = 0;  // scroll to the top of the playlist

  // update prev/next/prev10/next10 links
  updatePlaylistLinks(lineArr, currentDocId);
}

// disables next/prev/next10 links
function disablePlaylistLinks() {
  switchActiveDiv('nextlink', false); // disable 'next video' link
  switchActiveDiv('prevlink', false); // disable 'prev video' link
  switchActiveDiv('next10link', false); // disable 'next 10 videos' link
}

// sets the visible div for div pairs
function switchActiveDiv(linkName, isActive) {
  if (isActive) { // show active div, hide inactive div
    ele(linkName + 'active').style.display = 'inline';
    ele(linkName + 'inactive').style.display = 'none';
  } else { // hide active div, show inactive div
    ele(linkName + 'active').style.display = 'none';
    ele(linkName + 'inactive').style.display = 'inline';
  }
}

// generates the HTML code for the playlist
function generatePlaylistHTML(responseArr, currentDocId) {
  var plHTML = '<table cellpadding="4" cellspacing="0" id="upnexttable"> ' +
    '<tbody> ';
  // Playlist entries start at index 1 and goes until 'length - 4'
  // (we have prevId, new_playlist, and empty line in last 3 entries.
  // There are at most 10 playlist entries (11 items including current),
  // so don't pass index 11 (exclude 'next10 docid' at index 12 if present)
  var playlistEnd = Math.min(responseArr.length - 4, 11);
  for (var i = 1; i <= playlistEnd; i++) {
    // Each playlist entry has various fields separated by '\t'
    var eleArr = responseArr[i].split("\t");
    plHTML +='<tr style="';
    if (eleArr[0] == currentDocId) {
      plHTML += 'background-color:#E1DAE1;';
    }
    plHTML += '">';
    plHTML += generatePlaylistEntryHTML(eleArr);
  }
  plHTML += '</tbody> </table>';
  return plHTML;
}

// generates HTML code for a playlist entry
function generatePlaylistEntryHTML(eleArr) {
  // thumbnail link
  var rowHTML = '<td> <a href="' + eleArr[7] +
    '" onclick="setMyPlaylist()" rel="nofollow">' +
    '<img src="' + eleArr[1] + '" title="' + eleArr[3] +
    '" height="' + eleArr[5] + '" width="100" alt="" ' +
    'border="1"> </a> </td>';
  // title link
  rowHTML += '<td class="playlistentry" valign="top"> ' +
    '<a href="' + eleArr[7] +
    '" onclick="setMyPlaylist()" ' +
    '" rel="nofollow" ' +
    'title="' + eleArr[3] + '"> ' + eleArr[2] + '</a> <br> ';
  // provider
  rowHTML += '<span class="meta"> ';
  if (eleArr[6] != ".") { // server returns '.' if provider is invalid
    rowHTML += eleArr[6] + ' <br> ';
  }
  rowHTML += eleArr[4] + ' </span> </td> </tr> ';
  return rowHTML;
}

function updatePlaylistLinks(lineArr, currentDocId) {
  // lineArr items that will be used here:
  //  [length-3]: Prev item that precedes current playlist
  //  [length-2]: new playlist
  //  last array item is empty string.
  //  [2]: Second item in playlist, which is the 'next video'
  //    (given that 'length > 5' because last 3 items are fixed)
  //  [12]: Next item that follows current playlist
  //    (given that 'length == 16' because last 3 items are
  //     fixed and there are 11 items, [1-11], currently visible)
  var argLength = lineArr.length;

  // update 'prev video' link
  var currentLine = argLength - 3; // Index for item preceeding playlist
  var prevDocId = lineArr[currentLine];
  if (prevDocId == "0") { // prev is null
    switchActiveDiv('prevlink', false); // disable 'prev video' link
  } else {
    ele('playlistPrev').href = '/videoplay?docid=' + prevDocId +
      VP_queryParam + VP_langParam;
    switchActiveDiv('prevlink', true); // enable 'prev video' link
  }

  // update 'next video' link
  if (argLength > 5) { // playlist has at least 2 items
    currentLine = 2; // Index for second playlist item
    ele('playlistNext').href = HtmlUnescape(lineArr[currentLine].split("\t")[7]);
    switchActiveDiv('nextlink', true); // enable 'next video' link
  } else {
    switchActiveDiv('nextlink', false); // disable 'next video' link
  }

  // update 'next10 videos' link
  if (argLength == 16) { // item following playlist exists
    currentLine = 12; // Index for item following playlist
    VP_next10DocId = lineArr[currentLine].split("\t")[0];
    switchActiveDiv('next10link', true); // enable 'next 10 videos' link
  } else {
    VP_next10DocId = "0";
    switchActiveDiv('next10link', false); // disable 'next 10 videos' link
  }

  // read new playlist and update local playlist values
  // (only if the original playlist is not fixed)
  if (!isFixedPlaylist(VP_myPlaylist)) {
    currentLine = argLength - 2; // Index for new playlist
    verifyNewPlaylist(lineArr[currentLine], currentDocId, prevDocId);
  }
}

// returns true if the last docid in the playlist is 0
function isFixedPlaylist(playlist) {
  if (playlist.length >= 4) {
    var lastZeroIndex = playlist.indexOf(",0", playlist.length - 4);
    if (lastZeroIndex >= 0) {
      return true;
    }
  }
  return false;
}

// Check if current and prev docids are in the playlist,
//  add them to the beginning of the playlist if they are missing;
//  update VP_myPlaylist and VP_myPlaylistIndex accordingly
function verifyNewPlaylist(newPlaylist, currentDocId, prevDocId) {
  var plArr = newPlaylist.split(",");
  var currentIndex = -1;
  var prevIndex = -1;
  var foundBoth = 0;
  if (prevDocId == 0) { // prev is null so not in the list anyway
    foundBoth++;
  }
  for (var i = 0; i < plArr.length; i++) {
    if (currentDocId == plArr[i]) {
      currentIndex = i;
      foundBoth++;
    } else if (prevDocId == plArr[i]) {
      prevIndex = i;
      foundBoth++;
    }
    if (foundBoth == 2) {
      break;
    }
  }

  var plUpdated = true;
  var newApi = currentIndex;
  if (foundBoth == 2) {
    plUpdated = false;
  }
  if (plUpdated) { // update playlist if current or previous docId is missing
    if (prevDocId != 0) { // prev is not null
      if (prevIndex < 0) { // prevDocId is missing
        plArr[0] = prevDocId; // add prev at the beginning
        prevIndex = 0;
        if (currentIndex <= 0) { // then add current
          plArr[1] = currentDocId;
          newApi = 1;
        }
      } else if (currentIndex < 0) { // currentDocId is missing
        if (prevIndex == 0) {
          plArr[1] = currentDocId;
          newApi = 1;
        } else {
          plArr[0] = currentDocId;
          newApi = 0;
        }
      }
    } else if (currentIndex < 0) { // prev is null, currentDocId is missing
      plArr[0] = currentDocId;
      newApi = 0;
    }
    newPlaylist = plArr.join(",");
  }
  VP_myPlaylist = newPlaylist;
  VP_myPlaylistIndex = newApi;
}

function outputGrid(divname, resp) {
  var sHTML = "";
  var lineArr = resp.split("\r\n");
  var eleArr;
  var plDocids = "";
  var plFirstDocid;
  if (lineArr[0] == "0") {
    sHTML += "<br/><font size=-1>" + MSG_NO_MATCHING_VIDEOS +
             "</font>";
  } else {
    // first construct playlist (Note that lineArr[0] is
    // skipped because it contains the number of results)
    for (var i = 1; i < lineArr.length - 1; i++) {
      eleArr = lineArr[i].split("\t");
      plDocids += eleArr[0] + ",";
    }

    // create the thumbnail table
    sHTML += "<table cellpadding=0 cellspacing=3>";
    for (var i = 1; i < lineArr.length - 1; i++) {
      eleArr = lineArr[i].split("\t");
      if (i % 2 == 1) {
        sHTML += "<tr>";
      }
      sHTML +=
        "<td align=center class='standardfont' valign=top>" +
        "<a href='" + eleArr[7] +
        "' onclick='" +
        "setSessionCookie(VP_playlistCookieName, \"" + plDocids +
        "\", VP_cookieDomain); " +
        "setSessionCookie(VP_playlistIndexCookieName, -1, " +
        "VP_cookieDomain);' rel=\"nofollow\">" +
        "<img border=1 height=" + eleArr[5] + " width=100 alt=''" +
        "title=\"" + eleArr[3] + "\" src='" + eleArr[1] +
        "'></a><br>" +
        "<a href='" + eleArr[7] +
        "' onclick='" +
        "setSessionCookie(VP_playlistCookieName, \"" + plDocids +
        "\", VP_cookieDomain); " +
        "setSessionCookie(VP_playlistIndexCookieName, -1, " +
        "VP_cookieDomain);' " +
        "title=\"" + eleArr[3] + "\" rel=\"nofollow\">" + eleArr[2] + "</a><br>" +
        "<font color=green>" + eleArr[4] + "</font></td>";
      if (i == 1) {
        plFirstDocid = eleArr[0];
      }
      if (i % 2 == 0) {
        sHTML += "</tr>";
        sHTML += "<tr><td height=10></td></tr>";
      }
    }
    if (i % 2 == 0) {
      sHTML += "<td></td></tr>";
    }
    sHTML += "</table>";
  }
  ele(divname).innerHTML = sHTML;
}

/**
 * Given the dimensions of an image and the dimensions of a bounding box,
 * returns the scaled dimensions of the image so that it fits within
 * the bounding box and the aspect ratio is maintained.
 *
 * @param {Number} width The original width of the image
 * @param {Number} height The original height of the image
 * @param {Number} maxWidth The width of the bounding box
 * @param {Number} maxHeight The height of the bounding box
 * @return {Array.<Number>} An array whose first element is the constrained
 *   width and whose second element is the constrained height
 */
function constrainImageDimensions(width, height, maxWidth, maxHeight) {
  if (height == 0 || maxHeight == 0) {
    return [maxWidth, 0];
  }

  var imageAspectRatio = width / height;
  var boundingBoxAspectRatio = maxWidth / maxHeight;

  if (imageAspectRatio > boundingBoxAspectRatio) {
    return [maxWidth, Math.round(maxWidth / imageAspectRatio)];
  } else {
    return [Math.round(maxHeight * imageAspectRatio), maxHeight];
  }
}


function updateText(obj, cl, text) {
  obj.className = cl;
  obj.innerHTML = text;
}

function vpseek(time) {
  var movie = ele("VideoPlayback");
  movie.SetVariable("seekTime", time/1000);
}

function doPlay() {
  var movie = ele("VideoPlayback");
  movie.SetVariable("doPlay", true);
}

function getFullScreenWindowParams() {
  return "toolbar=no"
    + ",status=no"
    + ",resizable=yes"
    + ",scrollbars=0";
  /*
    + ",width=" + screen.availWidth
    + ",height=" + screen.availHeight
    + ",fullscreen=yes"
  */
}

function goFullscreen(videoPath, docid, fscid, time, state) {
  var timeRegex = new RegExp("&begin=[0-9]+", "i");
  var newVideoUrl = videoPath.replace(
                      timeRegex, "&begin=" + Math.floor(time * 1000));
  var w = window.open(
          "http://" + window.location.host + '/videopopup?q='
           + prepareSearchParams(newVideoUrl)
           + "&docid=" + prepareSearchParams(docid)
           + "&fscid=" + prepareSearchParams(fscid)
           + "&windowtitle="
           + prepareSearchParams(window.document.title + " - "
                                 + MSG_FULL_SCREEN),
           "GoogleVideo", getFullScreenWindowParams());
  w.focus();
}

function expand() {
  window.moveTo(0,0);
  window.resizeTo(screen.availWidth, screen.availHeight);
}

function removeScrollBars() {
  document.body.scroll = 'no';
}

function getNoCacheURL(url) {
  return url + "&ms=" + new Date().getTime();
}

function donePlaying() {
  if (!VP_autoplayEnabled) {
    return;
  }
  if (VP_waitForSale) {  // pause 10 seconds for purchasable videos
    setTimeout(startNextVideo, 10000);
  } else { // go to next video after 5 seconds
    setTimeout(startNextVideo, 5000);
  }
}

function startNextVideo() {
  // don't go to next video in any of these cases.
  if (!VP_autoplayEnabled ||
      isVisible("send") || isVisible("embed") ||
      isVisible("videopurchasediv") ||
      ele("playlistNext").href == null) {
    return;
  }
  // start playing next video...
  setMyPlaylist();
  window.location.href = ele("hidden_playlistNextAuto").href;
}

function isVisible(elementId) {
  return ele(elementId).style.display == "";
}

// set of links on the right side of the videoplay page
var VP_linksArray = [ "upnext", "details", "morefrom", "related" ];

// renders the links and tabs based on the selected tab id
function switchTab(linkId) {
  for (var i = 0; i < VP_linksArray.length; i++) {
    var el = ele(VP_linksArray[i]);
    if (el) {
      if (linkId == VP_linksArray[i]) { // this is selected link and visible tab
        ele("l" + VP_linksArray[i]).className = "nodecoration";
        showEle(el);
      } else { // make this link unselected and hide associated tab
        ele("l" + VP_linksArray[i]).className = "decorated";
        hideEle(el);
      }
    }
  }
}


var VP_windowHeight;
var VP_usableHeight;
var VP_cornerHeight;
var VP_flashPlayerHeight;
var VP_extraHeight1 = 2; // was 16
var VP_extraHeight2 = 19;

function setStyleHeightPx(id, heightPx) {
  setStyleHeightSuffix(id, heightPx, "px");
}

function setStyleHeightSuffix(id, height, suffix) {
  el = ele(id);
  if (!el || el.style == null || height < 0) {
    return;
  }
  var heightString = height.toString() + suffix;
  el.style.height = heightString;
}

function onWindowResize() {
  if (!(VP_windowHeight = window.innerHeight)) {
    if (!(VP_windowHeight = document.documentElement.clientHeight)) {
      VP_windowHeight = document.body.clientHeight;
    }
  }

  VP_usableHeight = VP_windowHeight - ele("playvideoblock").offsetTop;
  VP_flashPlayerHeight = VP_usableHeight - ele("flashobjectplaceholder").offsetTop;

  setStyleHeightPx("playvideoblock", VP_usableHeight);
  setStyleHeightPx("flashobjectplaceholder", VP_flashPlayerHeight);
  setStyleHeightPx("playrightblock", VP_usableHeight);
  setStyleHeightPx("summary", VP_usableHeight - VP_extraHeight1);

  VP_cornerHeight =
    VP_usableHeight - ele("abovecorner").offsetHeight - VP_extraHeight2;

  setStyleHeightPx("corner", VP_cornerHeight);

  if (this['onWindowResizeExtra']) {
    onWindowResizeExtra();
  }
}

function insertHtmlInEle(newHtml, eleName) {
  var newEle = document.createElement('div');
  ele(eleName).appendChild(newEle);
  newEle.innerHTML = newHtml;
}

function hashTextToTime() {
  var hashText = document.location.hash.substring(1);
  var hashTime = 0;
  var temp;
  if (hashText.indexOf('h') != -1) {
    temp = hashText.split('h');
    hashTime = (temp[0] * 60 * 60);
    hashText = temp[1];
  }
  if (hashText.indexOf('m') != -1) {
    temp = hashText.split('m');
    hashTime = (temp[0] * 60) + hashTime;
    hashText = temp[1];
  }
  if (hashText.indexOf('s') != -1) {
    temp = hashText.split('s');
    hashTime = (temp[0] * 1) + hashTime;
  } else {
    hashTime = (hashText * 1) + hashTime;
  }
  return hashTime;
}

function monitorDivOffset() {
  var el = ele('playvideoblock');
  if (el) {
    if (VP_divOffset != el.offsetTop || el.clientHeight < el.scrollHeight) {
      VP_divOffset = el.offsetTop;
      onWindowResize();
    }
  }
  var hashTime = hashTextToTime();
  if (hashTime != VP_hashPos) {
    VP_hashPos = hashTime;
    vpseek(VP_hashPos * 1000);
  }
}

function handleSharePanelClick() {
  var thedocid = window.location.search.split("docid=")[1].split("&")[0];

  if (isVisible('sharelinks')) {
    hideEle(ele('sharelinks'));
    hideEle(ele('send'));
    hideEle(ele('embed'));
    sendRequest(getNoCacheURL("/videostats?shareclick=close&docid=" + thedocid + "&frame=share"));
  } else {
    showEle(ele('sharelinks'));
    sendRequest(getNoCacheURL("/videostats?shareclick=open&docid=" + thedocid + "&frame=share"));
  }
}

function handleEmbedHTMLClick() {
  var thedocid = window.location.search.split("docid=")[1].split("&")[0];

  ele('lembed').className = 'nodecoration';
  ele('lsend').className = 'decorated';
  hideEle(ele('send'));
  showEle(ele('embed'));
  sendRequest(getNoCacheURL("/videostats?shareclick=embed&docid=" + thedocid + "&frame=share"));
}

// TODO: determine if it is safe to convert to SetVariable, as
// used by doPlay()
function doPause(target) {
  var params = "targetId=" + target + "&functionName=pause";
  insertFlash("proxyflashdiv", "/proxy.swf", params);
}

function insertFlash(container, swf, params) {
  var objectAttr;
  if (isIE) {
    objectAttr = 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"';
  } else {
    objectAttr = 'data="' + swf + '"';
  }

  ele(container).innerHTML = '<object ' + objectAttr +
      ' width="1" height="1" id="VideoDataStore" align="middle">' +
      '<param name="movie" value="' + swf + '" />' +
      '<param name="quality" value="best" />' +
      '<param name="bgcolor" value="#ffffff" />' +
      '<param name="scale" value="noScale" />' +
      '<param name="wmode" value="window" />' +
      '<param name="salign" value="TL" />' +
      '<param name="FlashVars" ' +
             'value="' + params + '" />' +
    '</object>';
}

// generate subtitle state argument for flash html code
function getSubtitleArgForFlash() {
  if (!VP_subtitleEnabled) {
  	return "";
  } else {
  	return "&subtitle=" + (VP_subtitleOn? "on" : "off");
  }
}

// This function accepts calls from flash player
function DoFSCommand(command, args) {
  if (command == "subtitleUpdate") {
    var arg_list = args.split(",");
    VP_subtitleEnabled = arg_list[0] == "true"? true : false;
    VP_subtitleOn = arg_list[1] == "true"? true : false;
  }
}

// Redirect a request to videohosted to the landing page if it is 
// opened in the top window.
function reloadWithFrameIfNeeded(target_url) {
  // We need "try" here as we won't have permission to access "top" 
  // if it is not our site.
  try { 
    if (top == window) {
      window.location.replace(target_url);
    }
  } catch (e) {
    // "top" is not us; do nothing.
  }
}
