/**** Define global variables ****/
var loaded = true;
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 flashbackShareUrl = "";

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


/**
 * 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 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 openPopupNoScroll(theURL, theTitle, width, height) {
    var strSettings = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,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]-0;
        var t2 = testver2[i]-0;

        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 = "superpass";
        }
        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 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 = "";
    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;
}

//TODO: Clean up setCookies functions only need one not 3...


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 createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function CookieManager(){}

CookieManager.setCookie = function( name, value, lifeInMillis, path, cookieDomain, secure )
{
  if ( lifeInMillis )
  {
    var date = new Date();
    date.setTime( date.getTime() + lifeInMillis );
    var expires = date.toGMTString();
  }
  else
  {
    var expires = null;
  }
  var cookie = name + "=" + escape(value) +
      ( expires ? "; expires=" + expires : "" ) +
      ( path ? "; path=" + path : "; path=/" )  +
      ( cookieDomain ? "; domain=" + cookieDomain : "; domain=.real.com" ) +
      ( secure ? "; secure" : "" );
  document.cookie = cookie;

}

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) {}
}

function Asynchronous() {
  this._xmlhttp = new FactoryXMLHttpRequest();
}

function Asynchronous_call( url, rssType ) {
  var instance = this;
  this._xmlhttp.open( 'GET', url, true );
  this._xmlhttp.onreadystatechange = function() {
    instance._status = instance._xmlhttp.readyState;
    switch(instance._xmlhttp.readyState) {
      case 1:
        instance.loading();
                break;
      case 2:
        instance.loaded();
                break;
      case 3:
        instance.interactive();
                break;
      case 4:
        instance.complete(
          instance._xmlhttp.status,
          instance._xmlhttp.statusText,
          instance._xmlhttp.responseText,
          instance._xmlhttp.responseXML
        );
                break;
    }
  }
  this._xmlhttp.send( null );
}

function Asynchronous_loading() {}
function Asynchronous_loaded() {}
function Asynchronous_interactive() {}
function Asynchronous_complete( status, statusText, reponseText, responseXML ) {}

Asynchronous.prototype.loading = Asynchronous_loading;
Asynchronous.prototype.loaded = Asynchronous_loaded;
Asynchronous.prototype.interactive = Asynchronous_interactive;
Asynchronous.prototype.complete = Asynchronous_complete;
Asynchronous.prototype.call = Asynchronous_call;

function FactoryXMLHttpRequest() {
  if( window.XMLHttpRequest ) {
    return new XMLHttpRequest();
  } else if( window.ActiveXObject ) {
    try {
      return new ActiveXObject( "Msxml2.XMLHTTP" );
    } catch( e ) {
      try {
        return new ActiveXObject( "Microsoft.XMLHTTP" );
      } catch( e ) {
      }
    }
  }
  throw new Error("Could not instantiate XMLHttpRequest.");
}


function changeTab(comTab)
  {
    var thisComTab = null;
    for (i = 1;i<7;i++)
    {
      thisComTab = eval(document.getElementById("comtab"+i));
      thisComTab.className = "hg_item_unsel";
    }
    comTab.className = "hg_item_sel";

    HGConnectSelectedTab = comTab.id;

    if(comTab.id == "comtab1"){
      $("HGConnectContentWrapper").innerHTML = $("HGTwitter").innerHTML;
    } else if(comTab.id == "comtab2"){
      $("HGConnectContentWrapper").innerHTML = $("HGFacebook").innerHTML;
    } else if(comTab.id == "comtab3"){
      $("HGConnectContentWrapper").innerHTML = $("HGMySpace").innerHTML;
    } else if(comTab.id == "comtab4"){
      $("HGConnectContentWrapper").innerHTML = $("HGBlogs").innerHTML;
    } else if(comTab.id == "comtab5"){
      $("HGConnectContentWrapper").innerHTML = $("HGEvents").innerHTML;
    } else if(comTab.id == "comtab6"){
      $("HGConnectContentWrapper").innerHTML = $("HGBoards").innerHTML;
    }
  }

function defaultHour() {
    var hourOption = "hour" + serverTime;
    document.getElementById(hourOption).selected = true;
  }

  function $(element) {
    return document.getElementById(element);
  }

  function showCalendar(season) {

    if (season == '10') {
      $("BB10Calendar").style.display = "block";
      $("bb10Header").className = "seasonSelected";
      $("BB11Calendar").style.display = "none";
      $("bb11Header").className = "seasonUnselected";
    } else
    {
      $("BB11Calendar").style.display = "block";
      $("bb11Header").className = "seasonSelected";
      $("BB10Calendar").style.display = "none";
      $("bb10Header").className = "seasonUnselected";
    }
  }

  function getFileName() {
    var errorText = "";
    var selectedDate = getSelectedCalDate();
    var selectedHour = getSelectedCalHour();

    //alert("Selected hour is: " + selectedHour + " serverTime is: " + serverTime);

    if (Date.parse(selectedDate[0]) == Date.parse(JSFullDate) && (selectedHour) > serverTime)
      errorText = "FlashBack streams are on a 2 hour delay. Please select a time more than 2 hours in the past.";

    if (errorText.length > 5) {
      alert(errorText);
      return;
    }

    var domain = "rtsp://start.real.com/rd?";
    var BB10directory = "pid=bb10_archive&url=";
    var BB11directory = "pid=bb11_archive&url=";

    var filename = getFileDate() + "_256.rm";
    var camera = getCamera();

    if ($("BB11Calendar").style.display == "block")
      playVideo(domain + BB11directory + camera + "/" + filename);
    else
      playVideo(domain + BB10directory + camera + "/" + filename);
  }

  function getFileDate(){
    var selectedDate = getSelectedCalDate();
    var selectedHour = getSelectedCalHour();
    var camera = getCamera();

    var fileDate = selectedDate[0].getFullYear();
    if ((selectedDate[0].getMonth() + 1) < 10) {
      fileDate += "0" + (selectedDate[0].getMonth() + 1); //getMonth() returns 0 index, 0-11, because it is dumb.
    } else {
      fileDate += "" + (selectedDate[0].getMonth() + 1); //getMonth() returns 0 index, 0-11, because it is dumb.
    }
    if (selectedDate[0].getDate() < 10) {
      fileDate += "0" + selectedDate[0].getDate() + selectedHour + "_" + camera;
    } else {
      fileDate += selectedDate[0].getDate() + selectedHour + "_" + camera;
    }
  return fileDate;
}

  function getSelectedCalDate(){
    var selectedDate;
    if(bb10Calendar == null){
      bb10Calendar = new YAHOO.widget.Calendar("BB10Calendar");
    }
    if(bb11Calendar == null){
      bb11Calendar = new YAHOO.widget.Calendar("BB11Calendar");
    }
    if ($("BB11Calendar").style.display == "block")
      selectedDate = bb11Calendar.getSelectedDates();
    else
      selectedDate = bb10Calendar.getSelectedDates();
    return selectedDate;
  }

  function getSelectedCalHour(){
    return document.getElementById("hour").options[document.getElementById("hour").selectedIndex].value;
  }

  function getCamera(){
    return $("camera").options[$("camera").selectedIndex].value;
  }

function playVideo( url) {
  if($("videoPlayback").style.display == "none")
  {
    $("videoPlaybackCurtain").style.display = "none";
    $("videoPlayback").style.display = "block";
    if ($("shareBar")) {
      $("shareBar").style.display = "block";
    }
  }

  setTimeout("document.video.SetSource(\"" + url + "\")",500);
  setTimeout("document.video.DoPlay()",1000);
  setShareUrl(url);
}

function playHotClip( url )
{
  setShareUrl(url);
  //loadhotClips is defined on HotClips page. If it is undefined, we move to that page, otherwise we play the video.
  if(typeof loadHotClips == "undefined"){
    window.location.replace(baseURL + "/bigbrother/hotclips?url=" + url);
  } else {
    playVideo(url);
  }
}

function playCarouselClip(url,page)
{
  setShareUrl(url);
  //loadhotClips is defined on HotClips page. If it is undefined, we move to that page, otherwise we play the video.
  if(typeof loadHotClips == "undefined"){
    window.location.replace(baseURL + "/" + page + "?url=" + url);
  } else {
    playVideo(url);
  }
}

function setShareUrl(url) {
  flashbackShareUrl = url;
  flashbackShareUrl = flashbackShareUrl.replace('rtsp:','http:');
  
}

function getShareUrl() {
    return flashbackShareUrl;
}

function shareUrl(type) {
    var url = getShareUrl();

		if (url != "") {
      if (type == "twitter") {
			  window.open('http://twitter.com/home?status=' + encodeURIComponent(url),'sharer','toolbar=0,status=0,width=800,height=436');
		  } else if (type == "email") {
			  window.location.href = 'mailto:?subject=' + encodeURIComponent('Check out this Big Brother Flashback!') + '&body=' + encodeURIComponent('Check out this Big Brother Flashback from SuperPass!' + url + '  You must be a SuperPass subscriber, and logged in, to view this link.');
		  }
    }

		return false;
}


function showPopup(popup){
  //Hide all popups first
  hide("goldfeature");
  hide("HG_container");
  if(popup == "gold")
    show("goldfeature");
  else if(popup == "HG_container")
    show("HG_container");
}

/*** Generic Show Hide Functions ***/

