/**
 * Copyright (C) 2005 Brightcove, Inc.  All Rights Reserved.  No
 * use, copying or distribution of this work may be made except in
 * accordance with a valid license agreement from Brightcove, Inc.
 * This notice must be included on all copies, modifications and
 * derivatives of this work.
 *
 * Brightcove, Inc MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT
 * THE SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED,
 * INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
 * NON-INFRINGEMENT. BRIGHTCOVE SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED
 * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS
 * SOFTWARE OR ITS DERIVATIVES.
 *
 * "Brightcove" is a trademark of Brightcove, Inc.
 **/

//functions used by the Console and BC Admin
var searchString = URLEncode( self.location.search );

function changeTitle( pTitle ) {
	document.title = pTitle;
}

function openFilePicker(callback) {
	// reset the selected file on each invocation
  document.frames['uploadframe'].document.forms.upload.reset();
	document.frames['uploadframe'].document.forms.upload.file.click();
	while(document.frames['uploadframe'].document.forms.upload.file == "") {
		setTimeout(100)
	}

	callbackFlash(callback, new String(document.frames['uploadframe'].document.forms.upload.file.value));
}

function flashFocus() {
  var fo = document.flashObj;
  if (fo == null) fo = document.embeds["flashObj"];
  if (fo == null) fo = document.getElementById("flashObj");

  if (fo != null) {
    fo.focus();
  }
}

// javascript escape is bad, bad, bad
function URLEncode(pString) {
  return escape(pString).
      replace(/\+/g, '%2B').
      replace(/\"/g,'%22').
      replace(/\'/g, '%27').
      replace(/\//g,'%2F');
}

function createCookie(pName, pValue, pDays)
{
  var c = pName + "=" + pValue;
  if (pDays) {
    var date = new Date();
    date.setTime(date.getTime()+(pDays*24*60*60*1000));
    c = c + "; expires="+date.toGMTString();
  }
  c = c + "; path=/";
  
  // share our cookies across the domain
  var domain = location.hostname;
  if (domain.indexOf('.') > -1) {
    // we need .brightcove.com for single-sign on
    domain = domain.substr(domain.indexOf('.'));  
    c = c + "; domain=" + domain;
  }
  
  var secure = location.protocol == 'https:';
  if(secure) {
	  c += "; secure";
  }
  
  document.cookie = c;
}

function readCookie(pName)
{
  var key = pName + "=";
  var vals = document.cookie.split(';');
  for (var i=0; i < vals.length; i++) {
    var val = vals[i];
    while (val.charAt(0)==' ') {
      val = val.substring(1, val.length);
    }
    if (val.indexOf(key) == 0) {
      return val.substring(key.length, val.length);
    }
  }
  return null;
}

function eraseCookie(pName){
  createCookie(pName,"",-1);
}

//write out embed tag for console or admin console
function createFlexApp(swfName){
	//win require flash 7/mac require flash 8
	var requiredMajorVersion = 8;		
	var requiredMinorVersion = 0;
	var requiredRevision = 0;
	var hasRightVersion = DetectFlashVer(requiredMajorVersion,requiredMinorVersion,requiredRevision);
	
	if(hasRightVersion) { 		
		var servicesURL = escape("http://console.brightcove.com/services");
                var servicesSecureURL = escape("https://console.brightcove.com/services");
		var cdnURL = escape("http://admin.brightcove.com");
		var bcAdServerURL = escape("@@BC_ADSERVER_URL@@");
		var browser = escape(navigator.userAgent);
		var authToken = URLEncode( readCookie("BC_TOKEN") );
		var allowPublisherReg = false;
		var searchString = URLEncode( self.location.search );
		var branding = readCookie("COBRAND");

		document.write("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0' width='100%' height='100%'");
		document.write("id='flashObj'");
		document.write(">");
		document.write("  <param name='flashvars' value='servicesURL="+servicesURL+"&servicesSecureURL="+servicesSecureURL+"&cdnURL="+cdnURL+"&bcAdServerURL="+bcAdServerURL+"&browser="+browser+"&authToken="+authToken+"&allowPublisherReg="+allowPublisherReg+"&searchString="+searchString+"&branding="+branding+"&'>");
		document.write("  <param name='src' value='" + swfName + "'>");
		document.write("  <param name='allowFullScreen' value='true'>");
		document.write("  <param name='allowScriptAccess' value='always'>");
		document.write("  <embed pluginspage='http://www.macromedia.com/go/getflashplayer' width='100%' height='100%'");
		document.write("    flashvars='servicesURL="+servicesURL+"&servicesSecureURL="+servicesSecureURL+"&cdnURL="+cdnURL+"&browser="+browser+"&authToken="+authToken+"&allowPublisherReg="+allowPublisherReg+"&searchString="+searchString+"&branding="+branding+"&'");
		document.write("    src='" + swfName + "' allowFullScreen='true'");
		document.write("    name='flashObj'");
		document.write("  />");
		document.write("</object>");
		document.write("<br><iframe src='upload.html' name='uploadframe' frameborder='0' scrolling='no' width='0' height='0'></iframe></br>");	
	} else {  // flash is too old or we can't detect the plugin 
		document.write("<table width='100%' height='100%' border='0' bgcolor='#838b90'>");
		document.write("<tr><td align='center' valign='middle'>");
		document.write("<a href='http://www.macromedia.com/go/getflashplayer/' target='_blank'><img src='images/upgrade_flash_player.gif' alt='Get Flash Player' width='314' height='200' border='0'></a>");
		document.write("</td></tr></table>");  			
   }       
}

/**
 * If the user attempts to close, refresh, or navigate the browser window during
 * an upload, warn the user that the uploads will be cancelled.
 */
function checkForUploadInProgress(event) {
    var warning = null;
    var fxControl = document["flashObj"] || window["flashObj"];
    if (typeof fxControl.getUploadInProgressWarning == "function") {
        warning = fxControl.getUploadInProgressWarning();
    }
    if (warning != null) {
        return warning;
    }
    return;
}
window.onbeforeunload = checkForUploadInProgress;

