/* !!NOTOKENS!!
   $Id: global.js,v 1.56 2009/07/23 00:22:03 mleite Exp $
   $Source: /home/np/shared/filmcom/static/js/global.js,v $
*/
/**** Define global variables ****/
var loaded = false;
var refreshRate = 7200000; //// Milliseconds between refreshes.  Default is 2 hours, to override, use ?refreshtimeout=5000
var navCookie = "realNav"; //// Name of cookie used for remembering state.
var navCookieLife = 360; //// Days for the nav cookie to live

var obj = getArgs();

function preloadImages() {
  getUserMastheadImage();
  if (document.images) {
    signin_over = newImage(staticBaseURL + '/images/buttons/login/header/signIn_over.gif');
    register_over = newImage(staticBaseURL + '/images/buttons/login/header/newUser_over.gif');
    myaccount_over = newImage(staticBaseURL + '/images/buttons/login/header/myAccount_over.gif');
    signout_over = newImage(staticBaseURL + '/images/buttons/login/header/logOut_over.gif');
    updateButton_over = newImage(staticBaseURL + '/images/buttons/login/update_over.gif');
    iagreeButton_over = newImage(staticBaseURL + '/images/buttons/login/iagree_over.gif');
    signinButton_over = newImage(staticBaseURL + '/images/buttons/login/signin_over.gif');
    registerButton_over = newImage(staticBaseURL + '/images/buttons/login/register_over.gif');
    submit_comment_over = newImage(staticBaseURL + '/images/buttons/submit_comment_over.gif');
    tabBkg_over = newImage(staticBaseURL + '/images/navButtons/tab_bg_over.gif');
    tabBkgArrow = newImage(staticBaseURL + '/images/navButtons/tab_bg_over_arrow.gif');
    search = newImage(staticBaseURL + '/images/buttons/search.gif');
    preloadFlag = true;
  }
}

//enables/disables submit button for header search
//depending on whether there is a value in the search field
function toggleSubmitButton(field,button) {
  var submitButton = document.getElementById(button);
  if (field.value == "" || field.value == null) {
    submitButton.disabled = true;
  } else {
    submitButton.disabled = false;
  }
}


function newImage(arg) {
    if (document.images) {
      rslt = new Image();
      rslt.src = arg;
      return rslt;
    }
  }
function changeImages() {
    if (document.images && (preloadFlag)) {
      for (var i=0; i<changeImages.arguments.length; i+=2) {
        document[changeImages.arguments[i]].src = changeImages.arguments[i+1];
      }
    }
  }


function showAdCookie(name,value,days) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i=0;i < ca.length;i++) {
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) {
          var cookieMatch = true;
        }
    }
    if (cookieMatch) {
      eraseCookie(name);
    }
    else {
      createCookie(name,value,days);
    }
  }

function openMediaPlaybackWindow (url,site){  // this is a deprecated function, was used when the media playback was
                                              // a pop-up window. Keeping the function here for old stories that used it.
                                              // this opens the url in the same window now.
  var theSite = site;
  window.location=url;
}

function divContentCopy(divTo,divFrom){
  div1 = document.getElementById(divFrom);
  div2 = document.getElementById(divTo);
  if (div1 && div2){
    div2.innerHTML = div1.innerHTML;
  }
}

function trySubmitRequest(){
  if (document.getElementById('allRatings')){
    submitRequest();
  }
}

function setPrefix()
  {
    if(!hasRealPlayer()){
        document.getElementById('noPlayer').style.display="block";
        document.getElementById('player').style.display="none";
        checkPlugin("RealPlayer Version Plugin");
    } else {
      document.getElementById('noPlayer').style.display="none";
      document.getElementById('player').style.display="block";

      if (majorVersion >= 11){
        fsprefix = "real";
      } else if(isObject(navigator.plugins["RealPlayer Version Plugin"]) && version <= '6.0.11.9000') {
        fsprefix = "real";
      }else{
        fsprefix= "real_one";
      }
      document.playFullScreen.src = staticBaseURL + "/images/player/controls/" + fsprefix + "_off.gif";

      if(navigator.userAgent.indexOf('Mac') != -1){
        fsprefix = "mac";
      }
      else if(checkPlugin("RealOne Player Version Plugin")){
        fsprefix= "real_one";
      }
    }
  }


// Global tab Navingation this code controls the main Navigation roll-over dropdowns

  function activeOver(divId,childDivId){
    var divObj = document.getElementById(divId);
    var childDivObj = document.getElementById(childDivId);
    if (document.getElementById(divId + "_button")){
      var linkObj = document.getElementById(divId + "_button");
      linkObj.style.color = "#333333";
    }
    divObj.style.backgroundImage = 'url("' + staticBaseURL + '/images/navButtons/tab_bg_over.gif")';
    divObj.style.backgroundRepeat = "repeat-x";
    divObj.style.color = "#333333";
    childDivObj.style.backgroundImage = 'url("' + staticBaseURL + '/images/navButtons/tab_bg_over_arrow.gif")';
    childDivObj.style.backgroundRepeat = "no-repeat";
    childDivObj.style.backgroundPosition = "center";
    childDivObj.style.backgroundColor = "transparent";
    document.getElementById(divId + '_subMenu').style.display="block";
  }

  function inActiveOut(divId,childDivId){
    var divObj = document.getElementById(divId);
    var childDivObj = document.getElementById(childDivId);
    divObj.style.backgroundImage = "none";
    divObj.style.backgroundRepeat = "repeat-x";
    divObj.style.color = "#5A5A5A";
    childDivObj.style.backgroundImage = "none";
    document.getElementById(divId + '_subMenu').style.display="none";

  }
 function activeOut(divId,childDivId){
    var divObj = document.getElementById(divId);
    var childDivObj = document.getElementById(childDivId);
    if (document.getElementById(divId + "_button")){
      var linkObj = document.getElementById(divId + "_button");
      linkObj.style.color = "#FFFFFF";
    }
    divObj.style.backgroundImage = 'url("' + appResourseUrl + '/images/navButtons/tab_bg_on.gif")';
    divObj.style.backgroundRepeat = "repeat-x";
    divObj.style.color = "#FFFFFF";
    childDivObj.style.backgroundImage = "none";
    document.getElementById(divId + '_subMenu').style.display="none";

  }

  function createCookie(name,value,days) {
    var expires = "";
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      expires = "; expires="+date.toGMTString();
    }
    document.cookie = name+"="+value+expires+"; path=/";
  }

  function eraseCookie(name) {
    createCookie(name,"",-1);
  }

  function goToMainWindow(theURL) {
    var mainWin = window.open(theURL,'main');
    mainWin.focus();
  }

