function FlashRequest(status, args) {
  if ((status == "goFullscreen")
      || (status == "donePlaying")
      || (status == "stateChanged")
      || (status == "beginScrub")
      || (status == "endScrub")) {
    if (this[status]) {
      var argvector = eval('[' + args + ']');
      this[status].apply(this, argvector);
    }
  } else if (status == "clickVideo") {
    doThumbPreviewClick();
  }
}

function doThumbPreviewClick() {
  var element = ele("thumbflashpreview");
  if (!element || typeof(element) == "undefined") {
    return;
  }
  var candidates = element.parentNode.parentNode.childNodes;
  stopflashpreview();
  for (var x = 0 ; x < candidates.length; x++ ) {
    if (candidates[x].nodeName == "A") {
      var url = candidates[x].href;
      if (url.indexOf("http://")==0) {
        var target = candidates[x].target;
        if (target == "") {
          target = "_self";
        }
        window.open(url, target);
        return;
      }
    }
  }
}

function setCookie(cookieName, newValue) {
  var expDate = new Date();
  expDate.setYear(expDate.getFullYear() + 1);
  document.cookie = cookieName + "=" + newValue + 
    "; expires=" + expDate.toGMTString();
}

// sets a session cookie (expiration date is not set)
function setSessionCookie(cookieName, newValue, cookieDomain) {
  document.cookie = cookieName + "=" + encodeURIComponent(newValue) + 
    "; domain=" + cookieDomain ;
}

// sets a permanent cookie that lives accross sessions
function setPermanentCookie(cookieName, newValue, cookieDomain) {
  var expDate = new Date();
  expDate.setYear(expDate.getFullYear() + 1);
  document.cookie = cookieName + "=" + encodeURIComponent(newValue) +
    "; domain=" + cookieDomain + "; expires=" + expDate.toGMTString();
}

// deletes cookie by setting expiration in the past
function deleteCookie(cookieName, cookieDomain) {
  var expDate = new Date();
  expDate.setYear(expDate.getFullYear() - 1);
  document.cookie = cookieName + "=0; domain=" + cookieDomain +
    "; expires=" + expDate.toGMTString();
}

function getCookie(cookieName) {
  // cookies are separated by semicolons
  var dCookie = document.cookie.split(/\s*;\s*/);
  var value = null;
  for (var i = 0; i < dCookie.length; i++) {
    // a name/value pair is separated by '='
    var pair = dCookie[i].split("=");
    if (cookieName == pair[0]) { 
      value = decodeURIComponent(pair[1]);
      break;
    }
  }
  return value;
}

function setChildVisibilityWithNodeName(element, name, show) {
	for (var x = 0 ; x < element.childNodes.length; x++ ) {
		if (element.childNodes[x].nodeName == name) {
			setEleVisibility(element.childNodes[x], show);
		}
	}
}

function stopflashpreview() {
	var element = ele("thumbflashpreview");
	if ((element) && typeof(element)!= "undefined") {
		var parent = element.parentNode.parentNode;
		removeEle(element.parentNode);
		setChildVisibilityWithNodeName(parent, "A", true);
	}
}

function switchflash(element, videosourceurl, width, wmode) {
	stopflashpreview(); 
        flash7OrHigher(true);
	
	var newhtml = 
		'<div id="thumbflashpreview">' 
 		/*+ '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" ' 
 		+ ' codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0"' 
 		+ ' width="100%" height="100%" id="VideoPlayback" align="middle">'
 		+	' <param name="allowScriptAccess" value="sameDomain" />'
 		+	' <param name="movie" value="' + videosourceurl + '&playerMode=mini&eovMessage=Click%20here%20to%20watch%20entire%20video" />'
 		+	' <param name="quality" value="best" />'
 		+	' <param name="bgcolor" value="#ffffff" />'*/
 		+	' <embed wmode="' + wmode + '" src="' + videosourceurl + '&playerMode=mini&eovMessage=Click%20here%20to%20watch%20entire%20video" ' 
 		+	'	 width="' + width + '"' 
		+ '  height="' + Math.round(width*0.75) + '"'
		+ '  name="VideoPlayback"' 
    + '	 type="application/x-shockwave-flash"' 
 		+	'  pluginspage="http://www.macromedia.com/go/getflashplayer" /> '
 		//+ ' </object>'
 	  +'</div>';


	var newEle = document.createElement('div');
	newEle.innerHTML = newhtml;

	setChildVisibilityWithNodeName(element.parentNode, "A", false);
	element.parentNode.appendChild(newEle);

	return false;

}

