if(! window.Conviva) { 
    window.Conviva = { };
}
if(! window._CP) { 
    window._CP = { };
    window._CP = window._CP; 
}
Conviva.Exception = function (code, message) {
    this.message = message;
    this.name = "Conviva.Exception";
    this.code = code;
}
Conviva.Exception.prototype.toString = function () {
    return this.name + ': ' + this.code + ' "'+this.message+'"';
}
Conviva.setOptions = function (options) {
try {
    _CP.checkType(options, "object", "setOptions:options");
    var validOptions = { "onLoad" : 1, "autoLoad" : 1,
                         "installUrl" : 1, "installPageUrl" : 1,
                         "installPageWidth" : 1, "installPageHeight" : 1,
                         "propertyId" : 1, "errorReporter" : 1, "logger" : 1, "language" : 1,
                         "installImageIE" : 1, "installImageFF2" : 1,
                         "installImageFF3" : 1, "installImageSafari" : 1 };
    for(var o in options) {
        if(! (o in validOptions)) {
            Conviva.error("Invalid option "+o+" used in Conviva.setOptions");
        }
    }
    if(options.errorReporter) {
        _CP.checkType(options.errorReporter,
                                 "function", "errorReporter argument");
        Conviva.error = options.errorReporter;
    }
    if(options.logger) {
        _CP.checkType(options.logger, "function", "logger argument");
        Conviva.log = options.logger;
    }
    if(options.onLoad) {
        _CP.checkType(options.onLoad, "function", "setOptions:onLoad");
        _CP.options.onLoad = options.onLoad;
    }
    if(! ('autoLoad' in options) || options.autoLoad) {
        if (window.addEventListener) {
            window.addEventListener('load', Conviva.load , false);
        } else {
            window.attachEvent('onload', Conviva.load );
        }
    }
    if(options.language) {
        _CP.checkType(options.language, "string", "setOptions::language");
        _CP.options.language = options.language;
        if(! _CP.translators[options.language]) {
            Conviva.error("Language "+options.language+" is not supported");
        }
    }
    _CP.options.hostUrl = window.location.href;
    if(options.installUrl) {
        _CP.checkType(options.installUrl, "string", "setOptions::installUrl");
        var absUrl;
        if (/^[^:]+:\/\//.test(options.installUrl) ||
            /^\//.test(options.installUrl)) {
            absUrl = options.installUrl;
        } else {
            absUrl = window.location.href;
            absUrl = absUrl.replace(window.location.search, "");
            absUrl = absUrl.replace(window.location.hash, "");
            absUrl = absUrl.replace(/\/[^\/]+$/, "");
            absUrl += "/" + options.installUrl;
        }
        absUrl = _CP.fixUrl(absUrl); 
        _CP.options.installUrl = absUrl;
        absUrl = absUrl.replace(/ConvivaStreamingPlugin.*$/, "ping.ping");
        if(absUrl == _CP.options.installUrl) {
            Conviva.error("Cannot decompose installUrl. Must contain ConvivaStreamingPlugin");
            return;
        }
        _CP.options.pingUrl = absUrl;
    }
    if(! _CP.options.pingUrl) {
        _CP.options.pingUrl = "http://logs.conviva.com/ping.ping";
    }
    var stringProps = [ "installPageUrl",
                        "installImageIE", "installImageFF2", "installImageFF3", "installImageSafari",
                        "propertyId" ]; 
    for(var ii in stringProps) {
        var sp = stringProps[ii];
        if(! options[sp]) continue;
        _CP.checkType(options[sp], "string", "setOptions::"+sp);
        _CP.options[sp] = options[sp];
    }
    var intProps = [ "installPageWidth", "installPageHeight" ];
    for(var ii in intProps) {
        var ip = intProps[ii];
        if(! options[ip]) continue;
        _CP.checkType(options[ip], "number", "setOptions::"+ip);
        _CP.options[ip] = options[ip];
    }
    if (window.addEventListener) { 
        window.addEventListener('unload', Conviva.unload , false);
    } else {
        window.attachEvent('onunload', Conviva.unload );
    }
} catch(e) {
    if(e.name != "Conviva.Exception")
        _CP.bug("Conviva.setOptions", e);
    else
        throw e;
}
};
Conviva.getLoadStatus = function () {
    return _CP.loadStatus;
};
Conviva.isLoaded = function () {
    return (0 == _CP.loadStatus);
};
Conviva.load = function () {
try {
    var options = _CP.options;
    if(Conviva.isLoaded()) {
        _CP.finishLoad(0);
        return;
    }
    _CP.uuid = _CP.getCookieParam('convivauuid');
    if(! _CP.uuid) {
        var freshuuid = Math.round(Math.random() * 1000000000);
        _CP.createCookie("convivauuid", freshuuid, 10000);
        _CP.uuid = _CP.getCookieParam('convivauuid');
    }
    if(! _CP.uuid) {
        _CP.uuid = "0";
    }
    var hostElement;
    hostElement = document.createElement("div");
    document.body.appendChild(hostElement);
    hostElement.style.position = 'absolute'; 
    hostElement.style.margin = "0pt 0pt 0pt 0pt";
    hostElement.style.left = "0px";
    hostElement.style.top = "0px";
    hostElement.innerHTML = _CP.prepareHostHTML();
    _CP.pingDiv = document.getElementById('conviva_ping'); 
    _CP.installDiv = document.getElementById('conviva_install');
    _CP.pluginDiv = document.getElementById('conviva_plugin'); 
    _CP.hostElement = hostElement;
    if(! Conviva.isOsSupported()) {
        var code = 1800;
        _CP.ping({ incompatibleBrowser : 'os',
                              useragent : navigator.userAgent});
        alert(Conviva.errorMessage(code));
        return _CP.finishLoad(code);
    }
    if(! Conviva.isBrowserSupported()) {
        var code = 1801;
        _CP.ping({ incompatibleBrowser : 'browser',
                              useragent : navigator.userAgent});
        alert(Conviva.errorMessage(code));
        return _CP.finishLoad(code);
    }
    if (options.propertyId == null) {
        alert("You must specify propertyId parameter in setOptions()");
    }            
    _CP.plugin = null;
    _CP.loadStatus = 999;
    _CP.loadInstalling = false;
    _CP.startLoading();
} catch(e) {
    _CP.bug("Conviva.load", e); throw e;
}
};
Conviva.unload = function unload () {
try {
    var oldOptions = _CP.options;
    var oldLogger = Conviva.log;
    var oldErrorReporter = Conviva.error;
    try {
        _CP.init ();
    } catch(e) { 
    }
    _CP.options = oldOptions;
    Conviva.log = oldLogger;
    Conviva.error = oldErrorReporter;
} catch(e) {
    _CP.bug("Conviva.unload", e); throw e;
}
};
Conviva.getVersion = function () {
    _CP.checkLoaded();
    try {
        return _CP.executeThrow("pluginGetVersion", "");
    } catch(e) {
        Conviva.error(_CP.i18n(_CP.ERR_LIVEPASS_NOT_LOADED,
                                          "pluginGetVersion"));
    }
};
Conviva.WINDOWS_MEDIA_PLAYER = "WMPlayer";
Conviva.SILVERLIGHT_PLAYER = "Silverlight";
Conviva.FLASH_PLAYER = "Flash";
Conviva.isOsSupported = function () {
    return _CP.osSupported;
};
Conviva.isBrowserSupported = function () {
    return _CP.osSupported && (_CP.browser != "");
};
Conviva.Stream = function (channel, options) {
 try { 
    this.getChannel = function () {
        return this._channel;
    };
    this.setOptions = function (options) {
      try {
        if(! this._options) this._options = { };
        if(! options) return;
        var handlers = [ 'onStatusChange', 'onError', 'onUrlChange' ];
        for(var i in handlers) {
            var opt = handlers[i]
            if(options[opt]) {
                _CP.checkType(options[opt], "function",
                                         "Stream."+opt+" option");
                this._options[opt] = options[opt];
            }
        }
        if(options.urlTransformer) {
            _CP.checkType(options.urlTransformer, "function",
                                     "Stream.urlTransformer option");
            this._options.urlTransformer = options.urlTransformer;
        }
        if(options.customData) {
            this._options.customData = options.customData;
        }
      } catch(e) {
         _CP.bug("Stream.setOptions", e); throw e;
      }
    };
    this._getOptions = function () {
        return this._options;
    }
    this.getStatus = function () {
        return this._status;
    };
    this.getLastError = function () {
        return this._lastError;
    };
    this.clearLastError = function () {
        this._lastError = 0;
    };
    this.getCustomData = function () {
        return this._options.customData;
    };
    this.getInformation = function () {
      try {
        var info = "";
        var pluginVersion = null;
        try {
            pluginVersion = _CP.executeThrow("pluginGetVersion", "");
        } catch(e) {
        }
        if(pluginVersion) {
            info += "<attribute name=\"LivePass version\" value=\""+pluginVersion+"\" />";
        }
        try {
            info += _CP.executeThrow("getStreamInformation",
                                                this.getStreamId());
        } catch(e) {
        }
        return ("<?xml version=\"1.0\" encoding=\"utf-8\"?>"+
                "<channelInformation>"+
                info+
                "</channelInformation>");
      } catch(e) {
         _CP.bug("Stream.getInformation", e); throw e;
      }
    };
    this.getUrl = function getUrl (playerType, noTransform) {
      try {
        var loopback = "127.0.0.1"; 
        if(playerType == Conviva.WINDOWS_MEDIA_PLAYER) {
            loopback = "127.1.1.1";
        }
        var needToConfigProxy;
        try {
            needToConfigProxy = _CP.executeThrow("getUserNeedsToConfigProxyBypass",
                                                            playerType + "." + _CP.browser);
        } catch(e) {
            needToConfigProxy = "0";
            _CP.bug("Conviva.ProxyBypass", e);
        }
        if ( needToConfigProxy == "1") {
            _CP.showErrorNeedToConfigProxy();
        }
        var protocol = _CP.playerProtocol(playerType);
        var res = (protocol + "//" + loopback +
                   ":" + _CP.getStreamingPort() +
                   this._streamId);
        if (noTransform || ! this._options.urlTransformer) {
            return res;
        } else {
            return this._options.urlTransformer(res);
        }
      } catch(e) {
         _CP.bug("Stream.getInformation", e); throw e;
      }
    };
    this.playStateChanged = function (newState) {
      try {
        var newStateStr = "unknown";
        if(newState == 1){
            newStateStr = "stopped";
        } else if(newState == 3) {
            newStateStr = "playing";
        } else if(newState == 6) {
            newStateStr = "buffering";
        } else if(newState == 10) {
            newStateStr = "ready";
        } else {
            newStateStr = "unknown ("+newState+")";
        }
        Conviva.log("playStateChanged("+this._streamId+","+newStateStr+")");
        var stats = (newState.toString() + 
                     " 0" + 
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " 0" +
                     " " + this.getStreamId());
        try {
            _CP.executeThrow("sendMediaPlayerState", stats);
        }  catch (e) {
        }
      } catch(e) {
         _CP.bug("Stream.playStateChanged", e); throw e;
      }
    };
    this._playingPlayerId = null;
    this._playerUrlChange = null;    
    this.connectPlayer = function (playerId, playerUrlChange) {
      try {
        if(this._playingPlayerId)
            Conviva.error("The stream is already playing on player "+
                          this._playingPlayerId);
        this._playingPlayerId = playerId;
        this._playerUrlChange = playerUrlChange;
      } catch(e) {
         _CP.bug("Stream.connectPlayer", e); throw e;
      }
    };
    this.disconnectPlayer = function () {
        this._playingPlayerId = null;
        this._playerUrlChange = null;
    };
    _CP.checkLoaded();
    this.setOptions(options);
    this._channel = channel;
    this._status = 0;
    this._lastError = 0;
    this._mainOnStatusChange = function (statusCode, data) {
      try {
        this._status = statusCode;
        if (this._options && this._options.onStatusChange) {
            this._options.onStatusChange (this, statusCode,
                                          _CP.statusMessage(statusCode));
        }
      } catch(e) {
         _CP.bug("Stream._mainOnStatusChange", e); throw e;
      }
    };
    if(this._channel.search(/\?/) > 0) {
        this._streamId = "/" + this._channel+"&sid=";
    } else {
        this._streamId = "/" + this._channel+"?sid=";
    }
    this._streamId = _CP.newUniqueId(this._streamId);
    this._streamId += "&uuid="+_CP.uuid;
    this._streamId += "&propid="+_CP.options.propertyId;
    this.getStreamId = function () {
        return this._streamId;
    };
    this._mainOnError = function (errorCode, data) {
      try {
        this._lastError = errorCode;
        if (this._options && this._options.onError) {
            this._options.onError (this, errorCode,
                                   Conviva.errorMessage(errorCode));
        }
      } catch(e) {
         _CP.bug("Stream._mainOnError", e); throw e;
      }
    };
    this._mainOnStreamingPortChange = function _mainOnStreamingPortChange (newport) {
      try {
        if(this._options && this._options.onUrlChange) {
            Conviva.log("invoking onUrlChange to "+this.getStreamId());
            this._options.onUrlChange(this);
        }
        if(this._playingPlayerId && this._playerUrlChange) {
            this._playerUrlChange(this, this._playingPlayerId);
        }
      } catch(e) {
         _CP.bug("Stream._mainOnStreamingPortChange", e); throw e;
      }
    };
    this.cleanup = function () {
      try {
        this._options = null;
        this._channel = null;
        this.disconnectPlayer();
      } catch(e) {
         _CP.bug("Stream.cleanup", e); throw e;
      }
    };
    _CP.streams[this._streamId] = this;
} catch(e) {
    _CP.bug("Conviva.Stream", e); throw e;
}
};
Conviva.getStreamById = function (streamId) {
try {
    var res = _CP.streams[streamId];
    if(! res) {
        _CP.bug("getStreamById:"+streamId);
        for (var s in _CP.streams) {
            Conviva.log("Have stream:"+s);
        }
    }
    return res;
} catch(e) {
    _CP.bug("Conviva.getStreamById", e); throw e;
}
};
Conviva.StreamExt = { };
Conviva.StreamExt.createInstance = function (externalId, channel, options) {
try {
    Conviva.log("StreamExt.createInstance("+externalId+", "+channel+")");
    var unwrappedOptions = { };
    for(var opt in options) {
        var unwrapOpt = options[opt]; 
        if(opt == 'onStatusChange') {
            unwrapOpt = (function (str1, code, msg) {
                             eval("try { document.getElementById('"+externalId+"')."+
                                  "onStreamStatusChange('"+str1._streamId+
                                  "',"+code+",'"+msg+"') } catch(e) {}");
                });
        } else if (opt == 'onError') {
            unwrapOpt = (function (str1, code, msg) {
                             eval("try { document.getElementById('"+externalId+"')."+
                                  "onStreamError('"+str1._streamId+
                                  "',"+code+",'"+msg+"') } catch(e) {}");
                });
        } else if (opt == 'onUrlChange') {
            unwrapOpt = (function (str1) {
                             eval("try { document.getElementById('"+externalId+"')."+
                                  "onStreamUrlChange('"+str1._streamId+"') } catch(e) {}");
                });
        } else {
            Conviva.error("Conviva.StreamExt.createInstance does not support the option: "+opt);
        }
        unwrappedOptions[opt] = unwrapOpt;
    }
    var str = new Conviva.Stream(channel, unwrappedOptions);
    Conviva.log("StreamExt.createInstance returns "+str._streamId);
    return str._streamId;
} catch(e) {
    _CP.bug("Conviva.StreamExt.createInstance", e); throw e;
}
};
Conviva.StreamExt.getUrl = function (externalId, streamId) {
try {
    Conviva.log("StreamExt.getUrl("+externalId+", "+streamId+")");
    var str = _CP.streams[streamId];
    if(! str) return null;
    try {
        var url = str.getUrl(Conviva.FLASH_PLAYER);
        Conviva.log("Returning url "+url);
        return url;
    } catch(e) {
        Conviva.log("Error: "+_CP.decodeExc(e));
        return null;
    }
} catch(e) {
    _CP.bug("Conviva.StreamExt.getUrl", e); throw e;
}
};
Conviva.StreamExt.getStatus = function (externalId, streamId) {
try {
    var str = _CP.streams[streamId];
    if(! str) return -1;
    return str.getStatus();
} catch(e) {
    _CP.bug("Conviva.StreamExt.getStatus", e); throw e;
}
};
Conviva.StreamExt.connectPlayer = function (externalId, streamId, playerId, playerOnUrlChange) {
try {
    var str = _CP.streams[streamId];
    if(! str) return false;
    var unwrapOnUrlChange =
         (function (str1) {
             eval("document.getElementById('"+externalId+"')."+
                  playerOnUrlChange+"('"+str1._streamId+"', '"+playerId+"')");
                });
    try {
        str.connectPlayer(playerId, unwrapOnUrlChange);
        return true;
    } catch(e) {
        Conviva.log("Error: "+_CP.decodeExc(e));
        return false;
    }
} catch(e) {
    _CP.bug("Conviva.StreamExt.connectPlayer", e); throw e;
}
};
Conviva.StreamExt.disconnectPlayer = function (externalId, streamId) {
try {
    var str = _CP.streams[streamId];
    if(! str) return false;
    try {
        str.disconnectPlayer();
        return true;
    } catch(e) {
        Conviva.log("Error: "+_CP.decodeExc(e));
        return false;
    }
} catch(e) {
    _CP.bug("Conviva.StreamExt.disconnectPlayer", e); throw e;
}
};
Conviva.StreamExt.lastError = function (externalId, streamId) {
try {    
    var str = _CP.streams[streamId];
    return str.getLastError();
} catch(e) {
    _CP.bug("Conviva.StreamExt.lastError", e); throw e;
}
};
Conviva.StreamExt.getInformation = function (externalId, streamId) {
try {
    var str = _CP.streams[streamId];
    return str.getInformation();
} catch(e) {
    _CP.bug("Conviva.StreamExt.getInformation", e); throw e;
}
};
Conviva.StreamExt.cleanup = function (externalId, streamId) {
try {
    var str = _CP.streams[streamId];
    str.cleanup ();
} catch(e) {
    _CP.bug("Conviva.StreamExt.cleanup", e); throw e;
}
};
Conviva.StreamExt.playStateChanged = function (externalId, streamId, newState) {
try {
    var str = _CP.streams[streamId];
    str.playStateChanged (newState);
} catch(e) {
    _CP.bug("Conviva.StreamExt.playStateChanged", e); throw e;
}
};
_CP.guidVersion="ABC4";
_CP.mimeSuffix=".4";
_CP.progidSuffix=".4";
_CP.versionMajor=1;
_CP.versionMinor=10;
_CP.versionRelease=8;
_CP.versionSvn=20921;
_CP.pluginMinimumRequiredVersion="1.4.0.0";
Conviva.version = (_CP.versionMajor+"."+
                   _CP.versionMinor+"."+
                   _CP.versionRelease+"."+
                   _CP.versionSvn);