var majorVersion;
var hasplayer = false;
var version = 0;
var showGuide = false;

function isObject(type){
  return ( "undefined" != typeof(type) );
}

function unpackVersionNumber(n)
{
  return "" + (n >> 28) + "." +
    ((n & 0xFF00000) >> 20) + "." +
    ((n & 0xFF000) >> 12) + "." +
    ( n & 0xFFF);
}

function winIE5upPlyrDetect(){
  var player;

  try{
    player = new ActiveXObject("rmocx.RealPlayer G2 Control.1");
    playerVersion = (player.GetVersionInfo());
  }
  catch(e){
  }

  return new String(isObject(player));
}

function checkPlugin(name){
  plugin = navigator.plugins[name];
  if(isObject(plugin)){
    playerVersion = plugin.description;
    return true;
  }
  return false;
}

function checkFuzzyPluginVersion() {
  if ( arguments == null || arguments.length <= 0 )
    return false;
  var plugins = navigator.plugins;
  if ( plugins != null && plugins.length > 0 ) {
    for(i=0; i<plugins.length; i++) {
      var name = " " + plugins[i].name;
      var desc = " " + plugins[i].description;
      var allFound = true;;
      for(j=0; j<arguments.length; j++) {
        if ( name.indexOf(" " + arguments[i]) < 0
            && desc.indexOf(" " + arguments[i]) < 0 ) { // not found
            allFound = false;
            break;
        }
      }
      if ( allFound ) {
        var versRX = /[0-9]+[\.][0-9]+[\.][0-9]+[\.][0-9]+/;
        playerVersion = desc.match(versRX);
        return true;
      }
    }
  }
  return false;
}

function pluginDetect(){
    var result = (checkPlugin("RealPlayer Version Plugin"))
                ||
                 (checkPlugin("RealOne Player Version Plugin"));
    if ( result ) {
      return result;
    }
    return checkFuzzyPluginVersion("RealPlayer","G2", "Plug-In");
}

function mimeTypeDetect(){
  return (
    isObject(navigator.mimeTypes)
    &&
    isObject(navigator.mimeTypes["audio/x-pn-realaudio-plugin"])
    );
}

function isWinIE5plus(){
  var result = false;
  var uaLower = navigator.userAgent.toLowerCase();
  if(uaLower.indexOf("windows") >=0 && uaLower.indexOf("msie")>=0){
    var versRX = /msie\s+[5-9]/;
    result = versRX.test(uaLower);
  }
  return result;
}

function hasRealPlayer(){
  if( isWinIE5plus() ){
    return (winIE5upPlyrDetect() == "true");
  }else{
    return (pluginDetect() || mimeTypeDetect());
  }
}


/****
    Get the arguments from the query string &
    put them into an object of name/value pairs.
    Accessible by obj.name=value
****/