var isIE  = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;

function flash7OrHigher(checkIE) {
  if (!checkIE && isIE && isWin) return;

  for (i=25;i>0;i--) {
    if (isIE && isWin && !isOpera) {
      versionStr = VBGetSwfVer(i);
    } else {
      versionStr = navigator.plugins["Shockwave Flash"].description.substring(16,19);
    }
    if (versionStr == -1) {
      displayFlashErrorAndNavigate();
      return false;
    } else if (versionStr != 0) {
      if(isIE && isWin && !isOpera) {
	tempArray = versionStr.split(" ");
	tempString = tempArray[1];
	versionArray = tempString .split(",");
      } else {
	versionArray = versionStr.split(".");
      }
      versionMajor = versionArray[0];
      if(versionMajor < 7)  {
        displayFlashErrorAndNavigate();
        return false;
      } else {
        return true;
      }
    }
  }
  displayFlashErrorAndNavigate();
  return false;  
}

function displayFlashErrorAndNavigate() {
  if(confirm("You need Flash 7 or higher to watch videos.")) {
    window.location = "http://www.macromedia.com/go/getflashplayer";
  }
}

function ele(eleName) {
 if(document.getElementById && document.getElementById(eleName)) {
    return document.getElementById(eleName);
  }
  else if (document.all && document.all(eleName)) {
    return document.all(eleName);
  }
  else if (document.layers && document.layers[eleName]) {
    return document.layers[eleName];
  } else {
    return false;
  }
}

function hideEle(el) {
  el.style.display = "none";
}

function showEle(el) {
  el.style.display = "";
}

function setEleVisibility(el, vis) {
  if (vis) {
    showEle(el);
  } else {
    hideEle(el);
  }
}

function toggleVisibility(eleName) {
  var el = ele(eleName);
  if (!el) {
    return true;
  } else if (cascadedstyle(el, "display", "display") == "block" ||
             cascadedstyle(el, "display", "display") == "inline" ) {
    el.className = "invisible";
  } else {
    el.className = "visible";
  }
}

function cascadedstyle(ele, cssproperty, csspropertyNS){
  if (ele.currentStyle) {
    return ele.currentStyle[cssproperty];
  } else if (window.getComputedStyle) {
    var elestyle = window.getComputedStyle(ele, "");
    return elestyle.getPropertyValue(csspropertyNS);
  }
}


function removeEle(el) {
  el.parentNode.removeChild(el);
}


function prepareSearchParams(p) {
  if (typeof(this.encodeURIComponent)!="undefined") {
    p = encodeURIComponent(p);
  } else {
    p = escape(p);
  }
  var re = /(%20)+/g;
  return p.replace(re, "+");
}

function searchthisshow(thequery) {
  var thedocid = window.location.search.split("docid=")[1].split("&")[0];
  window.location = "/videopreview?q=" + prepareSearchParams(thequery) + "&docid=" + thedocid;
  return false;
}

function pvsearch(thequery) {
  window.location = "/videosearch?q=" + prepareSearchParams(thequery);
  return false;
}


function rtclk(e) {
  if (document.all && !document.getElementById) {
    if (event.button == 2) 
      return false;} 
  else if (document.layers) {
    if (e.which == 2 || e.which == 3) {
      return false;
    }
  }
} 

function dropdownNav(sel) {
  var dest = sel.options[sel.selectedIndex].value;
  if (dest) location.href = dest;
}