_CP.version2 = (_CP.versionMajor+"."+
                           _CP.versionMinor);
_CP.version3 = (_CP.versionMajor+"."+
                           _CP.versionMinor+"."+
                           _CP.versionRelease);
_CP.activexInterface = "RINERAX.RineraXCtrl"+_CP.progidSuffix;
_CP.clsid = "4819DFDF-"+_CP.guidVersion+"-488C-A323-919848C51175";
_CP.mime = "application/x-rinera-proxy"+_CP.mimeSuffix;
Conviva.pluginVersion = "unknown";
Conviva.proxyVersion  = "unknown";
_CP.detectBrowser = function (userAgent) {
    if( ! userAgent)
        userAgent = navigator.userAgent;
    _CP.platform = ""; 
    _CP.browser = "";  
    _CP.osbr    = "";  
    _CP.useActiveX = false;  
    _CP.useGecko   = false;  
    _CP.useGecko19 = false;  
    _CP.winVersion = ""; 
    _CP.osSupported = false; 
    if(/MSIE (6|7|8).*Windows NT (5\.0|5\.1|5\.2|6\.0|6\.1)/.test(userAgent)) {
        _CP.browser = "IE";
        _CP.platform = "Win";
        _CP.useActiveX = true;
        _CP.osbr = "win32-ie";
    } else if(/Windows NT (5\.1|6\.0|6\.1).*Firefox\/(2|3)/.test(userAgent)) {
        _CP.browser = "FF";
        _CP.platform = "Win";
        _CP.useGecko = true;
        _CP.osbr = "win32-ff2";
        if(/rv:1\.9/.test(userAgent)) {
            _CP.useGecko19 = true;
            _CP.osbr = "win32-ff3";
        }
    } else if(/Macintosh.*Intel Mac OS X(;| 10.5).*Firefox\/(2|3)/.test(userAgent)) {
        _CP.browser = "FF";
        _CP.platform = "Mac";
        _CP.useGecko = true;
        _CP.osbr = "darwin-ff2";
        if(/rv:1\.9/.test(userAgent)) {
            _CP.useGecko19 = true;
            _CP.osbr = "darwin-ff3";
        }
    } else if(/Macintosh.*Intel Mac OS X(;| 10.5).+AppleWebkit\/5.*Safari/i.test(userAgent)) {
        _CP.browser = "Safari";
        _CP.platform = "Mac";
        _CP.useGecko = true;
        _CP.useGecko19 = false;
        _CP.osbr = "darwin-sf";
    } else if(/Macintosh.*Intel Mac OS X(;| 10.6).*Firefox\/(2|3)/.test(userAgent)) {
        _CP.browser = "FF";
        _CP.platform = "Mac";
        _CP.useGecko = true;
        _CP.osbr = "darwin-ff2";
        if(/rv:1\.9/.test(userAgent)) {
            _CP.useGecko19 = true;
            _CP.osbr = "darwin-ff3";
        }
    } else if(/Macintosh.*Intel Mac OS X(;| 10_6_1).+AppleWebkit\/5.*Safari/i.test(userAgent)) {
        _CP.browser = "Safari";
        _CP.platform = "Mac";
        _CP.useGecko = true;
        _CP.useGecko19 = false;
        _CP.osbr = "darwin-sf";
    } 
    var result = userAgent.match(/.*Windows NT (5\.0|5\.1|5\.2|6\.0|6\.1)/);
    if(result != null) {
        _CP.winVersion = result[1];
    }
    if(_CP.platform != "") {
        _CP.osSupported = true;
    } else if(/Windows NT (5\.1|6\.0||6\.1)/.test(userAgent)) {
        _CP.osSupported = true; 
    } else if(/Macintosh.*Intel Mac OS X 10.5.*AppleWebkit\/5/.test(userAgent)) {
        _CP.osSupported = true; 
    } else if(/Macintosh.*Intel Mac OS X 10.5*Firefox/.test(userAgent)) {
        _CP.osSupported = true;
    } else if(/Macintosh.*Intel Mac OS X 10_6_1*AppleWebkit\/5/.test(userAgent)) {
        _CP.osSupported = true; 
    } else if(/Macintosh.*Intel Mac OS X 10_6_1*Firefox/.test(userAgent)) {
        _CP.osSupported = true;
    }
};
_CP.detectBrowser ();
_CP.useDmgInstaller = false;
if(_CP.browser == "Safari") {
    _CP.useDmgInstaller = true;
}
_CP.players = { };
_CP.streams = { };
_CP.ConfigProxyMessageShown = false;
_CP.checkType = function (obj, typname, errorMsg) {
    if(! obj)
        Conviva.error(errorMsg+". Found null, expected "+typname);
    try {
        if(typeof(obj) != typname) throw new Error();
    } catch(e) {
        Conviva.error(errorMsg+". Found type "+typeof(obj)+", expected "+typname+". "+
                             _CP.decodeExc(e))
    }
};
_CP.lastUniqueId = 0;
_CP.newUniqueId = function (prefix) {
    _CP.lastUniqueId ++;
    return prefix + "_" + _CP.lastUniqueId;
};
_CP.checkLoaded = function () {
    if(! Conviva.isLoaded())
        Conviva.error(_CP.i18n(_CP.ERR_LIVEPASS_NOT_LOADED, 
                                          "checkLoaded"));
};
_CP.typeOfPlugin =
    (_CP.browser=="FF" ? "function" : "object");