/**
 * SWFObject v1.4.4: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept == "undefined") var deconcept = new Object();
if(typeof deconcept.util == "undefined") deconcept.util = new Object();
if(typeof deconcept.SWFObjectUtil == "undefined") deconcept.SWFObjectUtil = new Object();
deconcept.SWFObject = function(swf, id, w, h, ver, c, useExpressInstall, quality, xiRedirectUrl, redirectUrl, detectKey){
  if (!document.getElementById) { return; }
  this.DETECT_KEY = detectKey ? detectKey : 'detectflash';
  this.skipDetect = deconcept.util.getRequestParameter(this.DETECT_KEY);
  this.params = new Object();
  this.variables = new Object();
  this.attributes = new Array();
  if(swf) { this.setAttribute('swf', swf); }
  if(id) { this.setAttribute('id', id); }
  if(w) { this.setAttribute('width', w); }
  if(h) { this.setAttribute('height', h); }
  if(ver) { this.setAttribute('version', new deconcept.PlayerVersion(ver.toString().split("."))); }
  this.installedVer = deconcept.SWFObjectUtil.getPlayerVersion();
  if(c) { this.addParam('bgcolor', c); }
  var q = quality ? quality : 'high';
  this.addParam('quality', q);
  this.setAttribute('useExpressInstall', useExpressInstall);
  this.setAttribute('doExpressInstall', false);
  var xir = (xiRedirectUrl) ? xiRedirectUrl : window.location;
  this.setAttribute('xiRedirectUrl', xir);
  this.setAttribute('redirectUrl', '');
  if(redirectUrl) { this.setAttribute('redirectUrl', redirectUrl); }
  }
  deconcept.SWFObject.prototype = {
  setAttribute: function(name, value){
    this.attributes[name] = value;
  },
  getAttribute: function(name){
    return this.attributes[name];
  },
  addParam: function(name, value){
    this.params[name] = value;
  },
  getParams: function(){
    return this.params;
  },
  addVariable: function(name, value){
    this.variables[name] = value;
  },
  getVariable: function(name){
    return this.variables[name];
  },
  getVariables: function(){
    return this.variables;
  },
  getVariablePairs: function(){
    var variablePairs = new Array();
    var key;
    var variables = this.getVariables();
    for(key in variables){
      variablePairs.push(key +"="+ variables[key]);
    }
    return variablePairs;
  },
  getSWFHTML: function() {
    var swfNode = "";
    if (navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) { // netscape plugin architecture
      if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "PlugIn"); }
      swfNode = '<embed type="application/x-shockwave-flash" src="'+ this.getAttribute('swf') +'" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'"';
      swfNode += ' id="'+ this.getAttribute('id') +'" name="'+ this.getAttribute('id') +'" ';
      var params = this.getParams();
       for(var key in params){ swfNode += [key] +'="'+ params[key] +'" '; }
      var pairs = this.getVariablePairs().join("&");
       if (pairs.length > 0){ swfNode += 'flashvars="'+ pairs +'"'; }
      swfNode += '/>';
    } else { // PC IE
      if (this.getAttribute("doExpressInstall")) { this.addVariable("MMplayerType", "ActiveX"); }
      swfNode = '<object id="'+ this.getAttribute('id') +'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+ this.getAttribute('width') +'" height="'+ this.getAttribute('height') +'">';
      swfNode += '<param name="movie" value="'+ this.getAttribute('swf') +'" />';
      var params = this.getParams();
      for(var key in params) {
       swfNode += '<param name="'+ key +'" value="'+ params[key] +'" />';
      }
      var pairs = this.getVariablePairs().join("&");
      if(pairs.length > 0) {swfNode += '<param name="flashvars" value="'+ pairs +'" />';}
      swfNode += "</object>";
    }
    return swfNode;
  },
  write: function(elementId){
    if(this.getAttribute('useExpressInstall')) {
      // check to see if we need to do an express install
      var expressInstallReqVer = new deconcept.PlayerVersion([6,0,65]);
      if (this.installedVer.versionIsValid(expressInstallReqVer) && !this.installedVer.versionIsValid(this.getAttribute('version'))) {
        this.setAttribute('doExpressInstall', true);
        this.addVariable("MMredirectURL", escape(this.getAttribute('xiRedirectUrl')));
        document.title = document.title.slice(0, 47) + " - Flash Player Installation";
        this.addVariable("MMdoctitle", document.title);
      }
    }
    if(this.skipDetect || this.getAttribute('doExpressInstall') || this.installedVer.versionIsValid(this.getAttribute('version'))){
      var n = (typeof elementId == 'string') ? document.getElementById(elementId) : elementId;
      n.innerHTML = this.getSWFHTML();
      return true;
    }else{
      if(this.getAttribute('redirectUrl') != "") {
        document.location.replace(this.getAttribute('redirectUrl'));
      }
    }
    return false;
  }
}

/* ---- detection functions ---- */
deconcept.SWFObjectUtil.getPlayerVersion = function(){
  var PlayerVersion = new deconcept.PlayerVersion([0,0,0]);
  if(navigator.plugins && navigator.mimeTypes.length){
    var x = navigator.plugins["Shockwave Flash"];
    if(x && x.description) {
      PlayerVersion = new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/, "").replace(/(\s+r|\s+b[0-9]+)/, ".").split("."));
    }
  }else{
    // do minor version lookup in IE, but avoid fp6 crashing issues
    // see http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
    try{
      var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
    }catch(e){
      try {
        var axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
        PlayerVersion = new deconcept.PlayerVersion([6,0,21]);
        axo.AllowScriptAccess = "always"; // throws if player version < 6.0.47 (thanks to Michael Williams @ Adobe for this code)
      } catch(e) {
        if (PlayerVersion.major == 6) {
          return PlayerVersion;
        }
      }
      try {
        axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
      } catch(e) {}
    }
    if (axo != null) {
      PlayerVersion = new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
    }
  }
  return PlayerVersion;
}
deconcept.PlayerVersion = function(arrVersion){
  this.major = arrVersion[0] != null ? parseInt(arrVersion[0]) : 0;
  this.minor = arrVersion[1] != null ? parseInt(arrVersion[1]) : 0;
  this.rev = arrVersion[2] != null ? parseInt(arrVersion[2]) : 0;
}
deconcept.PlayerVersion.prototype.versionIsValid = function(fv){
  if(this.major < fv.major) return false;
  if(this.major > fv.major) return true;
  if(this.minor < fv.minor) return false;
  if(this.minor > fv.minor) return true;
  if(this.rev < fv.rev) return false;
  return true;
}
/* ---- get value of query string param ---- */
deconcept.util = {
  getRequestParameter: function(param) {
    var q = document.location.search || document.location.hash;
    if(q) {
      var pairs = q.substring(1).split("&");
      for (var i=0; i < pairs.length; i++) {
        if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
          return pairs[i].substring((pairs[i].indexOf("=")+1));
        }
      }
    }
    return "";
  }
}
/* fix for video streaming bug */
deconcept.SWFObjectUtil.cleanupSWFs = function() {
  if (window.opera || !document.all) return;
  var objects = document.getElementsByTagName("OBJECT");
  for (var i=0; i < objects.length; i++) {
    objects[i].style.display = 'none';
    for (var x in objects[i]) {
      if (typeof objects[i][x] == 'function') {
        objects[i][x] = function(){};
      }
    }
  }
}
// fixes bug in fp9 see http://blog.deconcept.com/2006/07/28/swfobject-143-released/
deconcept.SWFObjectUtil.prepUnload = function() {
  __flash_unloadHandler = function(){};
  __flash_savedUnloadHandler = function(){};
  if (typeof window.onunload == 'function') {
    var oldUnload = window.onunload;
    window.onunload = function() {
      deconcept.SWFObjectUtil.cleanupSWFs();
      oldUnload();
    }
  } else {
    window.onunload = deconcept.SWFObjectUtil.cleanupSWFs;
  }
}
if (typeof window.onbeforeunload == 'function') {
  var oldBeforeUnload = window.onbeforeunload;
  window.onbeforeunload = function() {
    deconcept.SWFObjectUtil.prepUnload();
    oldBeforeUnload();
  }
} else {
  window.onbeforeunload = deconcept.SWFObjectUtil.prepUnload;
}
/* add Array.push if needed (ie5) */
if (Array.prototype.push == null) { Array.prototype.push = function(item) { this[this.length] = item; return this.length; }}