function hide(id) {
  if (document.getElementById(id) != null && document.getElementById(id) != '') {
    document.getElementById(id).style.display = 'none';
  }
}
function show(id) {
  if (document.getElementById(id) != null && document.getElementById(id) != '') {
    document.getElementById(id).style.display = 'block';
  }
}

function defaultMenuColor(element)
{
  alert("Changing for: " + element.id);
  element.style.color="#086699";
}
/* EMS FADER CODE, borrowed from http://www.greywyvern.com/code/javascript/fade */

  function fadeObject(id, c1, c2, s1, s2) {
  var self = this;
  this.id      = id;
  this.elem    = false;
  this.colour  = {
    stt: [parseInt(c1.substr(0, 2), 16), parseInt(c1.substr(2, 2), 16), parseInt(c1.substr(4, 2), 16)],
    end: [parseInt(c2.substr(0, 2), 16), parseInt(c2.substr(2, 2), 16), parseInt(c2.substr(4, 2), 16)],
    now: [parseInt(c1.substr(0, 2), 16), parseInt(c1.substr(2, 2), 16), parseInt(c1.substr(4, 2), 16)]
  };
  this.steps   = [s1, s2];
  this.dir     = false;
  this.active  = false;
  this.queue   = [];
  this.msg     = [];
  this.message = 0;
  function d2h(num) {
    num = Math.round(num);
    return ((num < 16) ? "0" : "") + num.toString(16);
  }
  this.fade = function(message, direction) {
    this.elem = this.elem || document.getElementById(this.id);
    this.queue.push([message, direction]);
    for (var x = 0; x < this.queue.length; x++) {
      for (var y = x + 1; y < this.queue.length; y++) {
        if (this.queue[x][0] == this.queue[y][0] && this.queue[x][1] != this.queue[y][1]) {
          this.queue.splice(x, 1);
          this.queue.splice(y - 1, 1);
        }
      }
    }
    if (!this.active) setTimeout(function() { self.fadeLoop(); }, 10);
  };
  this.fadeLoop = function() {
    if (!this.active && this.queue.length) {
      if (this.dir && this.message != this.queue[0][0]) this.queue.unshift([this.message, false]);
      var msg = this.queue.shift();
      if (this.msg[msg[0]]) {
        this.active = true;
        this.elem.innerHTML = this.msg[this.message = msg[0]];
        this.dir = msg[1];
      }
    }
    if (this.dir) {
      var c1 = this.colour.stt, c2 = this.colour.end, stx = this.steps[0];
    } else var c1 = this.colour.end, c2 = this.colour.stt, stx = this.steps[1];
    for (var x = 0, cnow = "", inc = 0; x < 3; x++) {
      this.colour.now[x] += inc = (c2[x] - c1[x]) / stx;
      cnow += this.colour.now[x] = (inc < 0) ? Math.max(this.colour.now[x], c2[x]) : Math.min(this.colour.now[x], c2[x]);
    } this.elem.style.color = "#" + d2h(this.colour.now[0]) + d2h(this.colour.now[1]) + d2h(this.colour.now[2]);
    if (cnow == c2.join("")) {
      this.active = false;
      if (!this.queue.length) {
        if (!this.dir) {
          if (this.msg[0]) {
            this.queue.push([0, true]);
            setTimeout(function() { self.fadeLoop(); }, 10);
          } else this.elem.innerHTML = "&nbsp;";
        }
      } else setTimeout(function() { self.fadeLoop(); }, 10);
    } else setTimeout(function() { self.fadeLoop(); }, 10);
  };
  if (window.addEventListener) {
    window.addEventListener('load', function() { self.fade(0, true); }, false);
  } else if (window.attachEvent)
    window.attachEvent('onload', function() { self.fade(0, true); });
}

  /* *****
 * The code below describes how to make a throbbing or automatic fade
 * sequence of messages.  It is important to note that this function is
 * NOT part of the Buffered Text-Fade Effect, but merely an example of
 * how it can be used.  In this example, the throb() function controls
 * the commands which are sent to the fade engine; it is called
 * repeatedly at set time intervals rather than using mouseover events
 * as triggers.
 *
 * Notes:
 * - A global array "hash" is used to keep track of where each
 *   animation is currently in the sequence.
 * - The list of messages defined in the fader *must* start at one (1)
 *   and count upwards without skipping any integers.
 * - The third line of the throb() function controls how fast
 *   commands get sent to the fade engine.  It waits only 100 milli-
 *   seconds when fading out, but 5000 milliseconds (5 seconds) when
 *   fading in; this means the message will remain visible for about 5
 *   seconds before fading out again.
 *
 * Other types of fade animation are possible simply by designing
 * different ways to control the fade-ins and fade-outs!
 */