_CP.pluginDomId = "convivaLivePassPluginObj";
_CP.init = function init () {
    for(var p in _CP.players) {
        try {
            if(_CP.players[p]) 
                _CP.players[p].cleanup ();
        } catch(e) { }
    }
    _CP.players = { };
    for(var strid in _CP.streams) {
        try {
            _CP.streams[strid].cleanup();
        } catch(e) { }
    }
    _CP.streams = {};
    if(_CP.plugin) {
        Conviva.log("Stop LivePass");
        try { _CP.executeThrow("pluginStopProxy", ""); } catch(e) { };
        _CP.plugin = null;
    }
    Conviva.log = function (msg) {
        return;
    };
    Conviva.error = function (msg) {
        throw new Conviva.Exception(100, "Conviva LivePass: "+msg);
    };
    try {
        if(_CP.hostElement)
            _CP.hostElement.innerHTML = "";
    } catch(e) { };
    _CP.WMPdetected = false;
    _CP.options = {
        autoLoad : true,
        language : 'en-US',
        propertyId : null, 
        installPageUrl : 'ConvivaLivePassInstall.html',
        installImageIE : "installer_files/Install_instruc_IE_PC.jpg",
        installImageFF2 : "installer_files/Install_instruc_FF2_PC.jpg",
        installImageFF3 : "installer_files/Install_instruc_FF3_PC.jpg",
        installImageSafari : "installer_files/Install_instruc_Safari_MAC.jpg",
        installPageWidth : 900,
        installPageHeight : 620
    };
    _CP.loadStatus = 999; 
    _CP.lastUniqueId = 0;
};
_CP.init ();
_CP.startLoading = function () {
try {
    if(_CP.loadInstalling) {
        try {
            navigator.plugins.refresh();
        } catch(e) { }
    }
    var hasPlugin = false;
    if(_CP.browser == "IE") {
        try {
            var control = new ActiveXObject(_CP.activexInterface);
            control = null;
            hasPlugin = true;
        } catch(e) {
            Conviva.log("ActiveX not found");
        }
    } else if(_CP.useGecko) {
        for(var pidx=0;pidx<navigator.plugins.length && !hasPlugin ; pidx++) {
            var plug = navigator.plugins[pidx];
            var nrMimes = 0;
            try {
                nrMimes = plug.length;
            } catch(e) { };
            for(var typeidx=0;typeidx<nrMimes;typeidx++) {
                if(plug[typeidx].type == _CP.mime) {
                    hasPlugin = true;
                    break;
                }
            }
        }
        if (! hasPlugin && _CP.browser == "FF" && ! _CP.useGecko19) {
            Conviva.log("Looking for convivaPluginInstalled cookie");
            if (_CP.getCookieParam("convivaPluginInstalled") == 'true') {
                Conviva.log("Found the convivaPluginInstalled cookie");
                hasPlugin = true;
            }
        }
        if(! hasPlugin) {
            Conviva.log("MIME type "+
                        _CP.mime+" not found");
        }
    }
    if(! hasPlugin) {
        if(_CP.loadInstalling || ! _CP.options.installUrl) {
            return _CP.afterLoad(1010);
        } else {
            return _CP.startInstall();
        }
    }
    Conviva.log("Found the plugin");
    var domid = _CP.pluginDomId;
    if(_CP.browser == "IE") {
        _CP.pluginDiv.innerHTML =
        '<object id="' + domid + '" ' + 
        '       classid="CLSID:'+_CP.clsid+'"' +
        '       width="0" ' +
        '       height="0" ' +
        '       type="application/x-oleobject">' +
        '</object>' +
        '<script language="JavaScript" FOR="'+domid+'" EVENT="OnEvent(ename,eargs)">' +
        '   window._CP.eventListener(ename, eargs);' + 
        '</script>';
    } else if(_CP.useGecko) {
        _CP.pluginDiv.innerHTML = 
        '<embed type="'+_CP.mime+'" id="'+domid+'" '+
        '  width="0" height="0">';
    }
    _CP.timer1003 = 3000; 
    setTimeout(_CP.checkPluginLoaded, 200);
} catch(e) {
    _CP.bug("startLoading", e); throw e;
}
};
_CP.checkPluginLoaded = function () {
try {
    var code = _CP.loadCheckPluginVersion ();
    if(code == 0) {
        return _CP.afterLoad(code);
    }
    var msg = Conviva.errorMessage(code); 
    if(code == 1003) {
        if(! _CP.loadInstalling) {
            _CP.timer1003 -= 500;
            if(_CP.timer1003 > 0) {
                setTimeout(_CP.checkPluginLoaded, 500);
                return 1003;
            } else {
                if (! _CP.options.noInteractiveLoad)
                    alert(msg);
                return _CP.afterLoad(code);
            }
        }
        return _CP.afterLoad(code);
    }
    if(code == 1007) {
        if(! _CP.options.noInteractiveLoad) 
            alert(msg);
        return _CP.afterLoad(code);
    }
    if(code == 1009) {
        _CP.pluginDiv.innerHTML = "";
        _CP.plugin = null;
    }
    if(! _CP.loadInstalling && _CP.options.installUrl) {
        var doInstall = true;
        if(! _CP.options.noInteractiveLoad) {
            msg += "\n" + _CP.i18n(_CP.MSG_UPDATE_CONSENT_REQ);
            doInstall = confirm(msg);
        }
        if(doInstall) {
            return _CP.startInstall();
        }
    }
    return _CP.afterLoad(code);
} catch(e) {
    _CP.bug("checkPluginLoaded", e); throw e;
}
};
_CP.loadCheckPluginVersion = function() {    
    var domid = _CP.pluginDomId;
    _CP.plugin = document.getElementById(domid);
    if(_CP.plugin == null) {
        Conviva.log("Cannot get the plugin");
        return 1011;
    }
    Conviva.log("loadPlugin: test if plugin works");
    var version = "";
    try {
        if(_CP.useGecko) {
            var callback = { 
                onEvent : function onEvent(event, args) {
                    if(typeof window._CP == 'undefined') return;
                    window._CP.eventListener(event,args);
                }
            };
            _CP.plugin.setCallback(callback);
        }
        version = _CP.plugin.execute("pluginGetVersion", "");
    } catch(e) {
        Conviva.log("Plugin does not respond");
        return 1011;
    }
    Conviva.log("Found installed version "+version);
    Conviva.pluginVersion = version;
    if(version.substr(0, 1) == "!") {
        return parseInt(version.substr(1));
    }
    var versionArray = version.split('.');
    while(versionArray.length < 4) versionArray.push(0);
    while(versionArray.length > 4) versionArray.pop();
    var expectedArray = _CP.pluginMinimumRequiredVersion.split('.');
    for(var idx=0;idx<4;idx++) {
        if(parseInt(versionArray[idx]) > parseInt(expectedArray[idx]))
            break;
        if(parseInt(versionArray[idx]) < parseInt(expectedArray[idx])) {
            Conviva.log("Found installed but different version "+version+
                        ". Expecting version "+_CP.pluginMinimumRequiredVersion);
            return 1009;
        }
    }
    try {
        var res = _CP.plugin.execute("pluginStartProxy", "");
        Conviva.log("pluginStartProxy returns "+res);
        Conviva.proxyVersion = _CP.plugin.execute("getProxyVersion", "");
        if(res.substr(0, 1) == "!") {
            return parseInt(res.substr(1));
        } else {
            code = parseInt(res);
            return code;
        }
    } catch (e) {
        Conviva.log("pluginStartProxy: "+_CP.decodeExc(e));
        return 1011;
    }
};
_CP.afterLoad = function afterLoad (code) {
    if(_CP.loadInstalling) {
        if(code == 0 || code == 1007) {
            _CP.hideInstaller();
            setTimeout("_CP.finishLoad("+code+")", 20);
            return;
        } else {
            setTimeout(_CP.startLoading, 2000);
            return;
        }
    } else {
        if(code != 0) {
            _CP.pluginDiv.innerHTML = "";
            _CP.plugin = null;
        }
        _CP.finishLoad(code);
    }
}; 
_CP.finishLoad = function finishLoad (code) {
try {
    _CP.loadStatus = code;
    _CP.loadInstalling = false;
    _CP.ping({startPlugin : code, jsver : Conviva.version, pluginver : Conviva.pluginVersion });
    if(_CP.options.onLoad) {
        _CP.options.onLoad(code);
    }
} catch(e) {
    _CP.bug("finishLoad", e); throw e;
}
};
_CP.prepareHostHTML = function () {
    return (
            "<div id='conviva_ping' style='visibility:hidden' width=0px height=0px></div>" +
            "<div id='conviva_grey_box' style='position:absolute;background-color:grey'></div>" +
            "<div id='conviva_install' style='position:absolute;visibility:hidden;background-color:white'></div>" +
            "<div id='conviva_plugin'></div>");
};
_CP.jQuery_offset = function(elem) { 
    var left = 0, top = 0, results; 
    var safari = (_CP.browser == "Safari");
    var mozilla = (_CP.browser == "FF");
    function add(l, t) { 
        left += parseInt(l, 10) || 0; 
        top += parseInt(t, 10) || 0; 
    }
    function border(elem) { 
        add( elem.style["borderLeftWidth"], elem.style["borderTopWidth"] ); 
    } 
    if ( elem ) {
        var parent       = elem.parentNode, 
            offsetChild  = elem, 
            offsetParent = elem.offsetParent, 
            doc          = elem.ownerDocument, 
            css          = function (e, v) { return e.style[v]; },
            fixed        = (elem.style['position'] == 'fixed');
        var safari2 = safari;
        if(safari) {
            safari2 = (navigator.userAgent.match(/[Ss]afari: (\d+)/) || [ ])[0] < 522;
        }
        if ( !(mozilla && elem == document.body) && elem.getBoundingClientRect ) { 
            var box = elem.getBoundingClientRect(); 
            add(box.left + Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft), 
                box.top  + Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop)); 
            add( -doc.documentElement.clientLeft, -doc.documentElement.clientTop ); 
        } else { 
            add( elem.offsetLeft, elem.offsetTop ); 
            while ( offsetParent ) { 
                add( offsetParent.offsetLeft, offsetParent.offsetTop ); 
                if ( mozilla && !/^t(able|d|h)$/i.test(offsetParent.tagName) || safari && !safari2 ) 
                    border( offsetParent ); 
                if ( !fixed && css(offsetParent, "position") == "fixed" ) 
                    fixed = true; 
                offsetChild  = /^body$/i.test(offsetParent.tagName) ? offsetChild : offsetParent; 
                offsetParent = offsetParent.offsetParent; 
            } 
            while ( parent && parent.tagName && !/^body|html$/i.test(parent.tagName) ) { 
                if ( !/^inline|table.*$/i.test(css(parent, "display")) ) 
                    add( -parent.scrollLeft, -parent.scrollTop ); 
                if ( mozilla && css(parent, "overflow") != "visible" ) 
                    border( parent ); 
                parent = parent.parentNode; 
            } 
            if ( (safari2 && (fixed || css(offsetChild, "position") == "absolute")) || 
                 (mozilla && css(offsetChild, "position") != "absolute") ) 
                add( -doc.body.offsetLeft, -doc.body.offsetTop ); 
            if ( fixed ) 
                add(Math.max(doc.documentElement.scrollLeft, doc.body.scrollLeft), 
                    Math.max(doc.documentElement.scrollTop,  doc.body.scrollTop)); 
        } 
        results = { top: top, left: left };
    } 
    return results; 
}; 
_CP.computeOffsets = function (elem) {
    var result = { left : 0, top : 0,
                   pageWidth : window.offsetWidth, pageHeight : window.offsetHeight,
                   windowWidth : window.offsetWidth, windowHeight : window.offsetHeight
                 };
    var doc = elem.ownerDocument;
    try {
    	var xScroll, yScroll, windowWidth, windowHeight;
    	var isFrame = false;
    	if (window.innerHeight && window.scrollMaxY) {
    		xScroll = doc.body.scrollWidth;
    		yScroll = (isFrame ? parent.innerHeight : window.innerHeight) +
                      (isFrame ? parent.scrollMaxY : window.scrollMaxY);
    	} else if (doc.body.scrollHeight > doc.body.offsetHeight){ 
    		xScroll = doc.body.scrollWidth;
    		yScroll = doc.body.scrollHeight;
    	} else { 
    		xScroll = doc.getElementsByTagName("html").item(0).offsetWidth;
    		yScroll = doc.getElementsByTagName("html").item(0).offsetHeight;
    		xScroll = (xScroll < doc.body.offsetWidth) ? doc.body.offsetWidth : xScroll;
    		yScroll = (yScroll < doc.body.offsetHeight) ? doc.body.offsetHeight : yScroll;
    	}
    	if (window.innerHeight) {	
    		windowWidth = (isFrame) ? parent.innerWidth : window.innerWidth;
    		windowHeight = (isFrame) ? parent.innerHeight : window.innerHeight;
    	} else if (document.documentElement && document.documentElement.clientHeight) { 
    		windowWidth = doc.documentElement.clientWidth;
    		windowHeight = doc.documentElement.clientHeight;
    	} else if (document.body) { 
    		windowWidth = doc.getElementsByTagName("html").item(0).clientWidth;
    		windowHeight = doc.getElementsByTagName("html").item(0).clientHeight;
    		windowWidth = (windowWidth == 0) ? doc.body.clientWidth : windowWidth;
    		windowHeight = (windowHeight == 0) ? doc.body.clientHeight : windowHeight;
    	}
        result.pageHeight = (yScroll < windowHeight) ? windowHeight : yScroll;
        result.pageWidth = (xScroll < windowWidth) ? windowWidth : xScroll;
        result.windowHeight = windowHeight;
        result.windowWidth = windowWidth;
        var offset = _CP.jQuery_offset (elem);
        result.left = offset.left;
        result.top  = offset.top;
    } catch(e) {    }
    return result;
};
_CP.startInstall = function () {
    if(_CP.getCookieParam("convivaDownloadClicked") == "true") {
        _CP.loadInstalling = true; 
        Conviva.log("Found cookie convivaDownloadClicked");
        if(_CP.getCookieParam("convivaPluginInstalled") == "true") {
            Conviva.log("Skip to startLoading");
            _CP.startLoading ();
            return;
        } else {
            Conviva.log("Skip to installDownloadClicked");
            Conviva.installDownloadClicked ();
            return;
        }
    }
    _CP.ping({ installPlugin : 'start' });
    _CP.positionInstallWindows ();
    if(0) {
        if (typeof window.addEventListener != 'undefined') { 
            window.addEventListener('resize', _CP.positionInstallWindows , false);
        } else {
            window.attachEvent('onresize', _CP.positionInstallWindows );
        }
    }
    _CP.fadeGreyBox(10);
};
_CP.positionInstallWindows = function () {
    var grey_box = document.getElementById('conviva_grey_box');
    var offsets = _CP.computeOffsets(grey_box);
    var left = - offsets.left;
    var top = - offsets.top;
    grey_box.style.position = 'absolute';
    grey_box.style.opacity = "0.0"; 
    grey_box.style.filter = "alpha(opacity=0)";
    grey_box.style.left = left + "px";
    grey_box.style.top = top + "px";
    grey_box.style.visibility = "visible";
    grey_box.style.display = "block";
    grey_box.style.zIndex = 999;
    grey_box.style.height = offsets.pageHeight + "px";
    grey_box.style.width = offsets.pageWidth + "px";
    grey_box.style.position = 'absolute';
    grey_box.style.backgroundColor = "black";
    var w = window;
    var installer_panel = _CP.installDiv;
    installer_panel.style.position = 'absolute';
    installer_panel.style.visibility = "visible";
    installer_panel.style.display = "block";
    installer_panel.style.width = _CP.options.installPageWidth+"px";
    installer_panel.style.height = _CP.options.installPageHeight+"px";
    installer_panel.style.margin = "0 auto";
    installer_panel.style.zIndex = 100000;
    installer_panel.style.top = (10 + top) + "px";
    var ip_left = Math.round((document.body.clientWidth -
                              installer_panel.clientWidth) / 2 + left);
    if(ip_left < 0) ip_left = 0;
    installer_panel.style.left = ip_left + "px";
    installer_panel.innerHTML = ("<iframe id='conviva_install_iframe' "+
                                 " src='"+_CP.fixUrl(_CP.options.installPageUrl)+"' "+
                                 " width='100%' "+
                                 " height='100%' "+
                                 "/>");
    installer_panel.style.opacity = "1.0";
    installer_panel.style.filter = "alpha(opacity=100)";
    installer_panel.style.backgroundColor = "white";
    if(_CP.browser == "FF" && _CP.platform == "Win") {
        _CP.modifySeeThroughObjects("hidden");
        if(! _CP.useGecko19) {
            _CP.createCookie("convivaInstallTurnOnObjects", "1",
                                        1.0 / (24.0 * 60.0)); 
        }
    }
};
_CP.modifySeeThroughObjects = function (vis) { 
    var objects = document.getElementsByTagName("object");
    for (var oi in objects) {
        var obj = objects[oi];
        if(! obj) continue;
        if(obj.codeBase && /swflash/i.test(obj.codeBase)) {
            obj.style.visibility = vis;
            continue;
        }
        if(obj.type == "application/x-shockware-flash") {
            obj.style.visibility = vis;
            continue;
        }
    }
};
_CP.fadeGreyBox = function (opacity) {
try {
    var grey_box = document.getElementById('conviva_grey_box');
    grey_box.style.opacity = "0."+opacity;
    grey_box.style.filter = "alpha(opacity="+opacity+")";
    if(opacity >= 60) {
        if(_CP.browser == "FF") {
            var instIFrame = document.getElementById("conviva_install_iframe");
            if(instIFrame) { 
                var hasPingUrl;
                try {
                    hasPingUrl = (instIFrame.contentDocument.baseURI.indexOf("ping.ping") >= 0);
                } catch(e) {
                    hasPingUrl = true;
                }
                if(hasPingUrl) {
                    _CP.positionInstallWindows();
                    _CP.ping({ error : 'ff_install_iframe_error' }); 
                    alert(_CP.i18n(_CP.ERR_FIREFOX_PLUGIN_DISABLED));
                }
            }
        }
        return; 
    }
    var nextOpacity = opacity + 3;
    setTimeout(function () { _CP.fadeGreyBox(nextOpacity); },
               10);
} catch(e) { _CP.bug("fadeGreyBox", e); throw e; } 
};
_CP.fixUrl = function (url) {
    return url.replace('%best', _CP.version2);
};
Conviva.installInstructionsHtml = function (opts) {
    var image;
    var width = "855";
    if(opts.width) width = opts.width;
    var height = "374";
    if(opts.height) height = opts.height;
    var alt = "Installation instructions ";
    if(opts.alt) alt = opts.alt;
    if       (_CP.browser == 'IE') {
        image = _CP.options.installImageIE;
    } else if(_CP.browser == 'Safari') {
        image = _CP.options.installImageSafari;
    } else if(_CP.browser == 'FF' && ! _CP.useGecko19) {
        image = _CP.options.installImageFF2;
    } else if(_CP.browser == 'FF' && _CP.useGecko19) {
        image = _CP.options.installImageFF3;
    }
    if(! image)
        return "";
    image = _CP.fixUrl(image);
    return ('<img src="'+image+'" '+
            ' alt="'+alt+'" width="'+width+'" height="'+height+'" onclick="findConviva(); Conviva.installDownloadClicked();"/>');
};
Conviva.installDownloadClicked = function () {
try {
    if(_CP.browser == "FF") {
        _CP.ping({ eulaAgree : "true" });
        setTimeout(_CP.finishDownloadClicked, 1800);
    } else {
        setTimeout(function () { _CP.ping({ eulaAgree : "true"})}, 1000);
        _CP.finishDownloadClicked();
    }
} catch(e) {
    _CP.bug("installDownloadClicked", e); throw e;
}
};
_CP.finishDownloadClicked = function ()   {
try {
    if(_CP.browser == "FF") {
        var installer_panel = _CP.installDiv;
        installer_panel.innerHTML = ("<iframe id='conviva_install_iframe' "+
                                     " src='"+_CP.fixUrl(_CP.options.installPageUrl)+"' "+
                                     " width='100%' "+
                                     " height='100%' "+
                                     "/>");
    }
    var installUrl = _CP.options.installUrl; 
    installUrl += "-" + _CP.osbr; 
    if(_CP.browser == "IE") {
        installUrl += ".exe";
    } else if(_CP.browser == "FF") {
        installUrl += ".xpi";
    } else if(_CP.browser == "Safari") {
        installUrl += ".dmg";
    }
    if(! /file:/.test(installUrl)) {
        installUrl += "?uuid=" + _CP.uuid;
        installUrl += "&propid=" + _CP.options.propertyId;
    }
    if(_CP.browser == "IE") {
        installUrl += "&ext=.exe";
    }
    _CP.loadInstalling = true;
    if(_CP.browser == "FF") {
        if(! _CP.useGecko19) {
            _CP.createCookie("convivaDownloadClicked", "true",
                                        1.0 / (24.0 * 60.0)); 
        }
        var xpi = { 'Conviva LivePass' : installUrl+"&ext=.xpi" };
        setTimeout(function () { InstallTrigger.install(xpi, window.Conviva_FF_InstallTrigger_callback); },
                   50);
        return;
    } else {
        top.location = installUrl;
        _CP.loadInstalling = true;
        setTimeout(_CP.startLoading, 2000);
    }
} catch(e) {
    _CP.bug("installDownloadClicked", e); throw e;
}
};
window.Conviva_FF_InstallTrigger_callback = function (url, status) {
try {
    Conviva.log("InstallTrigger_callback("+url+", "+status+")");
    _CP.hideInstaller ();
    if(status == 0) {
        _CP.loadInstalling = true;
        if(_CP.browser == "FF" &&
           ! _CP.useGecko19 && _CP.platform == "Mac") {
            window.location.reload(false);
        } else {
            _CP.createCookie("convivaPluginInstalled", 'true',
                                        30.0 / (24.0 * 3600.0)); 
            Conviva.log("Installing the convivaPluginInstalled cookie");
            setTimeout(_CP.startLoading, 100);
        }
    } else {
        var checkStr = "Windows NT";
        var indexPos = navigator.userAgent.indexOf(checkStr);
        var osVersion = navigator.userAgent.substr(indexPos+checkStr.length+1, 3);
        if (parseFloat(osVersion) >= 6 ) {
            if ( status == -240 ) {
                alert(_CP.i18n(_CP.ERR_RUN_AS_ADMINISTRATOR));
                return;
            }
        }
        _CP.ping({ ffInstallStatus : status });
        return;
    }
} catch(e) {
    _CP.bug("Conviva_FF_InstallTrigger_callback", e); throw e;
}
};
Conviva.installCancelClicked = function () {
try {
    _CP.ping({ eulaAgree : "false" });
    _CP.hideInstaller ();
} catch(e) {
    _CP.bug("installCancelClicked", e); throw e;
}
};
_CP.hideInstaller = function () {
    var grey_box = document.getElementById('conviva_grey_box');
    grey_box.style.visibility = 'hidden'
    _CP.installDiv.style.visibility = 'hidden';
    _CP.installDiv.innerHTML = "";
    if(_CP.browser == "FF" && ! _CP.useGecko19) {
        if(_CP.getCookieParam("convivaInstallTurnOnObjects")) {
            _CP.modifySeeThroughObjects("visible");
        }
    }
    if(0) {
        if (typeof window.removeEventListener != 'undefined') { 
            window.removeEventListener('resize', _CP.positionInstallWindows , false);
        } else {
            window.detachEvent('onresize', _CP.positionInstallWindows );
        }
    }
};
_CP.executeThrow = function executeThrow (cmd, args) {
    if(! _CP.plugin ||
       ! cmd || 
       typeof(cmd) != "string" ||
       typeof(args) != "string") {
        Conviva.error("executeProxy: invalid arguments");
    }
    var res = _CP.plugin.execute(cmd, args);
    if(res.match(/^![0-9]+$/)) {
        var code = parseInt(res.substr(1));
        if(code == 0) {
            return "";
        } else {
            throw new Conviva.Exception(code,
                                        Conviva.errorMessage(code));
        }
    } else {
        return res;
    }
};
_CP.overrideStreamingPort = 0;
_CP.getStreamingPort = function () {
    if(_CP.overrideStreamingPort != 0) {
        return _CP.overrideStreamingPort;
    }
    try {
        return parseInt(_CP.executeThrow("getStreamingPort", ""));
    } catch(e) {
        _CP.bug("getStreamingPort", e);
        return 0;
    }
};
Conviva.errorMessage = function (code) {
    var msg = "";
    switch(parseInt(code)) {
    case 1000: 
        msg = _CP.i18n(_CP.ERR_CANNOT_FIND_CONFIG);
        break;
    case 1001: 
        msg = _CP.i18n(_CP.ERR_CANNOT_FIND_DLL);
        break;
    case 1002: 
        msg = _CP.i18n(_CP.ERR_INVALID_DLL);
        break;
    case 1003: 
        msg = _CP.i18n(_CP.ERR_MULTIPLE_INSTANCES_NOT_SUPPORTED);
        break;
    case 1004: 
        msg = _CP.i18n(_CP.ERR_CANNOT_INITIALIZE_PROXY);
        break;
    case 1005: 
        msg = _CP.i18n(_CP.ERR_BAD_CONFIG_PARAM);
        break;
    case 1006: 
        msg = _CP.i18n(_CP.ERR_TIMEOUT_PROXY_START);
        break;
    case 1007: 
        msg = _CP.i18n(_CP.ERR_CONVIVA_NOT_ENABLED);
        break;
    case 1008: 
        msg = _CP.i18n(_CP.ERR_LIVEPASS_VERSION_REVOKED);
        break;
    case 1009: 
        msg = _CP.i18n(_CP.ERR_LIVEPASS_VERSION_OLD);
        break;
    case 1010: 
        msg = _CP.i18n(_CP.ERR_LIVEPASS_NOT_INSTALLED);
        break;
    case 1011: 
        msg = _CP.i18n(_CP.ERR_LIVEPASS_NOT_ACCESSIBLE);
        break;
    case 1021: 
        msg = _CP.i18n(_CP.ERR_GEOBLOCK);
        break;
    case 1050: 
        msg = _CP.i18n(_CP.ERR_DOWNLOAD_UPDATE);
        break;
    case 1051: 
        msg = _CP.i18n(_CP.ERR_UPDATE_DLL_SAVE);
        break;
    case 1052: 
        msg = _CP.i18n(_CP.ERR_INVALID_UPDATE_DLL);
        break;
    case 1053: 
        msg = _CP.i18n(_CP.ERR_CANNOT_VERIFY_UPDATE_DLL);
        break;
    case 1054: 
        msg = _CP.i18n(_CP.ERR_CANNOT_RENAME_UPDATE_DLL);
        break;
    case 1055: 
        msg = _CP.i18n(_CP.ERR_UPDATE_DLL_WRONG_VERSION);
        break;
    case 1100: 
        msg = _CP.i18n(_CP.ERR_CHANNEL_FAILURE);
        break;
    case 1200: 
        msg = _CP.i18n(_CP.ERR_SESSION_FAILURE);
        break;
    case 1400: 
        msg = _CP.i18n(_CP.ERR_LOGIN_FAILURE);
        break;
    case 1401: 
        msg = _CP.i18n(_CP.ERR_EXCESSIVE_LOGINS);
        break;
    case 1450: 
        msg = _CP.i18n(_CP.ERR_AUTH_FAILURE);
        break;
    case 1460: 
        msg = _CP.i18n(_CP.ERR_ADMISSION_CTRL_FAILURE);
        break;
    case 1800: 
        msg = _CP.i18n(_CP.ERR_OS_NOT_SUPPORTED);
        break;
    case 1801: 
        msg = _CP.i18n(_CP.ERR_BROWSER_NOT_SUPPORTED);
        break;
    default:   
        msg = _CP.i18n(_CP.ERR_GENERIC, code);
        break;
    }
    return msg;
};
_CP.statusMessage = function (code) {
    switch(parseInt(code)) {
    case 2000: 
        return _CP.i18n(_CP.STATUS_MEASURING_BW);
    case 2001: 
        return _CP.i18n(_CP.STATUS_READY);
    case 2010: 
        return _CP.i18n(_CP.STATUS_CONNECTED);
    case 2011: 
        return _CP.i18n(_CP.STATUS_FETCHING_CHANNEL_CONF);
    case 2012: 
        return _CP.i18n(_CP.STATUS_FETCHING_STREAM_HEADER);
    case 2013: 
        return _CP.i18n(_CP.STATUS_CHECKING_NAT);
    case 2014: 
        return _CP.i18n(_CP.STATUS_WAITING_STREAM_DATA);
    case 2015: 
        return _CP.i18n(_CP.STATUS_STREAMING_DATA);
    case 2017: 
        return _CP.i18n(_CP.STATUS_FINISHING_SESSION);
    case 2020: 
        return _CP.i18n(_CP.STATUS_DOWNLOADING_UPDATES);
    case 2030: 
        return _CP.i18n(_CP.STATUS_STOPPING_PROXY);
    } 
    return _CP.i18n(_CP.STATUS_STATUS)+code;
};
_CP.showErrorNeedToConfigProxy = function() {
    if (_CP.ConfigProxyMessageShown) {
        return;
    }
    _CP.ConfigProxyMessageShown = true;
    if (_CP.platform == "Mac") {
        alert(_CP.i18n(_CP.ERR_HTTP_PROXY_NOT_CONFIGURED_MAC));
    } else {
        alert(_CP.i18n(_CP.ERR_HTTP_PROXY_NOT_CONFIGURED_WIN));
    }
};
_CP.getStreamFromEvent = function (eventStr) {
    var stream = Conviva.getStreamById(eventStr);
    if(stream) return stream;
    return null;
    if(eventStr.match(/^(.*)&uuid=\d+/)) {
        eventStr = RegExp.$1;
        stream = Conviva.getStreamById(eventStr);
        if(stream) return stream;
    }
    return stream;
};
_CP.mustUpdateHandled = false; 
_CP.eventListener = function eventListener (ename, eargs) {
    Conviva.log("Event("+ename+", "+eargs+")");
    if(ename == "StreamingPortChange") {
        for(var strid in _CP.streams) {
            var str = _CP.streams[strid];
            str._mainOnStreamingPortChange(eargs);
        }
    } else if(ename == "Error") {
        _CP.ping({ error : eargs });
        if(eargs.match(/^(\d+),(.*)$/)) {
            var code = parseInt(RegExp.$1);
            var streamUrl = RegExp.$2;
            var stream = _CP.getStreamFromEvent(streamUrl);
            if(stream)
                stream._mainOnError(code);
            else {
                Conviva.log("Cannot find stream for "+ename+","+eargs);
            }
        } else if(eargs.match(/^(\d+)$/)) {
            var code = parseInt(RegExp.$1);
            Conviva.log("Error does not have a stream identifier");
            for(var strid in _CP.streams) {
                var str = _CP.streams[strid];
                str._mainOnError(code);
            }
        } else {
            _CP.ping({ error : "invalid_error:"+eargs });
        }
    } else if(ename == "StatusChange") {
        var statusCode = 0;
        var streamUrl = null;
        if(eargs.match(/^(\d+)$/)) { 
            statusCode = parseInt(RegExp.$1);
        } else if(eargs.match(/^(\d+),(.*)$/)) {
            statusCode = parseInt(RegExp.$1);
            streamUrl  = RegExp.$2;
        } else {
            Conviva.log("Cannot parse StatusChange:"+eargs);
        }
        if (statusCode == 2001 || 
            statusCode == 2030) { 
            return;
        }
        if(statusCode == 2020) { 
            for(var strid in _CP.streams) {
                var str = _CP.streams[strid];
                str._mainOnStatusChange(statusCode);
            }
            return;
        }
        var stream = streamUrl ? _CP.getStreamFromEvent(streamUrl) : null;
        if(stream) {
            stream._mainOnStatusChange(statusCode);
        } else {
            Conviva.log("Cannot find streamUrl for StatusChange:"+eargs);
        }
    } else if(ename == "MustUpdate") {
        if(_CP.mustUpdateHandled) return;
        _CP.mustUpdateHandled = true;
        _CP.ping({ mustupdate : eargs });
        if(confirm(_CP.i18n(_CP.MSG_UPDATE_DLL_CONSENT_REQ))) {
            _CP.executeThrow("pluginInstallUpdate", eargs);
        } else {
            _CP.executeThrow("pluginStopProxy", "");
            _CP.ping({ error : 'updaterejected' });
        }
    } else if(ename == "DebugInfo") {
        _CP.ping({ debuginfo : eargs });
    }
}; 
_CP.pingQueue = [ ];
_CP.pingWaiting = false;
_CP.ping = function ping (params) {
    var url = _CP.options.pingUrl;
    if(! /\?/.test(url)) {
        url = url + "?";
    } else {
        url = url + "&";
    }
    var separator = ""; 
    for(var p in params) {
        url += separator + p + "=" + encodeURIComponent(params[p]);
        separator = "&";
    }
    url += separator + "uuid=" + _CP.uuid;
    url += "&osbr=" + _CP.osbr;
    url += "&propid=" + _CP.options.propertyId;
    url += "&rand=" + (Math.random () * 1000000000); 
    Conviva.log(url);
    if(/^file:/i.test(url)) return; 
    _CP.pingQueue.push(url);
    if(! _CP.pingWaiting) {
        _CP.pingDelivered (); 
    }
};
_CP.pingDelivered = function () {
    if(_CP.pingQueue.length > 0) {
        var url = _CP.pingQueue.shift();
        _CP.pingDiv.innerHTML = "<iframe id='conviva_ping_frame' src='"+url+"' frameborder='0' width='0' height='0'></iframe>";
        _CP.pingWaiting = true;
        setTimeout(_CP.pingDelivered, 1000); 
    } else {
        _CP.pingWaiting = false;
    }
};
_CP.decodeExc = function(e) {
    var trace = _CP.getStackTrace(e);
    if(trace) {
        trace = trace.join("\n");
    }
    var s1 = e.toString();
    if(s1.match(/^\[object/)) {
        return e.name+" "+e.description+"\nTrace:\n"+trace.toString();
    } else{
        return s1+"\nTrace:\n"+trace.toString();
    }
};
_CP.createCookie = function( name, value, expiresDays) {
    var str = name + '=' + escape(value) + '; path=/';
    if(expiresDays) {
        var expireDate = new Date();
        expireDate.setTime((new Date()).getTime() + 3600000*24*expiresDays);
        str = str + "; expires="+expireDate.toGMTString();
    }
    document.cookie = str;
};
_CP.getCookieParam = function ( name ) {
    var keyvals = document.cookie.split(';');
    for ( var i=0; i<keyvals.length; i++ ) {
        var parts = keyvals[i].split('=');
        if ( parts.length == 2 ) {
            if ( parts[0].replace(/^\s+|\s+$/g,"") == name ) {
                return parts[1].replace(/^\s+|\s+$/g,"");
            }
        }
    }
    return null;
};
_CP.deepCopy = function (what) {
    var to = typeof what;
    if(to == 'number' || to == 'string' || to == 'boolean' || to == 'undefined') {
        return what;
    }
    if(typeof what.splice === 'function') {
        return what.slice();
    }
    if(to == 'object') {
        var res = { } 
        for(var k in what) {
            res[o] = _CP.deepCopy(what[k]);
        }
        return res;
    }
};
_CP.playerProtocol = function (playerType) {
    if(playerType == Conviva.WINDOWS_MEDIA_PLAYER)
        return "mms:";
    else if(playerType == Conviva.SILVERLIGHT_PLAYER)
        return "mms:";
    else if (playerType == Conviva.FLASH_PLAYER)
        return "http:";
    else
        Conviva.error("Unexpected playerType");
};
_CP.getStackTrace = function(e) {   
    var callstack = [];   
    var isCallstackPopulated = false;   
    if (e.stack) { 
        var m ;
        while((m = /^\s*(.*)@(.+):(\d+)\s*$/gm.exec(e.stack))) {
            callstack.push(m[1]+" @ "+m[2]+":"+m[3]);
        }
        isCallstackPopulated = true;   
    } else if (window.opera && e.message) { 
        var lines = e.message.split("\n");   
        for (var i = 0, len = lines.length; i < len; i++) {   
            if (lines[i].match(/^\s*[A-Za-z0-9\-_\$]+\(/)) {   
                var entry = lines[i];   
                if (lines[i+1]) {   
                    entry += " at " + lines[i+1];   
                    i++;   
                }   
                callstack.push(entry);   
            }   
        }   
        callstack.shift();  
        isCallstackPopulated = true;   
    }   
    if (!isCallstackPopulated) { 
        var currentFunction = arguments.callee.caller;   
        while (currentFunction) {   
            var fn = currentFunction.toString();
            var m = /\s*function\s*(\S+)\s*\(/gm.exec(fn);
            if(m) {
                fname = "  *"+m[1];
            } else {
                fname = "  *"+fn.substring(0, 64)+".....";
            }
            callstack.push(fname);   
            currentFunction = currentFunction.caller;   
        }   
        callstack.shift();  
    }   
    return callstack;   
}
_CP.bug = function (msg, exc) {
    var trace = msg;
    if(exc) {
        trace += ": "+_CP.decodeExc(exc);
    }
    Conviva.log("BUG: "+trace);
    _CP.ping({ bug : msg + ": "+trace,
                          jsver : Conviva.version,
                          pluginver : Conviva.pluginVersion,
                          proxyver : Conviva.proxyVersion });
};
_CP.i18n = function () {
    var args = _CP.i18n.arguments;
    var msgId = args[0];
    var msg = _CP.i18nMessage(msgId);
    for(var i=1;i<args.length;i++) {
        msg = msg.replace("{"+i+"}", args[i].toString());
    }
    return msg;
};
_CP.ERR_LIVEPASS_NOT_LOADED = 1;
_CP.ERR_CANNOT_FIND_CONFIG = 2;
_CP.ERR_CANNOT_FIND_DLL = 3;
_CP.ERR_INVALID_DLL = 4;
_CP.ERR_MULTIPLE_INSTANCES_NOT_SUPPORTED = 5;
_CP.ERR_CANNOT_INITIALIZE_PROXY = 6;
_CP.ERR_BAD_CONFIG_PARAM = 7;
_CP.ERR_TIMEOUT_PROXY_START = 8;
_CP.ERR_CONVIVA_NOT_ENABLED = 9;
_CP.ERR_DOWNLOAD_UPDATE = 10;
_CP.ERR_LIVEPASS_VERSION_REVOKED = 11;
_CP.ERR_LIVEPASS_VERSION_OLD = 12;
_CP.ERR_LIVEPASS_NOT_INSTALLED = 13;
_CP.ERR_LIVEPASS_NOT_ACCESSIBLE = 14;
_CP.ERR_UPDATE_DLL_SAVE = 15;
_CP.ERR_INVALID_UPDATE_DLL = 16;
_CP.ERR_CANNOT_VERIFY_UPDATE_DLL = 17;
_CP.ERR_CANNOT_RENAME_UPDATE_DLL = 18;
_CP.ERR_UPDATE_DLL_WRONG_VERSION = 19;
_CP.ERR_CHANNEL_FAILURE = 20;
_CP.ERR_SESSION_FAILURE = 21;
_CP.ERR_LOGIN_FAILURE = 22;
_CP.ERR_EXCESSIVE_LOGINS = 23;
_CP.ERR_AUTH_FAILURE = 24;
_CP.ERR_ADMISSION_CTRL_FAILURE = 25;
_CP.ERR_GENERIC = 26;
_CP.ERR_OS_NOT_SUPPORTED = 27;
_CP.ERR_BROWSER_NOT_SUPPORTED = 28;
_CP.ERR_RUN_AS_ADMINISTRATOR = 29;
_CP.ERR_FIREFOX_PLUGIN_DISABLED = 30;
_CP.ERR_FIREFOX_WMP_MISSING = 31;
_CP.ERR_HTTP_PROXY_NOT_CONFIGURED_MAC = 32;
_CP.ERR_HTTP_PROXY_NOT_CONFIGURED_WIN = 33;
_CP.ERR_GEOBLOCK = 34;
_CP.STATUS_MEASURING_BW = 40;
_CP.STATUS_READY = 41;
_CP.STATUS_CONNECTED = 42;
_CP.STATUS_FETCHING_CHANNEL_CONF = 43;
_CP.STATUS_FETCHING_STREAM_HEADER = 44;
_CP.STATUS_CHECKING_NAT = 45;
_CP.STATUS_WAITING_STREAM_DATA = 46;
_CP.STATUS_STREAMING_DATA = 47;
_CP.STATUS_FINISHING_SESSION = 48;
_CP.STATUS_DOWNLOADING_UPDATES = 49;
_CP.STATUS_STOPPING_PROXY = 50;
_CP.STATUS_STATUS = 51;
_CP.MSG_UPDATE_CONSENT_REQ = 80;
_CP.MSG_UPDATE_DLL_CONSENT_REQ = 81;
_CP.en_us_messages = new Array ();
_CP.en_us_messages[_CP.ERR_LIVEPASS_NOT_LOADED] = "Conviva LivePass not loaded ({1})";
_CP.en_us_messages[_CP.ERR_CANNOT_FIND_CONFIG] = "Cannot find Conviva LivePass configuration information";
_CP.en_us_messages[_CP.ERR_CANNOT_FIND_DLL] = "Cannot find DLL, or its dependencies";
_CP.en_us_messages[_CP.ERR_INVALID_DLL] = "Invalid DLL";
_CP.en_us_messages[_CP.ERR_MULTIPLE_INSTANCES_NOT_SUPPORTED] = "Loading multiple instances of the Conviva LivePass in the same browser process is not yet supported";
_CP.en_us_messages[_CP.ERR_CANNOT_INITIALIZE_PROXY] = "Cannot initialize the proxy";
_CP.en_us_messages[_CP.ERR_BAD_CONFIG_PARAM] = "Bad configuration parameters";
_CP.en_us_messages[_CP.ERR_TIMEOUT_PROXY_START] = "Timeout starting the proxy";
_CP.en_us_messages[_CP.ERR_CONVIVA_NOT_ENABLED] = "Conviva LivePass is not enabled to work on this site";
_CP.en_us_messages[_CP.ERR_DOWNLOAD_UPDATE] = "Error downloading Conviva LivePass update";
_CP.en_us_messages[_CP.ERR_LIVEPASS_VERSION_REVOKED] = "Your version of Conviva LivePass has been revoked";
_CP.en_us_messages[_CP.ERR_LIVEPASS_VERSION_OLD] = "Your version of Conviva LivePass is too old";
_CP.en_us_messages[_CP.ERR_LIVEPASS_NOT_INSTALLED] = "Conviva LivePass is not installed";
_CP.en_us_messages[_CP.ERR_LIVEPASS_NOT_ACCESSIBLE] = "Error accessing the Conviva LivePass";
_CP.en_us_messages[_CP.ERR_UPDATE_DLL_SAVE] = "Error saving the update DLL";
_CP.en_us_messages[_CP.ERR_INVALID_UPDATE_DLL] = "Invalid update DLL";
_CP.en_us_messages[_CP.ERR_CANNOT_VERIFY_UPDATE_DLL] = "Cannot verify update DLL";
_CP.en_us_messages[_CP.ERR_CANNOT_RENAME_UPDATE_DLL] = "Cannot rename update DLL";
_CP.en_us_messages[_CP.ERR_UPDATE_DLL_WRONG_VERSION] = "Update DLL has wrong version";
_CP.en_us_messages[_CP.ERR_CHANNEL_FAILURE] = "Channel failure";
_CP.en_us_messages[_CP.ERR_SESSION_FAILURE] = "Session failure";
_CP.en_us_messages[_CP.ERR_LOGIN_FAILURE] = "Login failure";
_CP.en_us_messages[_CP.ERR_EXCESSIVE_LOGINS] = "Excessive logins";
_CP.en_us_messages[_CP.ERR_AUTH_FAILURE] = "Authorization Failure";
_CP.en_us_messages[_CP.ERR_ADMISSION_CTRL_FAILURE] = "Admission Control Failure";
_CP.en_us_messages[_CP.ERR_OS_NOT_SUPPORTED] = "This version of the Conviva LivePass is not supported on your operating system.\nSupported systems are: Windows XP and Vista, Mac OS X 10.5 on Intel platform.";
_CP.en_us_messages[_CP.ERR_BROWSER_NOT_SUPPORTED] = "This version of the Conviva LivePass is not supported on your browser.\nSupported browsers include: Internet Explorer 6 and 7, Firefox 2 and 3, and Safari on Mac OS X 10.5.";
_CP.en_us_messages[_CP.ERR_FIREFOX_PLUGIN_DISABLED] = "There is an error installing the Conviva LivePass. Check in the AddOns menu if the Conviva extension is disabled, or try to restart Firefox"; 
_CP.en_us_messages[_CP.ERR_GENERIC] = "Error ({1})";
_CP.en_us_messages[_CP.STATUS_MEASURING_BW] = "Measuring bandwidth";
_CP.en_us_messages[_CP.STATUS_READY] = "Ready";
_CP.en_us_messages[_CP.STATUS_CONNECTED] = "Connected";
_CP.en_us_messages[_CP.STATUS_FETCHING_CHANNEL_CONF] = "Fetching channel configuration";
_CP.en_us_messages[_CP.STATUS_FETCHING_STREAM_HEADER] = "Fetching stream header";
_CP.en_us_messages[_CP.STATUS_CHECKING_NAT] = "Checking NAT";
_CP.en_us_messages[_CP.STATUS_WAITING_STREAM_DATA] = "Waiting for stream data";
_CP.en_us_messages[_CP.STATUS_STREAMING_DATA] = "Streaming data";
_CP.en_us_messages[_CP.STATUS_FINISHING_SESSION] = "Finishing session";
_CP.en_us_messages[_CP.STATUS_DOWNLOADING_UPDATES] = "Downloading the latest version of Conviva LivePass";
_CP.en_us_messages[_CP.STATUS_STOPPING_PROXY] = "Stopping proxy";
_CP.en_us_messages[_CP.STATUS_STATUS] = "Status ";
_CP.en_us_messages[_CP.MSG_UPDATE_CONSENT_REQ] = "Do you want to install an up-to-date version of Conviva LivePass?";
_CP.en_us_messages[_CP.MSG_UPDATE_DLL_CONSENT_REQ] = "This content requires an update for your existing Conviva LivePass. The update has been downloaded and is ready to be enabled.\n\nPlease press OK to enable the update.";
_CP.en_us_messages[_CP.ERR_RUN_AS_ADMINISTRATOR] = "Unfinished install: please close Firefox, right click on your Firefox launch icon and select \"Run as administrator\"";
_CP.en_us_messages[_CP.ERR_FIREFOX_WMP_MISSING] =  "In order to view this content you must install the Windows Media Player plugin for Firefox\nPlease visit http://www.conviva.com/wmp for details.";
_CP.en_us_messages[_CP.ERR_HTTP_PROXY_NOT_CONFIGURED_MAC] = "Your HTTP Proxy is not configured properly, you may have issues using Conviva LivePass. Please add 127.0.0.1 to the Host bypass list";
_CP.en_us_messages[_CP.ERR_HTTP_PROXY_NOT_CONFIGURED_WIN] = "Your HTTP Proxy is not configured properly, you may have issues using Conviva LivePass. Please add 127.0.0.1 to the \"Do not use proxy for addresses beginning with\" field in the Internet Explorer or Control Panel Internet Options proxy configuration";
_CP.en_us_messages[_CP.ERR_GEOBLOCK] = "This channel is not enabled for your geographic location.";
_CP.en_us_Translator = function (msgId) {
    return _CP.en_us_messages[msgId];
};
_CP.translators = {
	'en-US' : _CP.en_us_Translator
};
_CP.i18nMessage = function (msgId) {
    var msg = _CP.translators[_CP.options.language](msgId);
    if(! msg) {
        Conviva.log("Cannot find translation of MSGID "+
                           msgId+" in language "+_CP.options.language);
        msg = _CP.translators['en-US'](msgId);
        if(! msg) {
            Conviva.error("Missing english translation for MSGID "+msgId);
        }
    }
    return msg;
};
_CP.checkTranslationComplete = function (lang) {
    var translator = _CP.translators[lang];
    for(var msgId in _CP.en_us_messages) {
        if(! translator[msgId]) {
            Conviva.log("Missing translation for "+msgId+" ("+_CP.en_us_messages[msgId]+")");
        }
    }
};
if(! window._CP) {
    alert("ConvivaLogger must be loaded after ConvivaLivePass.js");
}
window.ConvivaLogger = { };
ConvivaLogger.loggingWindow  = null;
ConvivaLogger.waitingLoggingWindow = null;
ConvivaLogger.logBuffer = "";
ConvivaLogger.startLogging = function () {
    if(ConvivaLogger.loggingWindow ||
       ConvivaLogger.waitingLoggingWindow) return;
    ConvivaLogger.waitingLoggingWindow = true;
    ConvivaLogger.createLoggingWindow ();
};
ConvivaLogger.createLoggingWindow = function () {
    if(false) {
        try {
            ConvivaLogger.loggingWindow =
                window.open('logging', 'Conviva Logger',
                            'width=400,height=400,scrollbars=1');
        } catch(e) {
        }
        if(! ConvivaLogger.loggingWindow) {
            setTimeout(ConvivaLogger.createLoggingWindow, 2000);
            return; 
        }
        ConvivaLogger.loggingWindow.document.write('<input type=button value="Clear log" '+
                                '  onclick="ConvivaLogger.logClear()"><br/>' +
                                '<textarea type="textarea" id="convivaLoggingArea" rows=40 cols=100></textarea>');
    } else {
        ConvivaLogger.loggingWindow = window;
        ConvivaLogger.waitingLoggingWindow = false;
        var le = document.createElement("p");
        document.body.appendChild(le);
        le.innerHTML = ('Log messages (last at the top) <input type=button value="Clear log" '+
                        '  onclick="ConvivaLogger.logClear()"><br/>' +
                        '<textarea type="textarea" id="convivaLoggingArea" rows=40 cols=100></textarea>');
    }
};
ConvivaLogger.logClear = function () {
    try {
        ConvivaLogger.loggingWindow.document.getElementById('convivaLoggingArea').value = "";
    } catch(e) { }
    ConvivaLogger.logBuffer = "";
};
ConvivaLogger.int2string = function (i, width) {
    var is = i.toString(10);
    while(is.length < width) {
        is = "0" + is;
    }
    return is;
};
ConvivaLogger.timeStamp = function () {
    var now = new Date();
    return (ConvivaLogger.int2string(1 + now.getMonth(), 2) + "/" +
            ConvivaLogger.int2string(now.getDate(), 2) + " " +
            ConvivaLogger.int2string(now.getHours(), 2) + ":" + 
            ConvivaLogger.int2string(now.getMinutes(), 2) + ":" +  
            ConvivaLogger.int2string(now.getSeconds(), 2) + "." + 
            ConvivaLogger.int2string(now.getMilliseconds(), 3));
};
ConvivaLogger.log = function (msg) {
    ConvivaLogger.startLogging();
    var logEntry = ConvivaLogger.timeStamp() + "\n  " + msg + "\n";
    var area = null;
    ConvivaLogger.logBuffer = logEntry + ConvivaLogger.logBuffer;
    if(ConvivaLogger.logBuffer.length > 10000) {
        ConvivaLogger.logBuffer = ConvivaLogger.logBuffer.substr(0, 10000);
    }
    if(ConvivaLogger.loggingWindow) {
        try {
            area = ConvivaLogger.loggingWindow.document.getElementById('convivaLoggingArea');
            if(ConvivaLogger.logBuffer) {
                area.value = ConvivaLogger.logBuffer + area.value;
                ConvivaLogger.logBuffer = "";
            }
        } catch (e) {
        }
    }
}
if(! window.Conviva) { 
    alert("ConvivaPlayerLib.js must be loaded after ConvivaLivePass.js");
}
_CP.playerInheritMethods = function (obj, 
                                                playerType) {
try {
    obj._constructor = function _constructor (playerHostId, options) {
        var name = "";
        if(playerType == Conviva.WINDOWS_MEDIA_PLAYER)
            name = "wmp";
        else if(playerType == Conviva.FLASH_PLAYER)
            name = "flash";
        else if(playerType == Conviva.SILVERLIGHT_PLAYER)
            name = "silverlight";
        else
            alert("Bug: unknown player type "+playerType);
        if(! playerHostId)
            Conviva.error(name+":playerHostId is null");
        var playerHostElement = document.getElementById(playerHostId);
        if(! playerHostElement)
            Conviva.error(name+":playerHostElement is null");
        _CP.checkType(playerHostElement,
                                 "object", name+":playerHostElement");
        this.playerType = playerType;
        this._playerHostElement = playerHostElement;
        if(! this._options)
            alert("Bug: PlayerLib:__options not initialized");
        this.setOptions(options);
        options = this._options;
        this._playerObjId = _CP.newUniqueId("conviva_"+name);
        _CP.players[this._playerObjId] = this;
        this._streamPlaying = null;
        this._isReady = false;
        this._playState = -1; 
        this._urlPlaying = this._setupPlayerStreamConnection(options.stream);
        this._setInnerHTML (this._urlPlaying);
    };
    obj.setOptions = function (options) {
      try {
        for(var o in options) {
            if(o == 'objectParams') {
                for(var p in options.objectParams) {
                    this._options.objectParams[p] = options.objectParams[p];
                }
            } else {
                if(o == 'onCreate' || o == 'onPlayStateChange') {
                    _CP.checkType(options[o], "function",
                                             "Stream.setOptions::"+o);
                }
                this._options[o] = options[o];
            }
        }
      } catch(e) {
        _CP.bug("Conviva.player.setOptions", e); throw e;
      }
    };
    obj._getOptions = function () {
        return this._options;
    }
    obj.isScriptable = function () {
        return true;
    };
    obj.isReady = function () {
        return this._isReady;
    };
    obj.getEmbeddedPlayer = function () {
        return document.getElementById(this._playerObjId);
    };
    obj._setupPlayerStreamConnection = function _setupPlayerStreamConnection (stream) {
      try {
        if(! stream) return null;
        var url = stream.getUrl(this.playerType);
        if(this._urlPlaying == url)
            return null;
        if(this._streamPlaying) {
            this._streamPlaying.disconnectPlayer();
        }
        this._streamPlaying = stream;
        var player = this;
        stream.connectPlayer(this._playerObjId,
                             function () { player.play(stream); });
        return url;
      } catch(e) {
        _CP.bug("Conviva.player._setupPlayerStreamConnection", e); throw e;
      }
    }
    obj._onPlayStateChange = function (newstate) {
      try {
        this._playState = newstate;
        if(this._options.onPlayStateChange)
            this._options.onPlayStateChange(newstate);
        if(this._streamPlaying) {
            this._streamPlaying.playStateChanged(this._playState);
        }
      } catch(e) {
        _CP.bug("Conviva.player._onPlayStateChange", e); throw e;
      }
    };
    obj.play = function (stream) {
      try {
        if(! this.isReady())
            Conviva.error("play called before the player is ready");
        var url = this._setupPlayerStreamConnection(stream);
        if(! url) return;
        this._urlPlaying = url;
        obj._actualPlay(url);
      } catch(e) {
        _CP.bug("Conviva.player.play", e); throw e;
      }
    };
    obj.stop = function stop () {
      try {
        if(this._streamPlaying) {
            Conviva.log("Player "+this._playerObjId+" stopping")
            this._actualStop ();
            if(this._streamPlaying) this._streamPlaying.disconnectPlayer();
            this._urlPlaying = null;
            this._streamPlaying = null;
        }
      } catch(e) {
        _CP.bug("Conviva.player.stop", e); throw e;
      }
    };
    obj.cleanup = function () {
      try {
        try { obj.stop (); } catch(e) { };
        this._playerHostElement.innerHTML = "";
        if(this._streamPlaying) {
            this._streamPlaying.disconnectPlayer();
        }
        if(this.playerType == Conviva.WINDOWS_MEDIA_PLAYER) {
            if(this._freezer)
                try { this._freezer.stop(); } catch(e) { };
            this._freezer = null; 
        }
        this._urlPlaying = null;
        _CP.players[obj._playerObjId] = null;
      } catch(e) {
        _CP.bug("Conviva.player.cleanup", e); throw e;
      }
    };
} catch(e) {
    _CP.bug("Conviva.playerInheritMethods", e); throw e;
}
};
Conviva.MMS_PLAYER = "MMS";
Conviva.createPlayer = function (playerType, playerDiv, options) {
try {
    if(playerType == Conviva.MMS_PLAYER) {
        if(/Macintosh/.test(navigator.userAgent)) {
            playerType = Conviva.SILVERLIGHT_PLAYER;
        } else {
            playerType = Conviva.WINDOWS_MEDIA_PLAYER;
        }
    }
    if(playerType == Conviva.WINDOWS_MEDIA_PLAYER) {
        return new Conviva.WMPlayer(playerDiv, options);
    }
    if(playerType == Conviva.FLASH_PLAYER) {
        return new Conviva.FlashPlayer(playerDiv, options);
    }
    if(playerType == Conviva.SILVERLIGHT_PLAYER) {
        return new Conviva.SilverlightPlayer(playerDiv, options);
    }
    Conviva.error("Unexpected playerType in Conviva.createPlayer");
} catch(e) {
    _CP.bug("Conviva.createPlayer", e); throw e;
}
};
if(! window.Conviva) { 
    alert("Must load ConvivaLivePass.js first");
}
if(! _CP.WMPdetected && _CP.browser == 'FF') {
    _CP.haveWMPff = false;     
    _CP.haveWMPplugin = false; 
    for(var i=0 ; i<navigator.mimeTypes.length ; i++) {
        if(navigator.mimeTypes[i].type == 'application/x-ms-wmp') {
            _CP.haveWMPplugin = true;
            _CP.haveWMPff = true;
        }
        if(navigator.mimeTypes[i].type == 'application/x-mplayer2') {
            _CP.haveWMPff = true;
        }
    }
    _CP.WMPdetected = true;
};
Conviva.WMPlayer = function (playerHostId, options) {
    _CP.playerInheritMethods(this,
                                        Conviva.WINDOWS_MEDIA_PLAYER);
    this._options = {
        objectParams : { autostart : "true",
                         UIMode : "mini",
                         windowlessVideo : (_CP.winVersion == "6.0" && _CP.browser == "IE" ? "true" : "false")
        }
    };
    this.isScriptable = function () {
        return _CP.browser == 'IE' || _CP.haveWMPplugin;
    };
    this._setInnerHTML = function (url) {
        var options = this._options;
        var header = '';
        if(_CP.browser == "IE") {
            header = '       classid="CLSID:6BF52A52-394A-11D3-B153-00C04F79FAA6"' +
                     '       type="application/x-oleobject" ';
        } else {
            if(! _CP.haveWMPff) {
                alert(_CP.i18n(_CP.ERR_FIREFOX_WMP_MISSING));
            }
            header = 'type="application/x-mplayer2" ';
            if ( _CP.browser == "FF" && _CP.haveWMPplugin) {
                header = 'type="application/x-ms-wmp"';
            }
        }
        if(! options || ! options.width || ! options.height) {
            Conviva.error("Must pass width and height to WMPlayer");
        }
        if(_CP.browser == 'FF' && url) {
            header = header + " data='"+url+"'";
        }
        var theHTML = '<object id="' + this._playerObjId + '" '+header;
        theHTML += '       width="' + options.width + '"';
        theHTML += '       height="' + options.height + '"';
        if(options && 'standby' in options) {
            theHTML += '       standby="' + options.standby + '"';
        }
        if(options && options.objectHTMLAttributes) {
            theHTML += ' '+options.objectHTMLAttributes+' ';
        }
        theHTML += ">";
        for(var p in options.objectParams) {
            theHTML += '    <param name="'+p+'" value="'+options.objectParams[p]+'" />';
        }
        if(_CP.browser == 'IE' && url) {
            theHTML += '    <param name="URL" value="' + url + '" />';
        }
        theHTML += "</object>";
        theHTML += "<script type='text/javascript' for='"+this._playerObjId+"' event='PlayStateChange(newState)'>";
        theHTML += "_CP.onWMPlayStateChange('"+this._playerObjId+"', newState)</script>";
        this._playerHostElement.innerHTML = theHTML;
        var playerId = this._playerObjId; 
        var toWait = 10;
        if(! this.isScriptable()) toWait = 100; 
        setTimeout(function () { _CP.checkIfWMPlayerReady(playerId); }, toWait);
    };
    this._checkIfPlayStateChanged = function () {
        var playerObj = this.getEmbeddedPlayer();
        var newState = playerObj.playState;
        if (newState === undefined) return;
        if(newState != this._playState) {
            this._onPlayStateChange(newState);
        }
    };
    this._actualPlay = function (url) {
        if(_CP.browser == 'FF') {
            this._setInnerHTML (url); 
        } else {
            this.getEmbeddedPlayer().url = url;
        }
        if(this._freezer)
            this._freezer.start ();
    };
    this._actualStop = function () {
        try {
            var controls = this.getEmbeddedPlayer().controls;
            if(! (controls === undefined)) controls.stop();
        } catch(e) {
        };
        if(this._freezer)
            this._freezer.stop ();
        if(_CP.browser == 'FF') {
        }
    }
    this._constructor (playerHostId, options);
};
_CP.onWMPlayStateChange = function (playerId, newState) {
    Conviva.log("WMPlayer("+playerId+" changed state to "+newState+")");
    var player = _CP.players[playerId];
    player._checkIfPlayStateChanged();
};
window.OnDSPlayStateChangeEvt = function (newState) {
try {
    Conviva.log("Called OnDSPlayStateChangeEvt("+newState+")");
    for(var pid in _CP.players) {
        var p = _CP.players[pid];
        if(p && p.playerType == Conviva.WINDOWS_MEDIA_PLAYER) {
            p._checkIfPlayStateChanged();
        }
    }
} catch(e) {
    _CP.bug("onDSPlayStateChangeEvt", e);
}
};
_CP.checkIfWMPlayerReady = function (playerId) {
try {
    var player = _CP.players[playerId];
    var ready = false;
    try {
        if(! player)
            ready = false;
        else if(! player.isScriptable())
            ready = true;
        else {
            ready = player.getEmbeddedPlayer().versionInfo;
        }
    } catch(e) {
        ready = false;
    }
    if(ready) {
        Conviva.log("Player "+playerId+" is ready");
        player._isReady = true;
        if(player._options.onCreate) {
            player._options.onCreate(player);
        }
        if(player._options.freezeDetection) {
            player._freezer = new _CP.freezeDetector (player);
            player._freezer.start ();
        }
    } else {
        setTimeout(function () { _CP.checkIfWMPlayerReady(playerId); }, 100);
    }
} catch(e) {
    _CP.bug("checkIfWMPlayerReady", e);
}
};
_CP.freezeDetector = function (wmp) {
    this.wmp = wmp;
    this.sampleInterval = 2000; 
    this.stopFlag = false; 
    this.timerHandler = function (obj) {
        if(obj.stopFlag) return; 
        try {
            var wmp = obj.wmp.getEmbeddedPlayer();
            if(!wmp) return;
            if(wmp.playState == 3) { 
                if(! obj.processSample(wmp.network.encodedFrameRate,
                                       wmp.network.frameRate,
                                       wmp.network.bandWidth,
                                       wmp.network.receivedPackets)) {
                    obj.reset ();
                    var url = obj.wmp._streamPlaying.getUrl(obj.wmp.playerType);
                    obj.wmp._actualPlay(url);
                    return;
                }
            }
        } catch(e) {
            Conviva.log("WMP.freezeDetect: error "+_CP.decodeExc(e));
        }
        setTimeout(function () { obj.timerHandler(obj); },
                   this.sampleInterval);
    };
    this.countSamples = 0;  
    this.countAFR0 = 0;     
    this.lastAfr   = 0;     
    this.lastBw    = 0;     
    this.lastRp    = 0;     
    this.countDecreaseAfr    = 0; 
    this.countNonIncreaseAfr = 0; 
    this.reset = function () {
        this.countSamples = 0;
        this.countAFR0 = 0;
        this.lastAfr = 0;
        this.lastBw = 0;
        this.lastRp = 0;
        this.countDecreaseAfr    = 0;
        this.countNonIncreaseAfr = 0;
        this.stopFlag = false;
    };
    this.processSample = function (efr, 
                                   afr, 
                                   bw,  
                                   rp) { 
        Conviva.log("WMP.freezeDetect(efr="+efr+",afr="+afr+
                    ",bw="+bw+",rp="+rp);
        if(efr == 0) { 
            this.reset();
            return true;
        }
        this.countSamples ++;
        if(this.countSamples < 5) { 
            return true;
        }
        if(afr == 0) { 
            if(++ this.countAFR0 >= 2) {
                Conviva.log("WMP.freezeDetect(restart due to AFR=0");
                return false; 
            }
        } else {
            this.countAFR0 = 0;
        }
        if(afr > this.lastAfr || bw != this.lastBw || rp <= this.lastRp) {
            this.lastAfr = afr; this.lastBw = bw; this.lastRp = rp;
            this.countNonIncreaseAfr = 0; this.countDecreaseAfr = 0;
            return true;
        }
        if(++ this.countNonIncreaseAfr >= 5) {
            if(afr < 10 * efr) {
                Conviva.log("WMP.freezeDetect(restart due to AFR < 10% of EFR");
                return false;
            }
        }
        if(afr < this.lastAfr) {
            if(++ this.countDecreaseAfr >= 5) {
                Conviva.log("WMP.freezeDetect(restart due to decreasing AFR)");
                return false;
            }
        } else {
            this.countDecreaseAfr = 0;
        }
        this.lastAfr = afr; this.lastBw = bw; this.lastRp = rp;
        return true;
    };
    this.start = function () {
        this.reset ();
        this.timerHandler (this);
    }
    this.stop = function () {
        this.stopFlag = true;
    }
};  
_CP.testWindowsMediaPlayer = function () {
    Conviva.log("haveWMPlugin = "+_CP.haveWMPplugin);
    var newMimeTypeFound = false;
    try {
        for(var i=0 ; i<navigator.mimeTypes.length ; i++) {
            if(navigator.mimeTypes[i].type == 'application/x-ms-wmp') {
                var mime = navigator.mimeTypes[i];
                Conviva.log("mimeTypes: type="+mime.type+" description="+mime.description);
                newMimeTypeFound = true;
            }
        }
        if(! newMimeTypeFound) {
            Conviva.log("mimeTypes: not found application/x-ms-wmp");
        }
    } catch(e) {
        Conviva.log("error reading navigator.mimeTypes "+_CP.decodeExc(e));
    }
    try {
        Conviva.log("plugin getMediaPlayerVersion="+_CP.plugin.execute("getMediaPlayerVersion", ""));
    } catch(e) {
        Conviva.log("Cannot call getMediaPlayerVersion "+_CP.decodeExc(e));
    }
    Conviva.log("Now try to create the player");
    var player;
    var divElement = document.createElement("div");
    divElement.innerHTML = "<div id='test_wmp_div'></div>";
    document.body.appendChild(divElement);
    try {
        player = new Conviva.WMPlayer('test_wmp_div',
                                      { width : 100, height : 100,
                                        onCreate : _CP.finishTestWMPlayer });
    } catch(e) {
        Conviva.log("Cannot create the player "+_CP.decodeExc(e));
    }
    if(! player) {
        Conviva.log("Cannot create the player (null)");
    }
};
_CP.finishTestWMPlayer = function (player) {
    var playerObj = player.getEmbeddedPlayer();
    try {
        Conviva.log("versionInfo="+playerObj.versionInfo);
    } catch(e) {
        Conviva.log("Cannot access versionInfo "+_CP.decodeExc(e));
    }
    try {
        Conviva.log("pluginVersionInfo (FF only)="+playerObj.pluginVersionInfo);
    } catch(e) {
        Conviva.log("Cannot access pluginVersionInfo "+_CP.decodeExc(e));
    }
    try {
        Conviva.log("playState="+playerObj.playState);
    } catch(e) {
        Conviva.log("Cannot access playState "+_CP.decodeExc(e));
    }
    try {
        Conviva.log("network.bufferingTime="+playerObj.network.bufferingTime);
    } catch(e) {
        Conviva.log("Cannot access network.bufferingTime "+_CP.decodeExc(e));
    }
    player.cleanup ();
}
if(! window.Conviva) { 
    alert("Must load ConvivaLivePass.js first");
}
if(! window.Silverlight) {
if (!window.Silverlight)
{
    window.Silverlight = { };
}
Silverlight._silverlightCount = 0;
Silverlight.fwlinkRoot='http://go2.microsoft.com/fwlink/?LinkID=';
Silverlight.onGetSilverlight = null;
Silverlight.onSilverlightInstalled = function () {window.location.reload(false);};
Silverlight.isInstalled = function(version)
{
    var isVersionSupported=false;
    var container = null;
    try 
    {
        var control = null;
        try
        {
            control = new ActiveXObject('AgControl.AgControl');
            if ( version == null )
            {
                isVersionSupported = true;
            }
            else if ( control.IsVersionSupported(version) )
            {
                isVersionSupported = true;
            }
            control = null;
        }
        catch (e)
        {
            var plugin = navigator.plugins["Silverlight Plug-In"] ;
            if ( plugin )
            {
                if ( version === null )
                {
                    isVersionSupported = true;
                }
                else
                {
                    var actualVer = plugin.description;
                    if ( actualVer === "1.0.30226.2")
                        actualVer = "2.0.30226.2";
                    var actualVerArray =actualVer.split(".");
                    while ( actualVerArray.length > 3)
                    {
                        actualVerArray.pop();
                    }
                    while ( actualVerArray.length < 4)
                    {
                        actualVerArray.push(0);
                    }
                    var reqVerArray = version.split(".");
                    while ( reqVerArray.length > 4)
                    {
                        reqVerArray.pop();
                    }
                    var requiredVersionPart ;
                    var actualVersionPart
                    var index = 0;
                    do
                    {
                        requiredVersionPart = parseInt(reqVerArray[index]);
                        actualVersionPart = parseInt(actualVerArray[index]);
                        index++;
                    }
                    while (index < reqVerArray.length && requiredVersionPart === actualVersionPart);
                    if ( requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart) )
                    {
                        isVersionSupported = true;
                    }
                }
            }
        }
    }
    catch (e) 
    {
        isVersionSupported = false;
    }
    if (container) 
    {
        document.body.removeChild(container);
    }
    return isVersionSupported;
}
Silverlight.WaitForInstallCompletion = function()
{
    if ( ! Silverlight.isBrowserRestartRequired && Silverlight.onSilverlightInstalled )
    {
        try
        {
            navigator.plugins.refresh();
        }
        catch(e)
        {
        }
        if ( Silverlight.isInstalled(null) )
        {
            Silverlight.onSilverlightInstalled();
        }
        else
        {
              setTimeout(Silverlight.WaitForInstallCompletion, 3000);
        }    
    }
}
Silverlight.__startup = function()
{
    Silverlight.isBrowserRestartRequired = Silverlight.isInstalled(null);
    if ( !Silverlight.isBrowserRestartRequired)
    {
        Silverlight.WaitForInstallCompletion();
    }
    if (window.removeEventListener) { 
       window.removeEventListener('load', Silverlight.__startup , false);
    }
    else { 
        window.detachEvent('onload', Silverlight.__startup );
    }
}
if (window.addEventListener) 
{
    window.addEventListener('load', Silverlight.__startup , false);
}
else 
{
    window.attachEvent('onload', Silverlight.__startup );
}
Silverlight.createObject = function(source, parentElement, id, properties, events, initParams, userContext)
{
    var slPluginHelper = new Object();
    var slProperties = properties;
    var slEvents = events;
    slPluginHelper.version = slProperties.version;
    slProperties.source = source;    
    slPluginHelper.alt = slProperties.alt;
    if ( initParams )
        slProperties.initParams = initParams;
    if ( slProperties.isWindowless && !slProperties.windowless)
        slProperties.windowless = slProperties.isWindowless;
    if ( slProperties.framerate && !slProperties.maxFramerate)
        slProperties.maxFramerate = slProperties.framerate;
    if ( id && !slProperties.id)
        slProperties.id = id;
    delete slProperties.ignoreBrowserVer;
    delete slProperties.inplaceInstallPrompt;
    delete slProperties.version;
    delete slProperties.isWindowless;
    delete slProperties.framerate;
    delete slProperties.data;
    delete slProperties.src;
    delete slProperties.alt;
    if (Silverlight.isInstalled(slPluginHelper.version))
    {
        for (var name in slEvents)
        {
            if ( slEvents[name])
            {
                if ( name == "onLoad" && typeof slEvents[name] == "function" && slEvents[name].length != 1 )
                {
                    var onLoadHandler = slEvents[name];
                    slEvents[name]=function (sender){ return onLoadHandler(document.getElementById(id), userContext, sender)};
                }
                var handlerName = Silverlight.__getHandlerName(slEvents[name]);
                if ( handlerName != null )
                {
                    slProperties[name] = handlerName;
                    slEvents[name] = null;
                }
                else
                {
                    throw "typeof events."+name+" must be 'function' or 'string'";
                }
            }
        }
        slPluginHTML = Silverlight.buildHTML(slProperties);
    }
    else 
    {
        slPluginHTML = Silverlight.buildPromptHTML(slPluginHelper);
    }
    if(parentElement)
    {
        parentElement.innerHTML = slPluginHTML;
    }
    else
    {
        return slPluginHTML;
    }
}
Silverlight.buildHTML = function( slProperties)
{
    var htmlBuilder = [];
    htmlBuilder.push('<object type=\"application/x-silverlight\" data="data:application/x-silverlight,"');
    if ( slProperties.id != null )
    {
        htmlBuilder.push(' id="' + slProperties.id + '"');
    }
    if ( slProperties.width != null )
    {
        htmlBuilder.push(' width="' + slProperties.width+ '"');
    }
    if ( slProperties.height != null )
    {
        htmlBuilder.push(' height="' + slProperties.height + '"');
    }
    htmlBuilder.push(' >');
    delete slProperties.id;
    delete slProperties.width;
    delete slProperties.height;
    for (var name in slProperties)
    {
        if (slProperties[name])
        {
            htmlBuilder.push('<param name="'+Silverlight.HtmlAttributeEncode(name)+'" value="'+Silverlight.HtmlAttributeEncode(slProperties[name])+'" />');
        }
    }
    htmlBuilder.push('<\/object>');
    return htmlBuilder.join('');
}
Silverlight.createObjectEx = function(params)
{
    var parameters = params;
    var html = Silverlight.createObject(parameters.source, parameters.parentElement, parameters.id, parameters.properties, parameters.events, parameters.initParams, parameters.context);
    if (parameters.parentElement == null)
    {
        return html;
    }
}
Silverlight.buildPromptHTML = function(slPluginHelper)
{
    var slPluginHTML = "";
    var urlRoot = Silverlight.fwlinkRoot;
    var shortVer = slPluginHelper.version ;
    if ( slPluginHelper.alt )
    {
        slPluginHTML = slPluginHelper.alt;
    }
    else
    {
        if (! shortVer )
        {
            shortVer="";
        }
        slPluginHTML = "<a href='javascript:Silverlight.getSilverlight(\"{1}\");' style='text-decoration: none;'><img src='{2}' alt='Get Microsoft Silverlight' style='border-style: none'/></a>";
        slPluginHTML = slPluginHTML.replace('{1}', shortVer );
        slPluginHTML = slPluginHTML.replace('{2}', urlRoot + '108181');
    }
    return slPluginHTML;
}
Silverlight.getSilverlight = function(version)
{
    if (Silverlight.onGetSilverlight )
    {
        Silverlight.onGetSilverlight();
    }
    var shortVer = "";
    var reqVerArray = String(version).split(".");
    if (reqVerArray.length > 1)
    {
        var majorNum = parseInt(reqVerArray[0] );
        if ( isNaN(majorNum) || majorNum < 2 )
        {
            shortVer = "1.0";
        }
        else
        {
            shortVer = reqVerArray[0]+'.'+reqVerArray[1];
        }
    }
    var verArg = "";
    if (shortVer.match(/^\d+\056\d+$/) )
    {
        verArg = "&v="+shortVer;
    }
    Silverlight.followFWLink("114576" + verArg);
}
Silverlight.followFWLink = function(linkid)
{
    top.location=Silverlight.fwlinkRoot+String(linkid);
}
Silverlight.HtmlAttributeEncode = function( strInput )
{
      var c;
      var retVal = '';
    if(strInput == null)
      {
          return null;
    }
      for(var cnt = 0; cnt < strInput.length; cnt++)
      {
            c = strInput.charCodeAt(cnt);
            if (( ( c > 96 ) && ( c < 123 ) ) ||
                  ( ( c > 64 ) && ( c < 91 ) ) ||
                  ( ( c > 43 ) && ( c < 58 ) && (c!=47)) ||
                  ( c == 95 ))
            {
                  retVal = retVal + String.fromCharCode(c);
            }
            else
            {
                  retVal = retVal + '&#' + c + ';';
            }
      }
      return retVal;
}
Silverlight.default_error_handler = function (sender, args)
{
    var iErrorCode;
    var errorType = args.ErrorType;
    iErrorCode = args.ErrorCode;
    var errMsg = "\nSilverlight error message     \n" ;
    errMsg += "ErrorCode: "+ iErrorCode + "\n";
    errMsg += "ErrorType: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";
    if (errorType == "ParserError")
    {
        errMsg += "XamlFile: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError")
    {
        if (args.lineNumber != 0)
        {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " +  args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }
    return errMsg;
}
Silverlight.__cleanup = function ()
{
    for (var i = Silverlight._silverlightCount - 1; i >= 0; i--) {
        window['__slEvent' + i] = null;
    }
    Silverlight._silverlightCount = 0;
    if (window.removeEventListener) { 
       window.removeEventListener('unload', Silverlight.__cleanup , false);
    }
    else { 
        window.detachEvent('onunload', Silverlight.__cleanup );
    }
}
Silverlight.__getHandlerName = function (handler)
{
    var handlerName = "";
    if ( typeof handler == "string")
    {
        handlerName = handler;
    }
    else if ( typeof handler == "function" )
    {
        if (Silverlight._silverlightCount == 0)
        {
            if (window.addEventListener) 
            {
                window.addEventListener('onunload', Silverlight.__cleanup , false);
            }
            else 
            {
                window.attachEvent('onunload', Silverlight.__cleanup );
            }
        }
        var count = Silverlight._silverlightCount++;
        handlerName = "__slEvent"+count;
        window[handlerName]=handler;
    }
    else
    {
        handlerName = null;
    }
    return handlerName;
}
} 
function createConvivaSilverlightPlugin(id, xaml, options) {
    var width = '496';
    if(options.width) width = options.width;
    var height = '272';
    if(options.height) height = options.height;
    return Silverlight.createObject(
        xaml,                           
        null,                           
        id,                             
        {                               
            width: width,               
            height: height,             
            inplaceInstallPrompt:false, 
            enableHtmlAccess:'true',
            background:'#D6D6D6',       
            isWindowless:'false',       
            framerate:'24',             
            BufferingTime:'0:0:05',     
            version:'2.0.30523'         
        },
        {
            onError:Conviva_SilverlightError,   
            onLoad:Conviva_SilverlightLoaded                 
        },
        null,                            
        id);                            
}
Conviva.SilverlightPlayer = function (playerHostId, options) {
try {
    _CP.playerInheritMethods(this,
                                        Conviva.SILVERLIGHT_PLAYER);
    this._options = {
        xaml : "ConvivaSilverlightPlayer.xaml"
    };
    this._setInnerHTML = function (url) {
        var options = this._options;
        if(! options || ! options.width || ! options.height) {
            Conviva.error("Must pass width and height to FlashPlayer");
        }
        var html = createConvivaSilverlightPlugin(this._playerObjId,
                                                  _CP.fixUrl(options.xaml), options);
        this._playerHostElement.innerHTML = html;
        if(_CP.browser == 'FF') {
            var playerId = this._playerObjId;
            setTimeout(function () { _CP.checkIfSilverlightPlayerReady(playerId); }, 100);
        }
    };
    this._actualPlay = function (url) {
        Conviva.log("Player "+this._playerObjId+" will play "+url);
        var obj = this.getEmbeddedPlayer();
        var vid = obj.content.findName("media");
        if(! vid) {
            Conviva.error("ConvivaSilverlightPlayer: cannot find media element");
        }
        vid.Source = url;
        vid.Play();
    };
    this._actualStop = function () {
        var obj = this.getEmbeddedPlayer();
        if(! obj) return;
        var vid = obj.content.findName("media");
        if(! vid) return;
        vid.Stop();
    };
    this._playerReady = function () {
        if(this._isReady) return; 
        Conviva.log("Player "+this._playerObjId+" is ready");
        this._isReady = true;
        if(this._urlPlaying) {
            this._actualPlay(this._urlPlaying);
        }
    };
    this._constructor (playerHostId, options);
} catch(e) {
    _CP.bug("Conviva.SilverlightPlayer", e);
}
};
Conviva_SilverlightLoaded = function (sender, userContext, args) {
try {    
    Conviva.log("SilverlightLoaded");
    var player = _CP.players[userContext];
    if(! player)
        return; 
    player._playerReady ();
} catch(e) {
    _CP.bug("Conviva_SilverlightLoaded", e);
}
};
Conviva_SilverlightError = function (sender, args) {
try {
    var msg = Silverlight.default_error_handler(sender, args);
    Conviva.log(msg);
    alert(msg);
} catch(e) {
    _CP.bug("Conviva_SilverlightError", e);
}
};
Conviva_SilverlightCurrentStateChanged = function (sender, args) {
try {
    var id = null;
    try {
        id = sender.getHost().id;
    } catch(e) { }
    if(! id) return;
    var player = _CP.players[id];
    var vid = sender.findName("media");
    var sState = vid.CurrentState; 
    var cState = 0;
    if(sState == 'Playing') {
        cState = 3;
    } else if(sState == 'Buffering') {
        cState = 6;
    } else {
        Conviva.log("Unexpected Silverlight state: "+sState);
    }
    if(cState && player) {
        player._onPlayStateChange(cState);
    }
} catch(e) {
    _CP.bug("Conviva_SilverlightCurrentStateChanged", e);
}
};
_CP.checkIfSilverlightPlayerReady = function (playerId) {
try {
    var player = _CP.players[playerId];
    var ready = false;
    if (!player) {
        return;
    }
    do {
        var obj = player.getEmbeddedPlayer();
        if(! obj) break;
        Conviva.log("ConvivaSilverlight.isLoaded = "+obj.isLoaded);
        var cont = obj.content;
        if(! cont) {
            Conviva.log("Cannot find obj.content");
            break;
        }
        var vid = cont.findName("media");
        if(! vid) {
            Conviva.log("ConvivaSilverlightPlayer: cannot find media element");
            break;
        }
        player._playerReady();
        return;
    } while(0);
    setTimeout(function () { _CP.checkIfSilverlightPlayerReady(playerId); }, 1000);
} catch(e) {
    _CP.bug("checkIfSilverligthPlayerReady", e);
}
};
var slPlugin;
var slMain;
var updateTimeCodesInt;
var controlsTimer;
var checkMediaInt;
var objsArr=new Array();
var _root_xmouse=0;
var _root_ymouse=0;
function initSilverlightPlayer(s) {
try {
    Conviva.log("initSilverlightPlayer");
	slMain=s.findName("mainCanvas");
	slMain.opacity=0;
	slPlugin = s.getHost();
	objsArr["volumeSlider"] = new Object();
	objsArr["volumeSlider"].el = s.findName("volumeSlider");
} catch(e) {
    _CP.bug("initSilverlightPlayer", e);
}
};
function Conviva_SilverlightMediaLoaded(s){ 
try {
    s.getHost().content.onfullScreenChange = Conviva_SilverlightOnFullScreenChanged;
	video_controls_height=0;
	var s=slMain.findName("media");
	var sourceWidth = s.width;
	var sourceHeight = s.height;
	var targetWidth = slPlugin.content.actualWidth;
	var targetHeight = slPlugin.content.actualHeight;
	var sourceWidthNatural = s.NaturalVideoWidth;
	var sourceHeightNatural = s.NaturalVideoHeight;
	var video_ratio=sourceWidthNatural/sourceHeightNatural;
	var display_ratio=targetWidth/(targetHeight-video_controls_height);
	vbg=s.findName("videoBG");
	pc=s.findName("PlayControls");
	vc=s.findName("volumeControl");
	me=s.findName("media");
	bmbg=s.findName("bufferMsgBG");
	if(sourceWidthNatural==0 || sourceHeightNatural==0 ) {
		me.width=targetWidth;
		me.height=targetHeight;
		me["Canvas.Left"]=0;
		me["Canvas.Top"]=(targetHeight-video_controls_height)/2-me.height/2;
        }
	else {
            if(display_ratio>video_ratio) {
		me.width=targetWidth*(sourceWidthNatural/sourceHeightNatural);
		me.height=(targetHeight);
		me["Canvas.Left"]=targetWidth/2-me.width/2;
		me["Canvas.Top"]=0;
	    }
	    else {
		me.width=targetWidth;
		me.height=targetWidth/(sourceWidthNatural/sourceHeightNatural);
		me["Canvas.Left"]=0;
		me["Canvas.Top"]=(targetHeight-video_controls_height)/2-me.height/2;
	    }
        }
	pc["Canvas.Top"]=targetHeight-video_controls_height-50;
	vbg.width=targetWidth;
	vbg.height=targetHeight-video_controls_height;
	bmbg.width=targetWidth;
	bmbg.height=targetHeight;
	new_full_bar_width=targetWidth-240;
	slMain.findName("PlayBG").width=targetWidth-57;
	s.findName("ToBeLoadedPath").width=new_full_bar_width;
	s.findName("LoadedPath").width= new_full_bar_width * me.downloadProgress;
	vc["Canvas.Left"]=new_full_bar_width+60;
	objsArr["volumeSlider"].world_offset=32+vc["Canvas.Left"];  
	slMain.opacity=1;
} catch(e) {
    _CP.bug("Conviva_SilverlightMediaLoaded", e);
}
};
function Conviva_SilverlightCanvasMouseLeave(s) {
try {
    clearInterval(mouseCheckerVolumeInt);
    s.releaseMouseCapture();
    slMain.findName("PlayControls").opacity = 0;
} catch(e) {
    _CP.bug("Conviva_SilverlightCanvasMouseLeave", e);
}
};
function Conviva_SilverlightMouseMove(s,e) {
try {
    var pt = e.getPosition(null);
    _root_xmouse = pt.x;
    _root_ymouse = pt.y;
    s.findName("PlayControls").opacity = 1;
    clearTimeout ( controlsTimer );
    controlsTimer = setTimeout("setSilverlightControlsInvisible()",1000);
} catch(e) {
    _CP.bug("Conviva_SilverlightMouseMove", e);
}
};
function setSilverlightControlsInvisible() {
try {
    clearTimeout ( controlsTimer );
    if(! slPlugin || ! slPlugin.content) return;
    if((_root_ymouse < slPlugin.content.actualHeight-100) ||
       (_root_ymouse > slPlugin.content.actualHeight)) {
        slMain.findName("PlayControls").opacity = 0;
    }
} catch(e) {
    _CP.bug("setSilverlightControlsInvisible", e);
}
};
function Conviva_SilverlightLeftButtonUp() {
try {
    clearInterval(mouseCheckerVolumeInt);
} catch(e) {
    _CP.bug("Conviva_SilverlightLeftButtonUp", e);
}
};
function Conviva_SilverlightPlayPauseButton(s) {
try {
    if(s.findName("PlaySymbol").opacity == 0) {
        s.findName("media").Stop();
        s.findName("PauseSymbol").opacity = 0;
        s.findName("PlaySymbol").opacity = 1;
    }
    else {
        s.findName("media").Play();
        s.findName("PauseSymbol").opacity = 1;
        s.findName("PlaySymbol").opacity = 0;
    }
} catch(e) {
    _CP.bug("Conviva_SilverlightPlayPauseButton", e);
}
};
function Conviva_SilverlightFullScreenButton(s) {
try {
    s.getHost().content.fullScreen = !s.getHost().content.fullScreen;
} catch(e) {
    _CP.bug("Conviva_SilverlightFullScreenButton", e);
}
};
function Conviva_SilverlightOnFullScreenChanged(s) {
try {
    Conviva_SilverlightMediaLoaded(s);
} catch(e) {
    _CP.bug("Conviva_SilverlightOnFullScreenChanged", e);
}
};
var mouseCheckerVolumeInt;
var volume_toggle=1;
var volume_slider_length=70;
function Conviva_SilverlightStartDragVolume(s,e) {
try {
    objsArr[s.name].is_dragging = true;
    mouseCheckerVolumeInt = setInterval("mouseCheckerVolume('"+s.name+"')",10);
    s.captureMouse();
} catch(e) {
    _CP.bug("Conviva_SilverlightStartDragVolume", e);
}
};
function Conviva_SilverlightEndDragVolume(s,e) {
try {
    objsArr[s.name].is_dragging = false;
    if (mouseCheckerVolumeInt != null) {
        clearInterval(mouseCheckerVolumeInt);
        mouseCheckerVolumeInt = null;
    }
    s.releaseMouseCapture();
} catch(e) {
    _CP.bug("Conviva_SilverlightEndDragVolume", e);
}
};
function mouseCheckerVolume(str) {
try {
    var obj = objsArr[str];
    window.status=obj.el["Canvas.Left"];
	if(obj.is_dragging) {
        var pre_check=_root_xmouse-obj.world_offset-obj.el.width/2;
        if(pre_check>0 && pre_check<volume_slider_length) {
            obj.el["Canvas.Left"]=pre_check;
            obj.el.findName("soundWaves").opacity=1;
            obj.el.findName("muteBtn").opacity=1;
            volume_toggle=1;
        } else if(pre_check<=0) {
            volume_toggle=-1;
            obj.el["Canvas.Left"]=0;
            obj.el.findName("soundWaves").opacity=0;
            obj.el.findName("muteBtn").opacity=0.3;
        } else {
            obj.el["Canvas.Left"]=volume_slider_length;
        }
        setVolume(pre_check);
    }
    else {
        if (mouseCheckerVolumeInt != null) {
            clearInterval(mouseCheckerVolumeInt);
            mouseCheckerVolumeInt = null;
        }
        s.releaseMouseCapture();
    }
} catch(e) {
    _CP.bug("mouseCheckerVolume", e);
}
};
function Conviva_SilverlightMuteButtonPress(s) {
try {
    if(volume_toggle>0) {
        s.opacity=0.3;
        s.findName("soundWaves").opacity=0;
        s.findName("volumeSlider")["Canvas.Left"]=0;
        setVolume(0);
    } else {
        s.opacity=1;
        s.findName("soundWaves").opacity=1;
        s.findName("volumeSlider")["Canvas.Left"]=60;
        setVolume(60);
    }
    volume_toggle*=-1;
} catch(e) {
    _CP.bug("Conviva_SilverlightMuteButtonPress", e);
}
};
function setVolume(val) {
try {
    var per=val/volume_slider_length;
    slMain.findName("media").volume=per;
} catch(e) {
    _CP.bug("setVolume", e);
}
};