/* add some aliases for ease of use/backwards compatibility */
var getQueryParamValue = deconcept.util.getRequestParameter;
var FlashObject = deconcept.SWFObject; // for legacy support
var SWFObject = deconcept.SWFObject;


/*

EXAMPLE OF FLASH SCRIPT CALL

<div id="movie_main_flash">
  You must have JavaScript enabled on your browser and<br/> the latest Flash Player for this to work properly.
</div>
<script type="text/javascript" language="JavaScript">// <![CDATA[
var myFlash = new SWFObject("http://i.real.com/assets/rn/img/9/5/0/9/11819059.swf?config=http://slideshow.real.com/?id=11617905%26application=guide%26useclick=false", "homeswf", "625", "250", "8", "#FFFFFF");
myFlash.addParam('allowScriptAccess', 'always');
myFlash.addParam('wmode', 'transparent');
myFlash.addParam('quality', 'high');
myFlash.write("movie_main_flash");
// ]]>
</script>


*/

function writePersistentCookie (CookieName, CookieValue, periodType, offset) {

  var expireDate = new Date ();
  offset = offset / 1;

  var myPeriodType = periodType;
  switch (myPeriodType.toLowerCase()) {
    case "years":
      expireDate.setYear(expireDate.getFullYear()+offset);
      break;
    case "months":
      expireDate.setMonth(expireDate.getMonth()+offset);
      break;
    case "days":
      expireDate.setDate(expireDate.getDate()+offset);
      break;
    case "hours":
      expireDate.setHours(expireDate.getHours()+offset);
      break;
    case "minutes":
      expireDate.setMinutes(expireDate.getMinutes()+offset);
      break;
    default:
      alert ("Invalid periodType parameter for writePersistentCookie()");
      break;
  }

  document.cookie = escape(CookieName ) + "=" + escape(CookieValue) + "; expires=" + expireDate.toGMTString() + "; path=/";
}

function getCookieValue (cookieName) {
  var exp = new RegExp (escape(cookieName) + "=([^;]+)");
  if (exp.test (document.cookie + ";")) {
    exp.exec (document.cookie + ";");
    return unescape(RegExp.$1);
  }
  else return false;
}

function testPersistentCookie () {
  writePersistentCookie ("testPersistentCookie", "Enabled", "minutes", 1);
  return getCookieValue("testPersistentCookie") == "Enabled";
}

var cookieErrorTxt = "Cookies need to be enabled to sign in, register and update. Please enable cookies and try again. <a href=\"http://service.real.com/filmcom/answer.html?answer=cookies\" >More Info</a>";

function cookieTest1() {
  if(testPersistentCookie()){
    document.getElementById('cookieError').style.visibility = "hidden";
    document.getElementById('cookieError').style.height = "0";
    document.getElementById('cookieError').style.padding = "0";
    document.getElementById('cookieError').style.margin = "0";
    document.getElementById('cookieError').style.border = "none";
    document.getElementById('cookieError').style.lineHeight = "0"
    if(document.getElementById('persistLogin'))
      document.getElementById('persistLogin').checked = true;
    return true;
  }else{
    document.getElementById('cookieError').style.visibility = "visible";
    document.getElementById('cookieError').style.height = "auto";
    document.getElementById('cookieError').style.padding = "10px";
    document.getElementById('cookieError').style.margin = "0 0 10px 0";
    document.getElementById('cookieError').style.border = "1px dotted #FF3300";
    document.getElementById('cookieError').style.lineHeight = "20px"
    document.getElementById('cookieError').innerHTML = cookieErrorTxt;
    if(document.getElementById('persistLogin'))
      document.getElementById('persistLogin').checked = false;
    return false;
  }
}

function cookieTest2(){
  if (!testPersistentCookie()){
    if(document.getElementById('persistLogin').checked){
      document.getElementById('cookieError').style.visibility = "visible";
      document.getElementById('cookieError').style.height = "auto";
      document.getElementById('cookieError').style.padding = "10px";
      document.getElementById('cookieError').style.margin = "0 0 10px 0";
      document.getElementById('cookieError').style.border = "1px dotted #FF3300";
      document.getElementById('cookieError').style.lineHeight = "20px"
      document.getElementById('cookieError').innerHTML = cookieErrorTxt;
      document.getElementById('persistLogin').checked = false;
      document.getElementById('submitButton').disabled = true;
    	return false;
		}
		return false;
  }else{
  	return true;
	}
}

function cookieTest3(){
	if (!testPersistentCookie()){
    if(document.getElementById('persistLogin').checked){
      document.getElementById('cookieError').style.visibility = "visible";
      document.getElementById('cookieError').style.height = "auto";
      document.getElementById('cookieError').style.padding = "10px";
      document.getElementById('cookieError').style.margin = "0 0 10px 0";
      document.getElementById('cookieError').style.border = "1px dotted #FF3300";
      document.getElementById('cookieError').style.lineHeight = "20px"
      document.getElementById('cookieError').innerHTML = cookieErrorTxt;
      document.getElementById('persistLogin').checked = false;
      document.getElementById('submitButton').disabled = true;
    	return true;
		}
		return true;
  }else{
		document.getElementById('community_form').submit();
		return false;
  }
}