var hash = new Array();
function throb(item) {

  // If the hash array does not have an entry for this item, initialise it at 2
  if (!hash[item]) hash[item] = 2;

  // Send a fade command, using the hash array to tell us what parameters we should use
  fader.fade(Math.floor(hash[item] / 2), !(hash[item] % 2));

  // Call this function again for this same item after a certain amount of time
  setTimeout(function() { throb(item); }, (hash[item] % 2) ? 100 : 5000);

  // If we have exceeded the number of messages in this fader, start over again at 2
  if (++hash[item] > fader.msg.length * 2 - 1) hash[item] = 2;
}

// setTitle18();

function setTitle18() {
  var title18Cookie = Get_Cookie('title18');
  Set_Cookie('title18','true','180');

  if (title18Cookie != 'true') {
    openPopup( baseURL + '/bigbrother/title18','SuperPass','685','270');
  }
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
// set time, it's in milliseconds
var today = new Date();
today.setTime( today.getTime() );

/*
if the expires variable is set, make the correct
expires time, the current script below will set
it for x number of days, to make it for hours,
delete * 24, for minutes, delete * 60 * 24
*/
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
var expires_date = new Date( today.getTime() + (expires) );

document.cookie = name + "=" +escape( value ) +
( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
( ( path ) ? ";path=" + path : "" ) +
( ( domain ) ? ";domain=" + domain : "" ) +
( ( secure ) ? ";secure" : "" );
}

function Get_Cookie( check_name ) {
  // first we'll split this cookie up into name/value pairs
  // note: document.cookie only returns name=value, not the other components
  var a_all_cookies = document.cookie.split( ';' );
  var a_temp_cookie = '';
  var cookie_name = '';
  var cookie_value = '';
  var b_cookie_found = false; // set boolean t/f default f

  for ( i = 0; i < a_all_cookies.length; i++ )
  {
    // now we'll split apart each name=value pair
    a_temp_cookie = a_all_cookies[i].split( '=' );


    // and trim left/right whitespace while we're at it
    cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

    // if the extracted name matches passed check_name
    if ( cookie_name == check_name )
    {
      b_cookie_found = true;
      // we need to handle case where cookie has no value but exists (no = sign, that is):
      if ( a_temp_cookie.length > 1 )
      {
        cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
      }
      // note that in cases where cookie is initialized but no value, null is returned
      return cookie_value;
      break;
    }
    a_temp_cookie = null;
    cookie_name = '';
  }
  if ( !b_cookie_found )
  {
    return null;
  }
}


function swapImageOn(tabIndex)
      {
        if(tabIndex != "undefined" && tabIndex != "null" && tabIndex != "" && tabNamesArray.indexOf(tabIndex) >=0)
        {
          if (tabIndex != document.getElementById('tabSel').value)
          {
            document.getElementById(tabIndex).src = tabs_over[tabNamesArray.indexOf(tabIndex)];
          }
          else
          {
              if(document.getElementById(tabIndex).src !="undefined" || document.getElementById(tabIndex).src !="null")
                document.getElementById(tabIndex).src = tabs_on[tabNamesArray.indexOf(tabIndex)];
          }

        }
      }

      function swapImageOff(tabIndex)
      {
        if (tabIndex != document.getElementById('tabSel').value)
          document.getElementById(tabIndex).src = tabs_out[tabNamesArray.indexOf(tabIndex)];
      }


      function setParameter(tabName)
      {
          document.getElementById('tabSel').value = currTab;
      }


    function getParameter (parameterName)
    {
      parameterName = parameterName + "=";
      var queryString = window.top.location.search.substring(1);
      if ( queryString.length > 0 )
      {
      // Find the beginning of the string
        begin = queryString.indexOf ( parameterName );
        // If the parameter name is not found, skip it, otherwise return the value
        if ( begin != -1 )
        {
          // Add the length (integer) to the beginning
          begin += parameterName.length;
          // Multiple parameters are separated by the "&" sign
          end = queryString.indexOf ( "&" , begin );
          if ( end == -1 )
          {
            end = queryString.length
          }
          // Return the string
          return unescape ( queryString.substring ( begin, end ) );
        }
        // Return "null" if no parameter has been found
        return "null";
      }
    }

    function adjustTabs()
    {
        document.getElementById("moreMenuTable").width = eval(document.getElementById("moreMenuTable").offsetWidth + 10);
        document.getElementById("tvMenuTable").width = eval(document.getElementById("tvMenuTable").offsetWidth + 10);
        document.getElementById("wrap1").style.top = "80px";
        document.getElementById("tvLinkWrapper").style.top = "80px";
      //document.getElementById("greeting_div").style.visibility = "visible";
    }

    function showMenu(menu)
    {
      var menuToShow = document.getElementById(menu);
      menuToShow.style.left = eval(tempX + 5) + "px";
      menuToShow.style.visibility = "visible";
    }

    function hideMenu(menu)
    {
      var menuToHide = document.getElementById(menu);
      var state = menuToHide.style.visibility;
      if (state == "visible")
        menuToHide.style.visibility = "hidden";

      return false;
    }

    function moreMenuLinkHover(td)
    {
      td.style.backgroundColor='#C4E0EF';
      td.style.fontWeight = 700;
      td.style.paddingRight = "5px";
    }

    function moreMenuLinkDown(td)
    {
      td.style.backgroundColor='#89C1E0';
      td.style.fontWeight = 700;
      td.style.paddingRight = "5px";
    }

    function moreMenuLinkOut(td)
    {
      td.style.backgroundColor="#FFFFFF";
      td.style.fontWeight = 500;
      td.style.paddingRight = "15px";
    }


    var IE = document.all;
    if (!IE) document.captureEvents(Event.MOUSEMOVE)

    // Set-up to use getMouseXY function onMouseMove
    document.onmousemove = getMouseXY;

    // Temporary variables to hold mouse x-y pos.s
    var tempX = 0
    var tempY = 0

    // Main function to retrieve mouse x-y pos.s

    function getMouseXY(e) {
      if (document.body)
      {
      if (IE) { // grab the x-y pos.s if browser is IE
        tempX = event.clientX + document.body.scrollLeft
        tempY = event.clientY + document.body.scrollTop
      } else {  // grab the x-y pos.s if browser is NS
        tempX = e.pageX
        tempY = e.pageY
      }
      // catch possible negative values in NS4
      if (tempX < 0){tempX = 0}
      if (tempY < 0){tempY = 0}


      if (document.getElementById("wrap1"))
      {
        var moreMenuDiv = document.getElementById("wrap1");
        var minX = moreMenuDiv.offsetLeft - 10;
        var maxX = moreMenuDiv.offsetLeft + moreMenuDiv.offsetWidth + 10;
        var minY = moreMenuDiv.offsetTop - 10;
        var maxY = moreMenuDiv.offsetTop + moreMenuDiv.offsetHeight + 10;
      }

      if (tempX < minX || tempX > maxX) hideMenu("wrap1");

      if (document.getElementById("tvLinkWrapper"))
      {
        var moreMenuDiv = document.getElementById("tvLinkWrapper");
        var minX = moreMenuDiv.offsetLeft - 10;
        var maxX = moreMenuDiv.offsetLeft + moreMenuDiv.offsetWidth + 10;
        var minY = moreMenuDiv.offsetTop - 10;
        var maxY = moreMenuDiv.offsetTop + moreMenuDiv.offsetHeight + 10;
      }

      if (tempX < minX || tempX > maxX) hideMenu("tvLinkWrapper");

      return true;
      }
    }
function playPause()
  {
    var plyrObj = document.RVOCX;
    var playState = plyrObj.GetPlayState();
    var playImg = document.getElementById("player_pause");
    if (playState == 4 || playState == 0)
    {
      plyrObj.DoPlay();
      playImg.style.backgroundImage = "url(\"/images/bb11/livefeeds/player_pause.gif\")";
    }
    else
    {
      plyrObj.DoPause();
      playImg.style.backgroundImage = "url(\"/images/bb11/livefeeds/player_play.gif\")";
    }
  }

  function fullScreen()
  {
    document.RVOCX.SetFullScreen();
  }


  function hi_lo()
  {
    var plyrObj = document.RVOCX;
    plyrObj.DoStop();
    document.getElementById("player_quad").style.backgroundImage = "url(\"/images/bb11/livefeeds/player_quad_off.gif\")";
    if (isLowPlaying)
    {
      plyrObj.height = 366;
      plyrObj.SetSource("rtsp://start.real.com/rd?pid=bb11&url=bb_hi.smil");
      isLowPlaying = false;
      document.getElementById("camContainer").style.display = "none";
      document.getElementById("player_lo").style.backgroundImage = "url(\"/images/bb11/livefeeds/player_low_off.gif\")";
      document.getElementById("player_hi").style.backgroundImage = "url(\"/images/bb11/livefeeds/player_high_on.gif\")";
    }
    else
    {
      plyrObj.height = 303;
      plyrObj.SetSource("rtsp://start.real.com/rd?pid=bb11&url=bb_lo.smil");
      isLowPlaying = true;
      document.getElementById("camContainer").style.display = "block";
      document.getElementById("player_lo").style.backgroundImage = "url(\"/images/bb11/livefeeds/player_low_on.gif\")";
      document.getElementById("player_hi").style.backgroundImage = "url(\"/images/bb11/livefeeds/player_high_off.gif\")";
    }

    plyrObj.DoPlay();
  }


  function playStream(streamNum)
  {
    if (nowPlaying != streamNum)
    {
      var plyrObj = document.RVOCX;
                var stream = "rtsp://start.real.com/rd?pid=bb11_live&url=c" + streamNum +"_large.rm";
      plyrObj.DoStop();
      plyrObj.SetSource(stream);
      plyrObj.DoPlay();
      if (nowPlaying > 0)
        document.getElementById("cam" + nowPlaying).style.backgroundImage = "url(\"/images/bb11/livefeeds/bb11-cam" + nowPlaying + ".gif\")";
      document.getElementById("cam" + streamNum).style.backgroundImage = "url(\"/images/bb11/livefeeds/bb11-cam" + streamNum + "-hover.gif\")";
      nowPlaying = streamNum;
    }
  }

  function doQuad()
  {
    var plyrObj = document.RVOCX;
    plyrObj.height = 303;
    plyrObj.SetSource('rtsp://start.real.com/rd?pid=bb11_live&url=quad.rm');
    document.getElementById("camContainer").style.display = "block";
    //document.getElementById("player_quad").style.backgroundImage = "url(\"/images/bb11/livefeeds/player_quad_on.gif\")";
    document.getElementById("player_lo").style.backgroundImage = "url(\"/images/bb11/livefeeds/player_low_on.gif\")";
    document.getElementById("player_hi").style.backgroundImage = "url(\"/images/bb11/livefeeds/player_high_off.gif\")";
    nowPlaying = 0;
            for (i = 1;i<5;i++)
    {
      document.getElementById("cam" + i).style.backgroundImage = "url(\"/images/bb11/livefeeds/bb11-cam" + i + ".gif\")";
    }
  }

        function camOn(divObj,camNum)
  {
    divObj.style.backgroundImage = "url(\"/images/bb11/livefeeds/bb11-cam" + camNum + "-hover.gif\")";
  }

  function camOff(divObj,camNum)
  {
    if (camNum != nowPlaying)
    {
      divObj.style.backgroundImage = "url(\"/images/bb11/livefeeds/bb11-cam" + camNum + ".gif\")";
    }
  }


function mouseSwap(mediaid,mediaclass,watchid,watchclass) {
    el = document.getElementById(mediaid);
    el.className = mediaclass;
    ele = document.getElementById(watchid);
    ele.className = watchclass;
}

function linkCode(obj) {
  s.linkTrackVars='None';
  s.linkTrackEvents='None';
  s.tl(obj,'d','PDF Document');
}

function doOmniture(page,name,value,id, pageNum){
//alert('page: ' + page + ' name: ' +name + ' value: ' + value + 'id: ' + id + ' pageNum: ' + pageNum);
    spTracking.sendLinkEvent(
        {
        eVar17: value,
        prop18: page,
        prop32: name,
        eVar32: name,
        prop48: pageNum,
        eVar48: pageNum
        },
        {
        type: 'custom',
        linkName: value,
        events: 'event8'
        }
    );
}

function doOmniture2(eventName, pageName, eventPathing){
  s.pageName = pageName;
  s.linkTrackVars="prop18, eVar7, eVar17, eVar18, eVar37, events";
  s.linkTrackEvents="event8";
  s.eVar7=spTracking?spTracking._guid:"NoId";
  s.eVar17 = eventName;
  s.eVar18 = pageName;
  s.eVar37 = eventPathing ? "PV:" + s.serverName + "sp" : "sp";
  s.prop18 = "E:" + eventName;
  s.tl(this,'o',"<linkName>");
}


// this one is used in newRadioWrapper.jsp
function omnitureCall(regionName, buttonType, clipTitle, clipID)
{
    s.linkTrackVars="prop29";
    s.prop29 = regionName;
    s.tl(this,'o',buttonType + '|' + clipTitle + '|' + clipID);
}