function install_rtclk() {
  if (document.layers)
    document.captureEvents(Event.MOUSEDOWN);
  document.onmousedown = rtclk;
  document.oncontextmenu = function() {return false;}
}


function numberFilter(evt) {
  var charCode;
  if (navigator.appName == "Microsoft Internet Explorer") {
    charCode = evt.keyCode;
  } else {
    charCode = evt.charCode;
  }
  return evt.metaKey || 
		(charCode < 31 
		 ||  (charCode > 47 && charCode < 58) 
		 || (charCode > 63231 && charCode < 63236));
}

function recordFlaggedVideo(docId, cookieName, cookieDomain) {
  var cookieValue = getCookie(cookieName);
  if (cookieValue == null) {
    cookieValue = docId;
  } else {
    // check for dup
    var ids = cookieValue.split(":");
    for (var i = 0; i < ids.length; ++i) {
      if (ids[i] == docId) {
        return;
      }
    }
    cookieValue = cookieValue + ":" + docId;
  }
  setPermanentCookie(cookieName, cookieValue, cookieDomain);
}

// AJAX stuff
function getAjaxRequestType() {
  var xmlhttp;
  var activeXType;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject(activeXType = "Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject(activeXType = "Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return activeXType;
}

var ieActiveXType = getAjaxRequestType();

function createAjaxRequest() {
  var xmlhttp;
  
  if (ieActiveXType) {
    xmlhttp = new ActiveXObject(ieActiveXType);
  } else {
    xmlhttp = new XMLHttpRequest();
  }
  return xmlhttp;
}

// if you do a GET, set data, mime to be null or don't pass them
// callback should have the following prototype
//
//      function aCallBack(req, success, url, originalData, opaqueId)
// url, originalData is to make it easy to properly identify to which request this response belongs to.
function sendAjaxRequest(url, callback, opt_data, opt_opaqueId, opt_mime) {

  // use a new private instance for every request
  var req = createAjaxRequest();
  var method = 'GET';
  if (opt_data) {
    method = 'POST';
    if (!opt_mime) {
      opt_mime = 'application/x-www-form-urlencoded';
    }
  }
  req.open(method, url, true);
  if (opt_data && opt_mime) {
    req.setRequestHeader('Content-Type', opt_mime);    // must be called after open
  }
  // stick the instance data into the scope of the function literal 
  req.onreadystatechange = function() {
    if (req.readyState == 4) {
      callback(req, req.status && req.status == 200, url, opt_data, opt_opaqueId);
    }
  };
  req.send(opt_data);
}

function escapeHtml(str) {
  return str.replace(/&/g, '&amp;')
            .replace(/</g, '&lt;')
            .replace(/>/g, '&gt;')
            .replace(/\"/g, '&quot;');
}

function newLine2Br(str) {
  return str.replace(/(\r\n|\r|\n)/g, '<br/>');
}

// XML Element creation
// set parent=doc to append to doc
// set null value if sub elements
function appendElement(doc, parent, tag, value) {
  var elem = doc.createElement(tag);
  if (value) {
    elem.appendChild(doc.createTextNode(value));
  }
  parent.appendChild(elem);
  return elem;
}

// Reading XML Element value 
function getElementValue(parentElement, tag) {
  var list = parentElement.getElementsByTagName(tag);
  if (!list || list.length == 0) {
    return null;
  }
  list = list[0].childNodes;
  if (!list || list.length == 0) {
    return null;
  }
  // supporting single child node only
  return list[0].nodeValue;
}

function getPrefCookie() {
  if (!getCookie('PREF')) {
    // extract the .google.xx or .google.xxx domain
    var url = document.location.toString();
    var result = url.match(/https?:\/\/[\w\.]*(\.google\.\w{2,5})(:\d{1,5})?\/?/i);
    if (result) {
      url = 'http://www' + result[1] + '/gen_204';
      var fakeImg = new Image();
      fakeImg.src = url;
    }
  }
}