function init(){
    //alert ("Running Init");


    if(!document.getElementById) {
        ////alert("Older than 4.0 browser.");
        document.write("Your browser is not supported by this application.");
    }
    else if (obj.state == true && document.getElementById('nav')){ // if state=1 is in the URL query string, remember what nav layers are open or not.
        if (getCookieValue(navCookie)){ // If there's a navCookie, open it up & get the list of what layers to open
            var cookieVal = getCookieValue(navCookie);
            groupCategories = cookieVal.split('|');
            for (var i=0; i < groupCategories.length; i++) {
                ////alert(groupCategories[i]);
                if (groupCategories[i].length > 1){
                    /****
                        for each item in the cookie, open that layer up...
                    ****/
                    toggleLayer(groupCategories[i]);
                }
            }
        }
    }

    /****
        If you're in the player, refresh the page every 2 hours (or whatever ?refreshtimeout is)
    ****/
    if(is_in_player){
        if (obj.refreshtimeout) {
            refreshRate = obj.refreshtimeout.length>1?obj.refreshtimeout:refreshRate;
        }
        startRefreshTimer();


    }

    pingTheGuide();
}

function openPopup(theURL, theTitle, width, height) {
    var strSettings = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width='+width+',height='+height;
    var win = window.open(theURL, theTitle, strSettings);
    win.focus();
}

function isViper() {
    var pv = plyrObj.PlayerProperty("PRODUCTVERSION");
    var beamerVersion = "6.0.11.000";
    return versionCompare( pv, beamerVersion ) == -1;
}

function isBoxter() {
    var pv = plyrObj.PlayerProperty("PRODUCTVERSION");
    var boxterVersion = "6.0.11.999";
    return versionCompare( pv, boxterVersion ) == 1;
}

/* Compares 2 versions as #.#.#.# strings... */
function versionCompare(a,b) {
    var testver1 = a.split(".");
    var testver2 = b.split(".");

    if( testver1.length != testver2.length ) {
        return 0;
    }

    for( var i=0 ; i<testver1.length ; i++ ) {
        var t1 = testver1[i];
        var t2 = testver2[i];

        if( t1 != t2 ) {
            if( t1 < t2 ) {
                return -1;
            }
            if( t1 > t2 ) {
                return 1;
            }
        }
    }
    return 0;
}

function navigateToTab( tab, theURL ) {
    if( is_in_player && plyrObj != null ) {
        if (!isBoxter() && (tab == "home" || tab == "musicguide" || tab == "musicstore" || tab == "browser" || tab == "channels")) {
            tab = "web";
        }
        plyrObj.OpenURLInPlayerBrowser(theURL,"_rp" + tab);
    } else {
        document.location.href = theURL;
    }
}

function getArgs() {

    var args = new Object();
    var query = location.search.substring(1); //// Get Query String
    var pairs = query.split("&"); //// Split query at the ampersand

    for(var i = 0; i < pairs.length; i++) {    //// Begin loop through the querystring

        var pos = pairs[i].indexOf('='); //// Look for "name=value"
        if (pos == -1) continue; //// if not found, skip to next
        var argname = pairs[i].substring(0,pos); //// Extract the name

        var value = pairs[i].substring(pos+1); //// Extract the value
        args[argname] = unescape(value); //// Store as a property
    }
    return args; //// Return the Query string name/value pairs as an Object
}

/****
    Set the refreshRate from the querystring if present
    and refresh the page that often.  Otherwise, use the
    default 2 hour timer.
****/
function startRefreshTimer( ) {
    if( !loaded ){
        setTimeout("startRefreshTimer()",1000);
    } else{
        setTimeout("pageRefresh();",refreshRate);
    }
}

function pageRefresh() {
    if (is_in_player) {
        var plyrObj = top.parent.window.external;
    } else {
        document.write("<object id=\"IERPCtl\" width=0 height=0 classid=\"CLSID:FDC7A535-4070-4B92-A0EA-D9994BCC0DC5\"></object>");
        var plyrObj = document.getElementById("IERPCtl");
    }

    if( refreshURL && plyrObj.IsNetConnected() && plyrObj.PlayerProperty("WORKOFFLINE")!=1 ){
          document.location.href = refreshURL;
    } else{
        setTimeout("pageRefresh();",refreshRate);
    }
}

/****
    Next two functions encode string as UTF-8.
****/
function diggUrl( digghref )
{
    var widowWidth = 400;
    var windowHeight = 200;
    if (self.innerWidth)
    {
      widowWidth = self.innerWidth;
      windowHeight = self.innerHeight;
    }
    else if (document.documentElement && document.documentElement.clientWidth)
    {
      widowWidth = document.documentElement.clientWidth;
      windowHeight = document.documentElement.clientHeight;
    }
    else if (document.body)
    {
      widowWidth = document.body.clientWidth;
      windowHeight = document.body.clientHeight;
    }

    diggWindowSet = "width=" + widowWidth + ",height=" +  windowHeight + ",toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes";
    theDiggWindow = window.open(digghref, 'diggwindow', diggWindowSet);
    if (window.focus) {theDiggWindow.focus()};
}

 // white_space removes beginning and trailing white space (spaces & returns) from the strin passed in.

function white_space(field)
{
  return field.replace(/^\s*|\s*$/g,'');
}


function encodeChar( val )
{
    /* Create URL encoded utf-8 values from a scalar int */
    var output = "";
    /* Single Byte Values */
    if( (val & 0x7F) == val )
    {
        return escape( String.fromCharCode(val) );
    }
    /* Two Byte translation */
    if( ( val & 0x07FF ) == val )
    {
        output += "%" + ( ( val>>6 ) | 0xC0 ).toString(16);
        output += "%" + ( ( val & 0x3F ) | 0x80 ).toString(16);
        return output;
    }
    /* Three byte translation */
    if( (val & 0xFFFF) == val )
    {
        output += "%" + (( val >> 12 ) | 0xE0 ).toString(16);
        output += "%" + ((( val >> 6 ) &  0x3F ) | 0x80 ).toString(16);
        output += "%" + (( val & 0x3F ) | 0x80 ).toString(16);
        return output;
    }
    /* Four Byte translation */
    if( (val & 0x1FFFFF) == val )
    {
        output += "%" + (( val >> 18 ) | 0xF0).toString(16);
        output += "%" + ((( val >> 12 ) & 0x3F ) | 0x80 ).toString(16);
        output += "%" + ((( val >> 6) & 0x3F ) | 0x80 ).toString(16);
        output += "%" + (( val & 0x3F ) | 0x80 ).toString(16);
        return output;
    }
}
function urlHexEncode( str )
{
    var ret = "";
    str = white_space(str);
    for( var i=0; i<str.length; i++ ){
      ret += encodeChar( str.charCodeAt( i ) );
    }
    return ret;
}


function RPOnStateChange(play_state){
    if (document.getElementById("flash")){
        switch(play_state) {
            case 0:
                // stopped state
                flash.Play();
                break
            case 3:
                // playing state
                flash.StopPlay();
                break;
        }
    }
}

function getExpiryDateForCookie(days){
    var UTCString;
    Today = new Date();
    milliseconds = Date.parse(Today);
    Today.setTime(milliseconds + days*24*60*60*1000);
    UTCString = Today.toUTCString();
    return UTCString;
}

function setCookie(name, value, duration, path, domain, secure) {
    document.cookie= name + "=" + value +
        ((duration) ? "; expires=" + getExpiryDateForCookie(duration) : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function rp_playclip(url) {
  if (plyrObj) {
    plyrObj.PlayClip(url);
    return false;
  }
  else {
    return true;
  }

}

function pingTheGuide() {
  var pstate = -1;
  try {
        pstate = plyrObj.GetPlayerState();
//alert("http://ping." + guideURL + "/?player-state=" + pstate);
    if (window.XMLHttpRequest) {
        // For Firefox and Mozilla
        var req = new XMLHttpRequest()
        req.open("GET", "http://" + guideURL + "/ping?player-state=" + pstate, true)
        req.send(null)
    }
    else if (window.ActiveXObject) {
        // For IE
        var req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.open("GET", "http://" + guideURL + "/ping?player-state=" + pstate, true);
            req.send();
        }
    }
  }
  catch (ex) {}
}

/* set top story rating div position depending on story title height */

function setTopMargin(topId, bottomId){
	var topDivHeight = 0;

  if(document.getElementById(topId)){
    topDivHeight = document.getElementById(topId).offsetHeight;
    //topDivHeight = topDivHeight + 5;
    document.getElementById(bottomId).style.marginTop = topDivHeight+"px";
  }
}

/*Match the height of the featured divs*/
function matchHeight(){

    if (document.getElementById('featured1')){
        var DH = 0;

        /*get the original div heights*/
        var feat1H = document.getElementById('featured1').offsetHeight;
        var feat2H = document.getElementById('featured2').offsetHeight;
        var feat3H = document.getElementById('featured3').offsetHeight;
        var feat4H = document.getElementById('featured4').offsetHeight;

        /* set DH to the largest Height value */
        if (feat1H >= feat2H && feat1H >= feat3H && feat1H >= feat4H){
            DH = feat1H;
        } else if (feat2H >= feat1H && feat2H >= feat3H && feat2H >= feat4H){
            DH = feat2H;
        } else if (feat3H >= feat1H && feat3H >= feat2H && feat3H >= feat4H){
            DH = feat3H;
        } else if (feat4H >= feat1H && feat4H >= feat2H && feat4H >= feat3H){
            DH = feat4H;
        } else {
            DH = feat1H;
        }

        /*redraw divs*/
        document.getElementById('featured1').style.height	=	DH+"px";
        document.getElementById('featured2').style.height	=	DH+"px";
        document.getElementById('featured3').style.height	=	DH+"px";
        document.getElementById('featured4').style.height	=	DH+"px";
    }
}

function bodyHeight(){

    if (document.getElementById('body_center')){

        /*get the original div heights*/
        var bcHeight = document.getElementById('body_main').offsetHeight;

        /*redraw divs*/
        document.getElementById('body_left').style.height	=	bcHeight+"px";
        document.getElementById('body_right').style.height	=	bcHeight+"px";

    }
}

/* This if for the zip code searching */
function checkField(fromWhere){

  if (document.getElementById('zip').value.length!=5 || isNaN(document.getElementById('zip').value) ) {

    alert("Zip code should be 5 numbers long, please re-enter the zip code and try again.");
    return false;
  } else {
    if (document.getElementById('zipForm')){
      document.getElementById('zipForm').submit();
    } else {
      do_xml(document.getElementById('zip').value);
    }
  }
}

function CheckKeyCode(evt)
{

  evt = (evt) ? evt : ((event) ? event : null);
  if (evt) {

     if(
        evt.keyCode==13 ){
        return checkField();
        } else if (
        (evt.keyCode == 189 || evt.keyCode == 109) ||
        (evt.keyCode >= 48 && evt.keyCode <= 57) ||
        (evt.keyCode >= 96 && evt.keyCode <= 105)  ||
        evt.keyCode==8 || evt.keyCode==46 || evt.keyCode==45

        ) {

      return true;


   } else {
      return false;
    }
  }
}
function setMaxLength(){
   document.getElementById('zip').maxLength = 5;
}
/* this is so user can press Enter on the sign in page and submit the form */

function shouldSubmit(evt, which){
  	evt = (evt) ? evt : ((event) ? event : null);
  	// keyCode is Enter key
	if (evt.keyCode==13 && document.getElementById(which)) {
		document.getElementById(which).submit();
	}else{
		return true;
	}
}

function submitEnterKey(evt){
  if(evt.keyCode==13){
    cookieTest3();
    return true;
  }else{
    return false;
  }
}

/****************************************************
  EMAIL Validation for Friends page
****************************************************/

function echeck(str, a) {
  a = a + "";

  var doAlert=true;
  var returnValue=true;
  if (a!="undefined"){
    doAlert=false;
  }

    var at="@"
    var dot="."
    var lat=str.indexOf(at)
    var lstr=str.length
    var ldot=str.indexOf(dot)
    if (str.indexOf(at)==-1){
      if (doAlert){
          alert("Invalid E-mail")
          return false
        } else {
          returnValue=false;
        }
    }

    if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
      if (doAlert){
          alert("Invalid E-mail")
          return false
        }else {
          returnValue=false;
        }
    }

    if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
      if (doAlert){
          alert("Invalid E-mail")
          return false
        }else {
          returnValue=false;
        }
    }

     if (str.indexOf(at,(lat+1))!=-1){
      if (doAlert){
          alert("Invalid E-mail")
          return false
        }else {
          returnValue=false;
        }
     }

     if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
      if (doAlert){
          alert("Invalid E-mail")
          return false
        }else {
          returnValue=false;
        }
     }

     if (str.indexOf(dot,(lat+2))==-1){
      if (doAlert){
          alert("Invalid E-mail")
          return false
        }else {
          returnValue=false;
        }
     }

     if (str.indexOf(" ")!=-1){
      if (doAlert){
          alert("Invalid E-mail")
          return false
        }else {
          returnValue=false;
        }
     }
    if (doAlert){
      return true
     }else{
      return returnValue;
     }
  }

function ValidateSenderName(nameID){

  if ((nameID.value==null)||(nameID.value=="")){
    alert("Please Enter your Name")
    nameID.focus()
    return false
  }
  return true
}

function ValidateSenderEmail(emailID){

  if ((emailID.value==null)||(emailID.value=="")){
    alert("Please Enter your Email");
    emailID.focus();
    return false;
  }
  if (echeck(emailID.value)==false){
    alert("Please Enter a valid Email");
    emailID.value="";
    emailID.focus();
    return false;
  }
  return true;
 }

function ValidateFriends(emailID){
  if ((emailID.value==null)||(emailID.value=="")){
    return true;
  }
  if (echeck(emailID.value)==false){

    emailID.value="";
    emailID.focus();
    return false;
  }
  return true;
 }
function ValidateFriendsNotEmpty(){
  if((document.getElementById('toemail1').value.length > 0) ||
      (document.getElementById('toemail2').value.length > 0) ||
      (document.getElementById('toemail3').value.length > 0) ||
      (document.getElementById('toemail4').value.length > 0) ||
      (document.getElementById('toemail5').value.length > 0)){
   return true;
  }
  alert("Please enter at least one Email for your friends.");
  document.getElementById('toemail1').focus();
  return false;
}

function ValidateForm(){
  var elem = document.getElementById('frmMain').elements;
  var valid = false;
  var validname = false;
  var validemail = false;
  var validfriend1 = false;
  var validfriend2 = false;
  var validfriend3 = false;
  var validfriend4 = false;
  var validfriend5 = false;

  for(var i = 0; i < elem.length; i++)
  {
    if (elem[i] == document.getElementById('fromname')){
      validname = ValidateSenderName(elem[i]);
      if(!validname) break;
    }
    if (elem[i] == document.getElementById('fromemail')){
      validemail = ValidateSenderEmail(elem[i]);
      if(!validemail) break;
    }
    if (elem[i] == document.getElementById('toemail1')){
      validfriend1 = ValidateFriends(elem[i]);
      if(!validfriend1) break;
    }
    if (elem[i] == document.getElementById('toemail2')){
      validfriend2 = ValidateFriends(elem[i]);
      if(!validfriend2) break;
    }
    if (elem[i] == document.getElementById('toemail3')){
      validfriend3 = ValidateFriends(elem[i]);
      if(!validfriend3) break;
    }
    if (elem[i] == document.getElementById('toemail4')){
      validfriend4 = ValidateFriends(elem[i]);
      if(!validfriend4) break;
    }
    if (elem[i] == document.getElementById('toemail5')){
      validfriend5 = ValidateFriends(elem[i]);
      if(!validfriend5) break;
    }
  }

  if (validname && validemail && validfriend1 && validfriend2 && validfriend3 && validfriend4 && validfriend5){
    if(ValidateFriendsNotEmpty()){
      document.getElementById('submitval').value = true;
      return true;
    }
    else{
    document.getElementById('submitval').value = false;
    return false;
    }
  }
  else{
    document.getElementById('submitval').value = false;
    return false;
  }
  return false;
}
function createGutterAds(){
  var newcontent = document.createElement('div');
  newcontent.id = 'leftGutterAd';
  newcontent.className="leftGutterAd";
  var newcontent2 = document.createElement("div");
  newcontent2.id='rightGutterAd';
  newcontent2.className="rightGutterAd";
  var scr = document.getElementById('body_tag');
  try{
     scr.parentNode.insertBefore(newcontent, scr);
     scr.parentNode.insertBefore(newcontent2, scr);
  }catch (e){};
  adjustGutterAds();
}

function adjustGutterAds(leftContentWidth, rightContentWidth){

   var width = document.width;
   if (width+"" == "undefined"){
      width = document.body.clientWidth ;
   }
   if (width+"" != "undefined"){
      var difference = width - 974; //assumes the width of the film.com site content is 974
      if (document.getElementById('leftGutterAd')){
         if (null==leftContentWidth) leftContentWidth=226;
         if (null==rightContentWidth) rightContentWidth=226;
         document.getElementById('leftGutterAd').style.marginLeft = (difference/2) - leftContentWidth + "px";
         document.getElementById('rightGutterAd').style.marginRight = (difference/2) - rightContentWidth + "px";
      } else{
          createGutterAds();
      }
  }
}

// story tools section scripts

function openShare(appendText){

  if (browser.indexOf("msie")>-1) {
    if (document.getElementById('openShareDiv' + appendText) ) {
      document.getElementById('openShareDiv' + appendText).style.marginLeft="-50px";
    }
    if (document.getElementById('openShareDiv' + appendText) ){
      document.getElementById('openShareDiv' + appendText).style.marginTop="14px";
    }
    if (browser.indexOf('msie 6.')>-1) {
      document.getElementById('openShare' + appendText).style.width="112px";
      document.getElementById('openShare' + appendText).style.borderBottom="2px solid #e2e2e2";
    }
  }
  document.getElementById('openShare' + appendText).style.display='block';
  document.getElementById('closedShare' + appendText).style.display="none";
}

function closeShare(appendText){
  document.getElementById('openShare' + appendText).style.display='none';
  document.getElementById('closedShare' + appendText).style.display="block";
}

/*  MOVIE ASSET PAGE - REVIEW TABS ******/

function swapReviewDiv(divToshow,divToHide){
  var swapDivToShow = null;
  var swapDivToHide = null;
  var storyButtonDiv = null;
  var movieButtonDiv = null;
  var headerDivToHide = null;
  var headerDivToShow = null;

  if(document.getElementById(divToshow + "_review")){
    swapDivToShow= document.getElementById(divToshow + "_review");
  }
  if(document.getElementById(divToHide + "_review")){
    swapDivToHide = document.getElementById(divToHide + "_review");
  }
  if(document.getElementById("story_review_button")){
    storyButtonDiv = document.getElementById("story_review_button");
  }
  if(document.getElementById("movie_review_button")){
    movieButtonDiv = document.getElementById("movie_review_button");
  }
  if(document.getElementById(divToshow + "_review_header")){
    headerDivToShow = document.getElementById(divToshow + "_review_header");
  }
  if(document.getElementById(divToHide + "_review_header")){
    headerDivToHide = document.getElementById(divToHide + "_review_header");
  }

  // The images swap is done here because IE6 is a giant peice of junk, and can't handle classes AND IDs at the same time...

  if(divToHide == "story"){
    if(storyButtonDiv){
      headerDivToShow.style.backgroundImage = "url(" + staticBaseURL + "/images/buttons/white_tab_right.gif)";
      headerDivToShow.style.color = "#333333";
      headerDivToHide.style.backgroundImage = "url(" + staticBaseURL + "/images/buttons/grey_tab_left.gif)";
      headerDivToHide.style.color = "#FFFFFF";
      storyButtonDiv.innerHTML = '<a href="#" onclick="swapReviewDiv(\'story\',\'movie\');return false;">Film.com Reviews</a>';
    }
    if(movieButtonDiv){
      movieButtonDiv.innerHTML = 'Other Reviews';
    }
  }else{
    if(movieButtonDiv){
      headerDivToShow.style.backgroundImage = "url(" + staticBaseURL + "/images/buttons/white_tab_left.gif)";
      headerDivToShow.style.color = "#333333";
      headerDivToHide.style.backgroundImage = "url(" + staticBaseURL + "/images/buttons/grey_tab_right.gif)";
      headerDivToHide.style.color = "#FFFFFF";

      movieButtonDiv.innerHTML = '<a href="#" onclick="swapReviewDiv(\'movie\',\'story\');return false;">Other Reviews</a>';
    }
    if(storyButtonDiv){
      storyButtonDiv.innerHTML = 'Film.com Reviews';
    }
  }
  swapDivToShow.style.display = "block";
  swapDivToHide.style.display = "none";
}




function showRegistration(){
  if (document.getElementById("register_login_pup")){
    var popupDiv = document.getElementById("register_login_pup");
    var popUpIFrameHTML = "<iframe id=\"registration_login\" name=\"signin\" marginwidth=\"0\" marginheight=\"0\" frameborder=\"0\" scrolling=\"no\" src=\"" + secureBaseUrl + "/auth/";
  }
  document.getElementById("register_pup").style.display = "block";
  popupDiv.innerHTML = popUpIFrameHTML +  "register\" width=\"410\" height=\"370\" />";
  popupDiv.style.height = "370px";
  popupDiv.style.display = "block";
  return false;
}

function showUserSignIn(){
  if (document.getElementById("register_login_pup")){
    var popupDiv = document.getElementById("register_login_pup");
    var popUpIFrameHTML = "<iframe id=\"registration_login\" marginwidth=\"0\" marginheight=\"0\" frameborder=\"0\" scrolling=\"yes\" src=\"" + secureBaseUrl + "/auth/";
  }
  document.getElementById("register_pup").style.display = "block";
  popupDiv.innerHTML = popUpIFrameHTML +  "signin\" width=\"410\" height=\"100\" />";
  popupDiv.style.height = "100px";
  popupDiv.style.display = "block";
  return false;
}

function showMyAccount(){
  if (document.getElementById("register_login_pup")){
    var popupDiv = document.getElementById("register_login_pup");
    var popUpIFrameHTML = "<iframe id=\"registration_login\" marginwidth=\"0\" marginheight=\"0\" frameborder=\"0\" scrolling=\"no\" src=\"" + secureBaseUrl + "/auth/";
  }
  document.getElementById("register_pup").style.display = "block";
  popupDiv.innerHTML = popUpIFrameHTML +  "register\" width=\"410\" height=\"500\" />";
  popupDiv.style.height = "500px";
  popupDiv.style.display = "block";
  return false;
}

function closeAccountWindow(){
  if (document.getElementById("register_login_pup")){
    var popupDiv = document.getElementById("register_login_pup");
  }
  popupDiv.innerHTML = "";
  popupDiv.style.display = "none";
  document.getElementById("register_pup").style.display = "none";
  return false;
}

function getLocation(location){
  if(location == null || location == ''){
    location = document.location.href;
  }
  if (location.indexOf('#')>-1){
    location = location.substring(0, location.indexOf('#'));
  }
  return location;
}

function pauseThenReload(){
  var start = new Date();
  var curDate = null;
  do
  {
      curDate = new Date();
  }
  while(curDate-start < 3000);
  window.location.reload(true);
}